Compare commits
88 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3385df4ba3 | |||
| 96b1cabb5a | |||
| 366591f247 | |||
| 241631b884 | |||
| 6c063344a3 | |||
| 2f5b1ce1f2 | |||
| 56b3ac6b0c | |||
| f6603ae76e | |||
| 21ae95b5ed | |||
| ce2e86c045 | |||
| 0f8eb0ec94 | |||
| 2f6d419453 | |||
| f34f9e1607 | |||
| c7dd134fce | |||
| 03cc9c9800 | |||
| de3d247d0d | |||
| ee87bcb8d0 | |||
| aaeea7a7b0 | |||
| 7f17681409 | |||
| d72c18756f | |||
| baf5edca42 | |||
| fefa28ae7a | |||
| a217ddae38 | |||
| 97fcb37761 | |||
| 58ff3870be | |||
| 439a039ff4 | |||
| 049a9ca43c | |||
| f128f2e13a | |||
| 20b8c80aaf | |||
| 8e85c91f15 | |||
| 1ac8d5c258 | |||
| 23cd89e882 | |||
| 47a0ab5f1b | |||
| dc37c54938 | |||
| 2834fac85c | |||
| be77c50b45 | |||
| 40d8c8655e | |||
| 7580319fc8 | |||
| 7a2f0f42a9 | |||
| 4ffd3797b6 | |||
| b42428b068 | |||
| 01d6e71f07 | |||
| 3b246b4f1f | |||
| caf5f954b7 | |||
| edb868f372 | |||
| d9009a2e1e | |||
| 2e0938628c | |||
| 3783505dbd | |||
| 0acee49de2 | |||
| 18e9260705 | |||
| 3f4cf2217f | |||
| bb2f49be37 | |||
| b68af3a48a | |||
| 7eb144e8fe | |||
| 7971a49dcd | |||
| c06cce20df | |||
| 2b0f6dfbed | |||
| c509cb7f87 | |||
| 5807f218b1 | |||
| 1d43ebff3b | |||
| eb92b99a1d | |||
| 4d67b019a6 | |||
| 934a793da3 | |||
| e6abf44bef | |||
| 0ee53fd286 | |||
| 62cdb252ca | |||
| 8f2906fe6f | |||
| e8628508d8 | |||
| 53edec8692 | |||
| a1ea31039e | |||
| ef631e2c0b | |||
| 27dc7a0166 | |||
| e6353f9f4c | |||
| 3bb9c2121d | |||
| 737c6f9f14 | |||
| 8e543cbcc6 | |||
| ea7aad5067 | |||
| 09b52e6b0a | |||
| 078db53ae4 | |||
| 957f4cd024 | |||
| 1ce8d98663 | |||
| 1771cb7ec6 | |||
| b74f188b15 | |||
| 5196f20e47 | |||
| 5d4cd6f654 | |||
| a05717f92d | |||
| 123232592f | |||
| 2cbb994667 |
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) => {
|
||||||
|
|||||||
@@ -2,11 +2,23 @@ import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/
|
|||||||
import { provideHttpClient } from '@angular/common/http';
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
import { provideRouter } from '@angular/router';
|
import { provideRouter } from '@angular/router';
|
||||||
import { routes } from './app.routes';
|
import { routes } from './app.routes';
|
||||||
|
import { IndicadoresService } from './features/indicadores/indicadores.service';
|
||||||
|
import { IndicadoresPeriodos } from './features/indicadores/indicadores-periodos';
|
||||||
|
import { TeaSeguimientoService } from './features/indicadores/tea-seguimiento.service';
|
||||||
|
import { FhirIndicadoresPeriodos, FhirIndicadoresService } from './features/indicadores/indicadores-fhir';
|
||||||
|
import { FhirTeaSeguimientoService } from './features/indicadores/tea-seguimiento-fhir';
|
||||||
|
|
||||||
export const appConfig: ApplicationConfig = {
|
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
|
||||||
|
// (`/<domain>/indicadores/<id>/datos`, `/tea/seguimiento`).
|
||||||
|
{ provide: IndicadoresService, useClass: FhirIndicadoresService },
|
||||||
|
{ provide: IndicadoresPeriodos, useClass: FhirIndicadoresPeriodos },
|
||||||
|
{ provide: TeaSeguimientoService, useClass: FhirTeaSeguimientoService },
|
||||||
]
|
]
|
||||||
};
|
};
|
||||||
|
|||||||
+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
-25
@@ -1,37 +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: 'conectar',
|
path: 'login',
|
||||||
title: 'Conectar datos | ISSSTELEON',
|
title: 'Inicio de sesión | ISSSTELEON',
|
||||||
// Lazy: the workspace (and the ~15 Material modules it uses) only
|
loadComponent: () => import('./auth/login-page').then((m) => m.LoginPage),
|
||||||
// downloads when someone actually opens it.
|
// Sin encabezado ni pie: la pantalla ocupa la ventana completa.
|
||||||
loadComponent: () => import('./connect/components/connect-page/connect-page').then((m) => m.ConnectPage),
|
data: { sinCromo: true },
|
||||||
data: { workspace: true, breadcrumb: 'Conectar datos' },
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'gobernanza',
|
// Todo lo demás vive detrás de la sesión; el guard corre en cada ruta hija.
|
||||||
title: 'Gobernanza de modelos | ISSSTELEON',
|
path: '',
|
||||||
loadComponent: () => import('./governance/components/governance-page/governance-page').then((m) => m.GovernancePage),
|
canActivateChild: [authGuard],
|
||||||
data: { workspace: true, breadcrumb: 'Gobernanza de modelos' },
|
children: [
|
||||||
|
{ path: '', component: Home, title: 'Análisis de información | ISSSTELEON' },
|
||||||
|
{
|
||||||
|
path: 'indicadores/tea-estatus',
|
||||||
|
title: 'Casos por estatus | ISSSTELEON',
|
||||||
|
loadComponent: () => import('./features/indicadores/tea-status-page').then(m => m.TeaStatusPage),
|
||||||
|
canActivate: [dominioGuard],
|
||||||
|
data: { workspace: true, breadcrumb: 'Casos por estatus', dominio: 'tea' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'conectar',
|
||||||
|
title: 'Conectar datos | ISSSTELEON',
|
||||||
|
// Lazy: the workspace (and the ~15 Material modules it uses) only
|
||||||
|
// downloads when someone actually opens it.
|
||||||
|
loadComponent: () => import('./connect/components/connect-page/connect-page').then((m) => m.ConnectPage),
|
||||||
|
data: { workspace: true, breadcrumb: 'Conectar datos' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'gobernanza',
|
||||||
|
title: 'Gobernanza de modelos | ISSSTELEON',
|
||||||
|
loadComponent: () => import('./governance/components/governance-page/governance-page').then((m) => m.GovernancePage),
|
||||||
|
data: { workspace: true, breadcrumb: 'Gobernanza de modelos' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'bitacora',
|
||||||
|
title: 'Bitácora de cargas | ISSSTELEON',
|
||||||
|
loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportsPage),
|
||||||
|
data: { workspace: true, breadcrumb: 'Bitácora de cargas' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'kpis',
|
||||||
|
title: 'Indicadores | ISSSTELEON',
|
||||||
|
loadComponent: () => import('./features/indicadores/kpis-page').then(m => m.KpisPage),
|
||||||
|
// The page reads CaCu's measures: an account of another domain goes to its own.
|
||||||
|
canActivate: [dominioGuard],
|
||||||
|
data: { workspace: true, breadcrumb: 'Indicadores', dominio: 'cacu' },
|
||||||
|
},
|
||||||
|
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
|
||||||
|
...DOMINIOS.map(dominio => ({
|
||||||
|
path: `indicadores/${dominio}`,
|
||||||
|
title: 'Indicadores | ISSSTELEON',
|
||||||
|
data: { workspace: true, breadcrumb: 'Indicadores', dominio },
|
||||||
|
canActivate: [dominioGuard],
|
||||||
|
loadComponent: loadIndicadores,
|
||||||
|
})),
|
||||||
|
{ path: '**', redirectTo: '' },
|
||||||
|
],
|
||||||
},
|
},
|
||||||
{
|
|
||||||
path: '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: '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 : '/';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -85,6 +85,8 @@ export interface PreviewResponse {
|
|||||||
/** Sub-tables the source offers (Excel sheets...), with the options to read each. */
|
/** Sub-tables the source offers (Excel sheets...), with the options to read each. */
|
||||||
tables?: { name: string; options: Record<string, unknown>; kind: string }[];
|
tables?: { name: string; options: Record<string, unknown>; kind: string }[];
|
||||||
source_metadata?: Record<string, unknown>;
|
source_metadata?: Record<string, unknown>;
|
||||||
|
/** Columns whose sampled cells hold files (PDF, images) that can be read as documents. */
|
||||||
|
document_columns?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface FileOptions {
|
export interface FileOptions {
|
||||||
@@ -134,6 +136,56 @@ export interface ImportSourcePayload extends SourceLocator {
|
|||||||
label?: string;
|
label?: string;
|
||||||
column_mapping: Record<string, string>;
|
column_mapping: Record<string, string>;
|
||||||
defaults?: Record<string, unknown>;
|
defaults?: Record<string, unknown>;
|
||||||
|
derived?: Record<string, DerivationRule>;
|
||||||
|
documents?: DocumentColumnsConfig;
|
||||||
|
/** Also store, on the patient, captions the documents print that the project's catalog already knows. */
|
||||||
|
catalog_fallback?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Derived fields and document columns
|
||||||
|
|
||||||
|
export type DerivationParamKind = 'column' | 'columns' | 'text' | 'integer' | 'mapping' | 'boolean';
|
||||||
|
|
||||||
|
export interface DerivationParam {
|
||||||
|
name: string;
|
||||||
|
kind: DerivationParamKind;
|
||||||
|
label: string;
|
||||||
|
required: boolean;
|
||||||
|
default: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One operation a derived field may use, as `/imports/derivations` lists it. */
|
||||||
|
export interface DerivationSpec {
|
||||||
|
op: string;
|
||||||
|
label: string;
|
||||||
|
description: string;
|
||||||
|
params: DerivationParam[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DerivationCatalog {
|
||||||
|
derivations: DerivationSpec[];
|
||||||
|
cases: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `{op, ...params, case?}`: how one target field is computed from source columns. */
|
||||||
|
export type DerivationRule = { op: string; case?: string } & Record<string, unknown>;
|
||||||
|
|
||||||
|
/** A grouping or naming given as a column, a list of columns or a rule. */
|
||||||
|
export type ColumnRule = string | string[] | DerivationRule;
|
||||||
|
|
||||||
|
/** Which columns of a source hold documents, and how their records are formed. */
|
||||||
|
export interface DocumentColumnsConfig {
|
||||||
|
columns: string[];
|
||||||
|
group_by?: ColumnRule;
|
||||||
|
name_by?: ColumnRule;
|
||||||
|
file_field?: string;
|
||||||
|
segmentation?: string;
|
||||||
|
pages_per_record?: number;
|
||||||
|
ocr_mode?: OcrMode;
|
||||||
|
key_pattern?: string;
|
||||||
|
include_pattern?: string;
|
||||||
|
exclude_pattern?: string;
|
||||||
|
overrides?: Record<string, Record<string, unknown>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clinical documents
|
// Clinical documents
|
||||||
@@ -145,13 +197,19 @@ export interface DocumentSettings {
|
|||||||
pages_per_record: number;
|
pages_per_record: number;
|
||||||
ocr_mode: OcrMode;
|
ocr_mode: OcrMode;
|
||||||
key_pattern: string;
|
key_pattern: string;
|
||||||
|
/** Only documents whose text matches (regular expression, case and accents ignored). */
|
||||||
|
include_pattern?: string;
|
||||||
|
/** Documents whose text matches are left out. */
|
||||||
|
exclude_pattern?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ExtractedField {
|
export interface ExtractedField {
|
||||||
value: unknown;
|
value: unknown;
|
||||||
confidence: number;
|
confidence: number;
|
||||||
/** etiqueta | patron | texto_libre | manual */
|
/** etiqueta | patron | texto_libre | medicion | columna_fuente | manual */
|
||||||
method: string;
|
method: string;
|
||||||
|
/** What the report says about the mention: afirmado, negado, incierto, hipotetico, historico, presuntivo. */
|
||||||
|
assertion?: string | null;
|
||||||
raw?: string;
|
raw?: string;
|
||||||
document?: string;
|
document?: string;
|
||||||
page_number?: number;
|
page_number?: number;
|
||||||
@@ -175,6 +233,10 @@ export interface ExtractedRecord {
|
|||||||
conflicts: { field: string; kept: ExtractedField; discarded: ExtractedField }[];
|
conflicts: { field: string; kept: ExtractedField; discarded: ExtractedField }[];
|
||||||
sources: { document: string; page_numbers: number[] }[];
|
sources: { document: string; page_numbers: number[] }[];
|
||||||
images: DocumentImage[];
|
images: DocumentImage[];
|
||||||
|
/** `false` when the pages only name another kind of study than the target's; `null` when they name none. */
|
||||||
|
on_topic?: boolean | null;
|
||||||
|
/** Per field, the other values the extractors proposed, best first. */
|
||||||
|
alternatives?: Record<string, ExtractedField[]>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DocumentFieldSpec {
|
export interface DocumentFieldSpec {
|
||||||
@@ -188,6 +250,8 @@ export interface DocumentExtraction extends PreviewResponse {
|
|||||||
key_field: string | null;
|
key_field: string | null;
|
||||||
fields: DocumentFieldSpec[];
|
fields: DocumentFieldSpec[];
|
||||||
records: ExtractedRecord[];
|
records: ExtractedRecord[];
|
||||||
|
/** The extraction code's version and its ranker's, as stored with each row. */
|
||||||
|
nlp_version?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RowError {
|
export interface RowError {
|
||||||
|
|||||||
@@ -1,12 +1,41 @@
|
|||||||
import { HttpClient } from '@angular/common/http';
|
import { HttpClient } from '@angular/common/http';
|
||||||
import { Injectable, inject } from '@angular/core';
|
import { Injectable, inject } from '@angular/core';
|
||||||
import { Observable } from 'rxjs';
|
import { Observable, shareReplay } from 'rxjs';
|
||||||
import { BatchResult, ConflictStrategy, ImportSourcePayload, ValidationResult } from './api.types';
|
import {
|
||||||
|
BatchResult,
|
||||||
|
ConflictStrategy,
|
||||||
|
DerivationCatalog,
|
||||||
|
ImportSourcePayload,
|
||||||
|
PreviewResponse,
|
||||||
|
Row,
|
||||||
|
ValidationResult,
|
||||||
|
} from './api.types';
|
||||||
|
|
||||||
/** POST /imports/validate (one source, writes nothing) and POST /imports/commit (a batch, one transaction). */
|
/**
|
||||||
|
* POST /imports/validate (one source, writes nothing), POST /imports/commit
|
||||||
|
* (a batch, one transaction), the rows a source would write
|
||||||
|
* (POST /imports/mapped-preview), the columns documents add to a source
|
||||||
|
* (POST /imports/sources/document/columns) and the operations derived
|
||||||
|
* fields may use (GET /imports/derivations, fetched once).
|
||||||
|
*/
|
||||||
@Injectable({ providedIn: 'root' })
|
@Injectable({ providedIn: 'root' })
|
||||||
export class ImportsApi {
|
export class ImportsApi {
|
||||||
private readonly http = inject(HttpClient);
|
private readonly http = inject(HttpClient);
|
||||||
|
private catalog?: Observable<DerivationCatalog>;
|
||||||
|
|
||||||
|
derivations(): Observable<DerivationCatalog> {
|
||||||
|
this.catalog ??= this.http.get<DerivationCatalog>('/imports/derivations').pipe(shareReplay(1));
|
||||||
|
return this.catalog;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A source with document columns: its own columns plus every field and caption its documents print. */
|
||||||
|
documentColumns(source: ImportSourcePayload): Observable<PreviewResponse> {
|
||||||
|
return this.http.post<PreviewResponse>('/imports/sources/document/columns', { source });
|
||||||
|
}
|
||||||
|
|
||||||
|
mappedPreview(source: ImportSourcePayload, limit = 20): Observable<{ rows: Row[] }> {
|
||||||
|
return this.http.post<{ rows: Row[] }>('/imports/mapped-preview', { source, limit });
|
||||||
|
}
|
||||||
|
|
||||||
validate(source: ImportSourcePayload): Observable<ValidationResult> {
|
validate(source: ImportSourcePayload): Observable<ValidationResult> {
|
||||||
return this.http.post<ValidationResult>('/imports/validate', { source });
|
return this.http.post<ValidationResult>('/imports/validate', { source });
|
||||||
|
|||||||
@@ -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);
|
||||||
|
|
||||||
|
|||||||
@@ -85,6 +85,31 @@
|
|||||||
</mat-form-field>
|
</mat-form-field>
|
||||||
</form>
|
</form>
|
||||||
} @else {
|
} @else {
|
||||||
|
@if (savedConnections().length) {
|
||||||
|
<div class="saved-connections">
|
||||||
|
<span class="saved-connections__label">Conexiones guardadas</span>
|
||||||
|
<div class="saved-connections__list">
|
||||||
|
@for (saved of savedConnections(); track saved.id) {
|
||||||
|
<div class="saved-connection">
|
||||||
|
<button type="button" class="saved-connection__pick" matRipple (click)="applySaved(saved)">
|
||||||
|
<mat-icon aria-hidden="true">storage</mat-icon>
|
||||||
|
<span>{{ saved.label }}</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
mat-icon-button
|
||||||
|
type="button"
|
||||||
|
class="saved-connection__forget"
|
||||||
|
(click)="forgetSaved(saved, $event)"
|
||||||
|
aria-label="Eliminar esta conexión guardada"
|
||||||
|
matTooltip="Eliminar"
|
||||||
|
>
|
||||||
|
<mat-icon aria-hidden="true">close</mat-icon>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
<form [formGroup]="serverForm" class="db-form" (ngSubmit)="connectDatabase()">
|
<form [formGroup]="serverForm" class="db-form" (ngSubmit)="connectDatabase()">
|
||||||
<mat-form-field appearance="outline" class="db-form__host">
|
<mat-form-field appearance="outline" class="db-form__host">
|
||||||
<mat-label>Servidor</mat-label>
|
<mat-label>Servidor</mat-label>
|
||||||
@@ -108,6 +133,9 @@
|
|||||||
<input matInput type="password" formControlName="password" autocomplete="new-password" />
|
<input matInput type="password" formControlName="password" autocomplete="new-password" />
|
||||||
</mat-form-field>
|
</mat-form-field>
|
||||||
</form>
|
</form>
|
||||||
|
<mat-checkbox [checked]="remember()" (change)="remember.set($event.checked)">
|
||||||
|
Guardar servidor, usuario y base de datos para conexiones futuras (la contraseña no se guarda)
|
||||||
|
</mat-checkbox>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (testing()) {
|
@if (testing()) {
|
||||||
|
|||||||
@@ -80,6 +80,62 @@
|
|||||||
color: var(--mat-sys-on-surface-variant);
|
color: var(--mat-sys-on-surface-variant);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.saved-connections {
|
||||||
|
margin-bottom: var(--space-4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.saved-connections__label {
|
||||||
|
color: var(--mat-sys-on-surface-variant);
|
||||||
|
display: block;
|
||||||
|
font: var(--mat-sys-label-small);
|
||||||
|
margin-bottom: var(--space-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.saved-connections__list {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: var(--space-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.saved-connection {
|
||||||
|
align-items: center;
|
||||||
|
background: var(--mat-sys-surface-variant);
|
||||||
|
border-radius: var(--mat-sys-corner-full);
|
||||||
|
display: flex;
|
||||||
|
gap: var(--space-1);
|
||||||
|
padding-right: var(--space-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.saved-connection__pick {
|
||||||
|
align-items: center;
|
||||||
|
background: none;
|
||||||
|
border: 0;
|
||||||
|
color: var(--mat-sys-on-surface-variant);
|
||||||
|
cursor: pointer;
|
||||||
|
display: flex;
|
||||||
|
font: var(--mat-sys-body-small);
|
||||||
|
gap: var(--space-1);
|
||||||
|
padding: var(--space-1) 0 var(--space-1) var(--space-3);
|
||||||
|
|
||||||
|
mat-icon {
|
||||||
|
font-size: 18px;
|
||||||
|
height: 18px;
|
||||||
|
width: 18px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.saved-connection__forget {
|
||||||
|
--mdc-icon-button-state-layer-size: 28px;
|
||||||
|
height: 28px;
|
||||||
|
width: 28px;
|
||||||
|
|
||||||
|
mat-icon {
|
||||||
|
font-size: 16px;
|
||||||
|
height: 16px;
|
||||||
|
width: 16px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.db-form {
|
.db-form {
|
||||||
display: grid;
|
display: grid;
|
||||||
gap: 0 var(--space-4);
|
gap: 0 var(--space-4);
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Component, computed, inject, signal } from '@angular/core';
|
import { Component, computed, inject, signal } from '@angular/core';
|
||||||
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
|
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatCheckboxModule } from '@angular/material/checkbox';
|
||||||
import { MatDialogModule, MatDialogRef } from '@angular/material/dialog';
|
import { MatDialogModule, MatDialogRef } from '@angular/material/dialog';
|
||||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||||
import { MatIconModule } from '@angular/material/icon';
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
@@ -17,6 +18,7 @@ import { SourceGateway } from '../../api/source-gateway';
|
|||||||
import { connectionsFor } from '../../domain/connection-registry';
|
import { connectionsFor } from '../../domain/connection-registry';
|
||||||
import { GALLERY_CATEGORIES, GalleryCategory, GalleryEntry, galleryEntries } from '../../domain/connector-catalog';
|
import { GALLERY_CATEGORIES, GalleryCategory, GalleryEntry, galleryEntries } from '../../domain/connector-catalog';
|
||||||
import { DataConnection } from '../../domain/data-source';
|
import { DataConnection } from '../../domain/data-source';
|
||||||
|
import { SavedSqlConnection, listSavedSqlConnections, removeSqlConnection, saveSqlConnection } from '../../domain/saved-sql-connections';
|
||||||
import { SqlConnection } from '../../domain/sql-source';
|
import { SqlConnection } from '../../domain/sql-source';
|
||||||
import { describeSqlServer, describeSqlUrl } from '../../domain/sql-url';
|
import { describeSqlServer, describeSqlUrl } from '../../domain/sql-url';
|
||||||
import { FileDropzone } from '../file-dropzone/file-dropzone';
|
import { FileDropzone } from '../file-dropzone/file-dropzone';
|
||||||
@@ -33,6 +35,7 @@ type View = 'catalog' | 'files' | 'database';
|
|||||||
imports: [
|
imports: [
|
||||||
FileDropzone,
|
FileDropzone,
|
||||||
MatButtonModule,
|
MatButtonModule,
|
||||||
|
MatCheckboxModule,
|
||||||
MatDialogModule,
|
MatDialogModule,
|
||||||
MatFormFieldModule,
|
MatFormFieldModule,
|
||||||
MatIconModule,
|
MatIconModule,
|
||||||
@@ -95,6 +98,7 @@ export class ConnectorGalleryDialog {
|
|||||||
readonly urlForm = this.formBuilder.nonNullable.group({ url: ['', Validators.required] });
|
readonly urlForm = this.formBuilder.nonNullable.group({ url: ['', Validators.required] });
|
||||||
readonly testing = signal(false);
|
readonly testing = signal(false);
|
||||||
readonly testResult = signal<{ ok: boolean; message: string } | null>(null);
|
readonly testResult = signal<{ ok: boolean; message: string } | null>(null);
|
||||||
|
readonly remember = signal(false);
|
||||||
|
|
||||||
readonly engine = computed(() => this.entry()?.engine ?? null);
|
readonly engine = computed(() => this.entry()?.engine ?? null);
|
||||||
readonly serverEngine = computed(() => {
|
readonly serverEngine = computed(() => {
|
||||||
@@ -102,10 +106,29 @@ export class ConnectorGalleryDialog {
|
|||||||
return engine && engine !== 'url' ? engine : null;
|
return engine && engine !== 'url' ? engine : null;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
private readonly savedConnectionsAll = signal(listSavedSqlConnections());
|
||||||
|
/** Only the ones for the engine currently picked, so a saved SQL Server entry never fills a MySQL form. */
|
||||||
|
readonly savedConnections = computed(() => {
|
||||||
|
const engineId = this.serverEngine()?.id;
|
||||||
|
return engineId ? this.savedConnectionsAll().filter((saved) => saved.engine === engineId) : [];
|
||||||
|
});
|
||||||
|
|
||||||
|
applySaved(saved: SavedSqlConnection): void {
|
||||||
|
this.serverForm.patchValue({ host: saved.host, port: saved.port, database: saved.database, user: saved.user });
|
||||||
|
this.testResult.set(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
forgetSaved(saved: SavedSqlConnection, event: Event): void {
|
||||||
|
event.stopPropagation();
|
||||||
|
removeSqlConnection(saved.id);
|
||||||
|
this.savedConnectionsAll.set(listSavedSqlConnections());
|
||||||
|
}
|
||||||
|
|
||||||
pick(entry: GalleryEntry): void {
|
pick(entry: GalleryEntry): void {
|
||||||
if (!entry.available) return;
|
if (!entry.available) return;
|
||||||
this.entry.set(entry);
|
this.entry.set(entry);
|
||||||
this.testResult.set(null);
|
this.testResult.set(null);
|
||||||
|
this.remember.set(false);
|
||||||
this.view.set(entry.engine ? 'database' : 'files');
|
this.view.set(entry.engine ? 'database' : 'files');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,6 +166,10 @@ export class ConnectorGalleryDialog {
|
|||||||
connectDatabase(): void {
|
connectDatabase(): void {
|
||||||
const ref = this.connectionRef();
|
const ref = this.connectionRef();
|
||||||
if (!ref) return;
|
if (!ref) return;
|
||||||
|
if (this.remember() && 'server' in ref) {
|
||||||
|
const { password: _password, ...shape } = ref.server;
|
||||||
|
saveSqlConnection({ label: this.connectionLabel(), ...shape });
|
||||||
|
}
|
||||||
this.dialogRef.close([new SqlConnection(ref, this.connectionLabel(), this.serverEngine()?.default_schema ?? undefined)]);
|
this.dialogRef.close([new SqlConnection(ref, this.connectionLabel(), this.serverEngine()?.default_schema ?? undefined)]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -33,6 +33,15 @@
|
|||||||
/>
|
/>
|
||||||
<mat-hint>Expresión regular; ayuda a encontrar el expediente sin etiqueta.</mat-hint>
|
<mat-hint>Expresión regular; ayuda a encontrar el expediente sin etiqueta.</mat-hint>
|
||||||
</mat-form-field>
|
</mat-form-field>
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
|
<mat-label>Solo documentos que digan</mat-label>
|
||||||
|
<input matInput [ngModel]="settings().include_pattern ?? ''" (ngModelChange)="updateSettings({ include_pattern: $event })" />
|
||||||
|
<mat-hint>Expresión regular; sin distinguir mayúsculas ni acentos.</mat-hint>
|
||||||
|
</mat-form-field>
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
|
<mat-label>Omitir documentos que digan</mat-label>
|
||||||
|
<input matInput [ngModel]="settings().exclude_pattern ?? ''" (ngModelChange)="updateSettings({ exclude_pattern: $event })" />
|
||||||
|
</mat-form-field>
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
<mat-label>OCR</mat-label>
|
<mat-label>OCR</mat-label>
|
||||||
<mat-select [value]="settings().ocr_mode" (valueChange)="updateSettings({ ocr_mode: $event })">
|
<mat-select [value]="settings().ocr_mode" (valueChange)="updateSettings({ ocr_mode: $event })">
|
||||||
@@ -89,6 +98,12 @@
|
|||||||
Confianza mínima {{ record.confidence | percent }}
|
Confianza mínima {{ record.confidence | percent }}
|
||||||
</span>
|
</span>
|
||||||
</header>
|
</header>
|
||||||
|
@if (record.on_topic === false) {
|
||||||
|
<p class="record__off-topic" role="status">
|
||||||
|
<mat-icon aria-hidden="true">report</mat-icon>
|
||||||
|
Sus páginas mencionan otro tipo de estudio y no el de este destino; sus valores quedan vacíos para que los revise.
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
|
||||||
<table class="fields" aria-label="Campos extraídos">
|
<table class="fields" aria-label="Campos extraídos">
|
||||||
<thead>
|
<thead>
|
||||||
@@ -115,6 +130,21 @@
|
|||||||
(change)="setValue(record, field.name, $any($event.target).value)"
|
(change)="setValue(record, field.name, $any($event.target).value)"
|
||||||
[attr.aria-label]="'Valor de ' + field.name"
|
[attr.aria-label]="'Valor de ' + field.name"
|
||||||
/>
|
/>
|
||||||
|
@if (alternatives(record, field.name).length && !isOverridden(record, field.name)) {
|
||||||
|
<span class="fields__alternatives">
|
||||||
|
También:
|
||||||
|
@for (alternative of alternatives(record, field.name); track $index) {
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="fields__alternative"
|
||||||
|
(click)="pick(record, field.name, alternative)"
|
||||||
|
[matTooltip]="(methodLabels[alternative.method] ?? alternative.method) + ' · ' + (alternative.confidence | percent) + (alternative.line ? ' · “' + alternative.line + '”' : '')"
|
||||||
|
>
|
||||||
|
{{ alternative.value }}
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
@if (conflict) {
|
@if (conflict) {
|
||||||
<span class="fields__conflict" [matTooltip]="'Otro documento dice: ' + conflict.discarded.value + ' (' + conflict.discarded.document + ' p. ' + conflict.discarded.page_number + ')'">
|
<span class="fields__conflict" [matTooltip]="'Otro documento dice: ' + conflict.discarded.value + ' (' + conflict.discarded.document + ' p. ' + conflict.discarded.page_number + ')'">
|
||||||
<mat-icon aria-hidden="true">compare_arrows</mat-icon>difiere
|
<mat-icon aria-hidden="true">compare_arrows</mat-icon>difiere
|
||||||
@@ -132,6 +162,9 @@
|
|||||||
[attr.aria-label]="'Confianza ' + (found.confidence | percent)"
|
[attr.aria-label]="'Confianza ' + (found.confidence | percent)"
|
||||||
></mat-progress-bar>
|
></mat-progress-bar>
|
||||||
<span class="method">{{ methodLabels[found.method] ?? found.method }} · {{ found.confidence | percent }}</span>
|
<span class="method">{{ methodLabels[found.method] ?? found.method }} · {{ found.confidence | percent }}</span>
|
||||||
|
@if (found.assertion && assertionLabels[found.assertion]) {
|
||||||
|
<span class="method method--assertion">{{ assertionLabels[found.assertion] }}</span>
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</td>
|
</td>
|
||||||
<td class="fields__evidence">
|
<td class="fields__evidence">
|
||||||
|
|||||||
@@ -133,6 +133,47 @@
|
|||||||
background: color-mix(in srgb, var(--mat-sys-primary) 8%, transparent);
|
background: color-mix(in srgb, var(--mat-sys-primary) 8%, transparent);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.fields__alternatives {
|
||||||
|
align-items: center;
|
||||||
|
color: var(--mat-sys-on-surface-variant);
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
font: var(--mat-sys-label-small);
|
||||||
|
gap: 4px;
|
||||||
|
margin-top: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.fields__alternative {
|
||||||
|
background: var(--mat-sys-surface-container-high);
|
||||||
|
border: 0;
|
||||||
|
border-radius: 999px;
|
||||||
|
color: var(--mat-sys-on-surface);
|
||||||
|
cursor: pointer;
|
||||||
|
font: var(--mat-sys-label-small);
|
||||||
|
padding: 1px 8px;
|
||||||
|
|
||||||
|
&:hover,
|
||||||
|
&:focus-visible {
|
||||||
|
background: var(--mat-sys-secondary-container);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.method--assertion {
|
||||||
|
color: var(--mat-sys-tertiary);
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.record__off-topic {
|
||||||
|
align-items: center;
|
||||||
|
background: var(--mat-sys-error-container);
|
||||||
|
color: var(--mat-sys-on-error-container);
|
||||||
|
display: flex;
|
||||||
|
font: var(--mat-sys-body-small);
|
||||||
|
gap: var(--space-2);
|
||||||
|
margin: 0 0 var(--space-2);
|
||||||
|
padding: var(--space-2) var(--space-3);
|
||||||
|
}
|
||||||
|
|
||||||
.fields__conflict {
|
.fields__conflict {
|
||||||
align-items: center;
|
align-items: center;
|
||||||
color: var(--mat-sys-error);
|
color: var(--mat-sys-error);
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import { signal } from '@angular/core';
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
|
||||||
|
import { SourceGateway } from '../../api/source-gateway';
|
||||||
|
import { DocumentExtraction, ExtractedRecord } from '../../api/api.types';
|
||||||
|
import { DocumentReviewDialog } from './document-review-dialog';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The review of extracted documents: the other readings the extractors proposed can be picked as a correction, a
|
||||||
|
* record whose pages name another kind of study asks for review, and a qualified mention shows how it was qualified.
|
||||||
|
* The table is a stub holding one extraction already made, so no request is sent; the gateway is never called.
|
||||||
|
*/
|
||||||
|
describe('DocumentReviewDialog', () => {
|
||||||
|
const record: ExtractedRecord = {
|
||||||
|
index: 0,
|
||||||
|
key: 'K-1',
|
||||||
|
confidence: 0.9,
|
||||||
|
fields: { bx_cin_grado: { value: 'LIEAG', confidence: 0.9, method: 'texto_libre', assertion: 'presuntivo' } },
|
||||||
|
missing: [],
|
||||||
|
conflicts: [],
|
||||||
|
sources: [{ document: 'a.pdf', page_numbers: [1] }],
|
||||||
|
images: [],
|
||||||
|
on_topic: true,
|
||||||
|
alternatives: { bx_cin_grado: [{ value: 'LIEBG', confidence: 0.7, method: 'etiqueta', line: 'Diagnóstico: NIC I' }] },
|
||||||
|
};
|
||||||
|
|
||||||
|
function open(records: ExtractedRecord[]) {
|
||||||
|
const extraction = { key_field: 'pac_id_hospital', fields: [{ name: 'bx_cin_grado', kind: 'choice', required: false, labels: [] }], records } as unknown as DocumentExtraction;
|
||||||
|
const table = {
|
||||||
|
settings: () => ({}),
|
||||||
|
overrides: () => ({}),
|
||||||
|
extractions: signal({ biopsia: extraction }),
|
||||||
|
configure: vi.fn(),
|
||||||
|
};
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
imports: [DocumentReviewDialog],
|
||||||
|
providers: [
|
||||||
|
{ provide: MAT_DIALOG_DATA, useValue: { table, target: { key: 'biopsia', domain: 'cacu', table: 'biopsia_cervical' }, segmentations: [] } },
|
||||||
|
{ provide: MatDialogRef, useValue: { close: vi.fn() } },
|
||||||
|
{ provide: SourceGateway, useValue: {} },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const fixture = TestBed.createComponent(DocumentReviewDialog);
|
||||||
|
fixture.detectChanges();
|
||||||
|
return fixture;
|
||||||
|
}
|
||||||
|
|
||||||
|
it('picks another reading as the correction', () => {
|
||||||
|
// Fails if the alternatives stop being offered or picking one stops recording it as an override.
|
||||||
|
const fixture = open([record]);
|
||||||
|
const dialog = fixture.componentInstance;
|
||||||
|
const [alternative] = dialog.alternatives(record, 'bx_cin_grado');
|
||||||
|
dialog.pick(record, 'bx_cin_grado', alternative);
|
||||||
|
expect(dialog.value(record, 'bx_cin_grado')).toBe('LIEBG');
|
||||||
|
expect(dialog.isOverridden(record, 'bx_cin_grado')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows how a mention was qualified and asks to review off-topic records', () => {
|
||||||
|
// Fails if the assertion label or the off-topic warning disappear from the page.
|
||||||
|
const fixture = open([record, { ...record, index: 1, on_topic: false }]);
|
||||||
|
expect(fixture.nativeElement.textContent).toContain('Presuntivo');
|
||||||
|
expect(fixture.componentInstance.needsReview()).toBe(1);
|
||||||
|
fixture.componentInstance.select(1);
|
||||||
|
fixture.detectChanges();
|
||||||
|
expect(fixture.nativeElement.textContent).toContain('otro tipo de estudio');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -33,9 +33,19 @@ const METHOD_LABELS: Record<string, string> = {
|
|||||||
etiqueta: 'Etiqueta',
|
etiqueta: 'Etiqueta',
|
||||||
patron: 'Patrón',
|
patron: 'Patrón',
|
||||||
texto_libre: 'Texto libre',
|
texto_libre: 'Texto libre',
|
||||||
|
medicion: 'Medición',
|
||||||
|
columna_fuente: 'Columna',
|
||||||
manual: 'Manual',
|
manual: 'Manual',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** How a value's mention is qualified, for the ones a reviewer should notice. */
|
||||||
|
const ASSERTION_LABELS: Record<string, string> = {
|
||||||
|
incierto: 'Incierto',
|
||||||
|
hipotetico: 'Hipotético',
|
||||||
|
historico: 'Antecedente',
|
||||||
|
presuntivo: 'Presuntivo',
|
||||||
|
};
|
||||||
|
|
||||||
const REVIEW_BELOW = 0.8;
|
const REVIEW_BELOW = 0.8;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -73,6 +83,7 @@ export class DocumentReviewDialog {
|
|||||||
readonly target = this.data.target;
|
readonly target = this.data.target;
|
||||||
readonly segmentations = this.data.segmentations;
|
readonly segmentations = this.data.segmentations;
|
||||||
readonly methodLabels = METHOD_LABELS;
|
readonly methodLabels = METHOD_LABELS;
|
||||||
|
readonly assertionLabels = ASSERTION_LABELS;
|
||||||
readonly reviewBelow = REVIEW_BELOW;
|
readonly reviewBelow = REVIEW_BELOW;
|
||||||
|
|
||||||
readonly settings = signal<DocumentSettings>({ ...this.table.settings() });
|
readonly settings = signal<DocumentSettings>({ ...this.table.settings() });
|
||||||
@@ -133,7 +144,18 @@ export class DocumentReviewDialog {
|
|||||||
}
|
}
|
||||||
|
|
||||||
recordNeedsReview(record: ExtractedRecord): boolean {
|
recordNeedsReview(record: ExtractedRecord): boolean {
|
||||||
return record.missing.length > 0 || record.conflicts.length > 0 || record.confidence < REVIEW_BELOW;
|
return (
|
||||||
|
record.missing.length > 0 || record.conflicts.length > 0 || record.confidence < REVIEW_BELOW || record.on_topic === false
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
alternatives(record: ExtractedRecord, field: string): ExtractedField[] {
|
||||||
|
return record.alternatives?.[field] ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Takes another reading the extractors proposed; the correction teaches the ranker once imported. */
|
||||||
|
pick(record: ExtractedRecord, field: string, alternative: ExtractedField): void {
|
||||||
|
this.setValue(record, field, alternative.value === null || alternative.value === undefined ? '' : String(alternative.value));
|
||||||
}
|
}
|
||||||
|
|
||||||
extracted(record: ExtractedRecord, field: string): ExtractedField | null {
|
extracted(record: ExtractedRecord, field: string): ExtractedField | null {
|
||||||
|
|||||||
@@ -55,6 +55,15 @@
|
|||||||
</ng-template>
|
</ng-template>
|
||||||
<div class="editor__panel"><app-column-mapper [flow]="f"></app-column-mapper></div>
|
<div class="editor__panel"><app-column-mapper [flow]="f"></app-column-mapper></div>
|
||||||
</mat-tab>
|
</mat-tab>
|
||||||
|
<mat-tab>
|
||||||
|
<ng-template mat-tab-label>
|
||||||
|
<mat-icon aria-hidden="true">functions</mat-icon>Reglas
|
||||||
|
@if (f.documents() || (f.derived() | keyvalue).length) {
|
||||||
|
<span class="tab-count">{{ (f.derived() | keyvalue).length + (f.documents() ? 1 : 0) }}</span>
|
||||||
|
}
|
||||||
|
</ng-template>
|
||||||
|
<div class="editor__panel"><app-mapping-rules [flow]="f"></app-mapping-rules></div>
|
||||||
|
</mat-tab>
|
||||||
<mat-tab>
|
<mat-tab>
|
||||||
<ng-template mat-tab-label><mat-icon aria-hidden="true">table_view</mat-icon>Datos</ng-template>
|
<ng-template mat-tab-label><mat-icon aria-hidden="true">table_view</mat-icon>Datos</ng-template>
|
||||||
<div class="editor__panel"><app-data-grid [flow]="f"></app-data-grid></div>
|
<div class="editor__panel"><app-data-grid [flow]="f"></app-data-grid></div>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { DecimalPipe } from '@angular/common';
|
import { DecimalPipe, KeyValuePipe } from '@angular/common';
|
||||||
import { Component, computed, inject, input, signal } from '@angular/core';
|
import { Component, computed, inject, input, 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';
|
||||||
@@ -13,12 +13,13 @@ import { ConnectWorkspaceStore } from '../../state/connect-workspace.store';
|
|||||||
import { ColumnMapper } from '../column-mapper/column-mapper';
|
import { ColumnMapper } from '../column-mapper/column-mapper';
|
||||||
import { DataGrid } from '../data-grid/data-grid';
|
import { DataGrid } from '../data-grid/data-grid';
|
||||||
import { DocumentReviewData, DocumentReviewDialog } from '../document-review-dialog/document-review-dialog';
|
import { DocumentReviewData, DocumentReviewDialog } from '../document-review-dialog/document-review-dialog';
|
||||||
|
import { MappingRules } from '../mapping-rules/mapping-rules';
|
||||||
import { FlowStatusChip } from '../shared/flow-status';
|
import { FlowStatusChip } from '../shared/flow-status';
|
||||||
import { ValidationReport } from '../validation-report/validation-report';
|
import { ValidationReport } from '../validation-report/validation-report';
|
||||||
|
|
||||||
const VALIDATION_TAB = 2;
|
const VALIDATION_TAB = 3;
|
||||||
|
|
||||||
/** Everything about the selected flow: its mapping, its data, its validation. */
|
/** Everything about the selected flow: its mapping, its rules, its data, its validation. */
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-flow-editor',
|
selector: 'app-flow-editor',
|
||||||
imports: [
|
imports: [
|
||||||
@@ -26,6 +27,8 @@ const VALIDATION_TAB = 2;
|
|||||||
DataGrid,
|
DataGrid,
|
||||||
DecimalPipe,
|
DecimalPipe,
|
||||||
FlowStatusChip,
|
FlowStatusChip,
|
||||||
|
KeyValuePipe,
|
||||||
|
MappingRules,
|
||||||
MatBadgeModule,
|
MatBadgeModule,
|
||||||
MatButtonModule,
|
MatButtonModule,
|
||||||
MatIconModule,
|
MatIconModule,
|
||||||
|
|||||||
@@ -0,0 +1,238 @@
|
|||||||
|
@let f = flow();
|
||||||
|
@let docs = documentForm();
|
||||||
|
<div class="rules">
|
||||||
|
<section class="rules__section" aria-labelledby="documents-title">
|
||||||
|
<header class="rules__header">
|
||||||
|
<h3 id="documents-title"><mat-icon aria-hidden="true">document_scanner</mat-icon>Documentos dentro de columnas</h3>
|
||||||
|
@if (f.documents()) {
|
||||||
|
<span class="rules__badge">Leyendo {{ f.documents()!.columns.length }} columna(s)</span>
|
||||||
|
}
|
||||||
|
</header>
|
||||||
|
<p class="rules__hint">
|
||||||
|
Si alguna columna guarda archivos (PDF o imágenes, como binario, hexadecimal o base64), se leen y todo lo que
|
||||||
|
imprimen (campos conocidos y cualquier otra etiqueta) aparece como columnas nuevas que puede asignar o usar en reglas.
|
||||||
|
Los valores que vienen de columnas de la fuente se respetan por encima de lo que diga el documento.
|
||||||
|
@if (f.documentColumns().length) {
|
||||||
|
Columnas con archivos detectadas: <strong>{{ f.documentColumns().join(', ') }}</strong>.
|
||||||
|
}
|
||||||
|
</p>
|
||||||
|
<div class="rules__grid">
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
|
<mat-label>Columnas con documentos</mat-label>
|
||||||
|
<mat-select multiple [ngModel]="docs.columns" (ngModelChange)="patchDocuments({ columns: $event })">
|
||||||
|
@for (name of columnNames(); track name) {
|
||||||
|
<mat-option [value]="name">{{ name }}@if (f.documentColumns().includes(name)) { (archivo) }</mat-option>
|
||||||
|
}
|
||||||
|
</mat-select>
|
||||||
|
</mat-form-field>
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
|
<mat-label>Agrupar registros por</mat-label>
|
||||||
|
<mat-select [ngModel]="docs.group_by" (ngModelChange)="patchDocuments({ group_by: $event })">
|
||||||
|
<mat-option value="">Por el identificador del paciente</mat-option>
|
||||||
|
@for (name of columnNames(); track name) {
|
||||||
|
<mat-option [value]="name">{{ name }}</mat-option>
|
||||||
|
}
|
||||||
|
</mat-select>
|
||||||
|
<mat-hint>Las filas con el mismo valor forman un solo registro (p. ej. un número de estudio).</mat-hint>
|
||||||
|
</mat-form-field>
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
|
<mat-label>Guardar el documento en</mat-label>
|
||||||
|
<mat-select [ngModel]="docs.file_field" (ngModelChange)="patchDocuments({ file_field: $event })">
|
||||||
|
<mat-option value="">No guardar</mat-option>
|
||||||
|
@for (field of fileFields(); track field.name) {
|
||||||
|
<mat-option [value]="field.name">{{ field.name }}</mat-option>
|
||||||
|
}
|
||||||
|
</mat-select>
|
||||||
|
</mat-form-field>
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
|
<mat-label>OCR</mat-label>
|
||||||
|
<mat-select [ngModel]="docs.ocr_mode" (ngModelChange)="patchDocuments({ ocr_mode: $event })">
|
||||||
|
<mat-option value="auto">Solo páginas escaneadas</mat-option>
|
||||||
|
<mat-option value="always">Todas las páginas</mat-option>
|
||||||
|
<mat-option value="never">Nunca (solo texto del PDF)</mat-option>
|
||||||
|
</mat-select>
|
||||||
|
</mat-form-field>
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
|
<mat-label>Solo documentos que digan</mat-label>
|
||||||
|
<input matInput [ngModel]="docs.include_pattern" (ngModelChange)="patchDocuments({ include_pattern: $event })" />
|
||||||
|
<mat-hint>Expresión regular; sin distinguir mayúsculas ni acentos.</mat-hint>
|
||||||
|
</mat-form-field>
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
|
<mat-label>Omitir documentos que digan</mat-label>
|
||||||
|
<input matInput [ngModel]="docs.exclude_pattern" (ngModelChange)="patchDocuments({ exclude_pattern: $event })" />
|
||||||
|
</mat-form-field>
|
||||||
|
</div>
|
||||||
|
<mat-checkbox [checked]="f.catalogFallback()" (change)="f.setCatalogFallback($event.checked)">
|
||||||
|
Guardar también, en el expediente de cada paciente, las etiquetas de los documentos que el catálogo del proyecto ya
|
||||||
|
conoce
|
||||||
|
</mat-checkbox>
|
||||||
|
<p class="rules__hint">
|
||||||
|
Las etiquetas que nadie usa no se guardan: aparecen, solo con su nombre y cuántos registros las traen, en la
|
||||||
|
Bitácora de cargas.
|
||||||
|
</p>
|
||||||
|
<div class="rules__actions">
|
||||||
|
<button mat-flat-button type="button" [disabled]="documentsBusy()" (click)="applyDocuments()">
|
||||||
|
<mat-icon aria-hidden="true">play_arrow</mat-icon>Leer documentos
|
||||||
|
</button>
|
||||||
|
@if (f.documents()) {
|
||||||
|
<button mat-button type="button" (click)="clearDocuments()">Dejar de leerlos</button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
@if (documentsBusy()) {
|
||||||
|
<mat-progress-bar mode="indeterminate" />
|
||||||
|
}
|
||||||
|
@if (documentsError(); as error) {
|
||||||
|
<p class="rules__error" role="alert">{{ error }}</p>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="rules__section" aria-labelledby="derived-title">
|
||||||
|
<header class="rules__header">
|
||||||
|
<h3 id="derived-title"><mat-icon aria-hidden="true">functions</mat-icon>Campos calculados</h3>
|
||||||
|
</header>
|
||||||
|
<p class="rules__hint">
|
||||||
|
Para cuando las columnas no coinciden una a una con los campos: unir nombre y apellidos, separar un nombre completo,
|
||||||
|
tomar la primera columna con valor, extraer un dato de un texto o traducir códigos. Funciona igual con columnas de la
|
||||||
|
fuente y con lo leído de los documentos.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
@for (item of rules(); track item.field) {
|
||||||
|
<div class="rule">
|
||||||
|
<mat-icon aria-hidden="true">arrow_forward</mat-icon>
|
||||||
|
<strong>{{ item.field }}</strong>
|
||||||
|
<span class="rule__summary">{{ item.summary }}</span>
|
||||||
|
<button mat-icon-button type="button" [attr.aria-label]="'Quitar regla de ' + item.field" (click)="removeRule(item.field)">
|
||||||
|
<mat-icon>delete</mat-icon>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
<div class="rules__grid">
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
|
<mat-label>Campo</mat-label>
|
||||||
|
<mat-select [ngModel]="ruleField()" (ngModelChange)="ruleField.set($event)">
|
||||||
|
@for (field of f.target.fields; track field.name) {
|
||||||
|
<mat-option [value]="field.name">{{ field.name }}@if (field.required) { * }</mat-option>
|
||||||
|
}
|
||||||
|
</mat-select>
|
||||||
|
</mat-form-field>
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
|
<mat-label>Cómo calcularlo</mat-label>
|
||||||
|
<mat-select [ngModel]="ruleOp()" (ngModelChange)="chooseOp($event)">
|
||||||
|
@for (spec of catalog()?.derivations ?? []; track spec.op) {
|
||||||
|
<mat-option [value]="spec.op" [matTooltip]="spec.description">{{ spec.label }}</mat-option>
|
||||||
|
}
|
||||||
|
</mat-select>
|
||||||
|
@if (selectedSpec(); as spec) {
|
||||||
|
<mat-hint>{{ spec.description }}</mat-hint>
|
||||||
|
}
|
||||||
|
</mat-form-field>
|
||||||
|
|
||||||
|
@for (param of selectedSpec()?.params ?? []; track param.name) {
|
||||||
|
@switch (param.kind) {
|
||||||
|
@case ('column') {
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
|
<mat-label>{{ param.label }}</mat-label>
|
||||||
|
<mat-select [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)">
|
||||||
|
@for (name of columnNames(); track name) {
|
||||||
|
<mat-option [value]="name">{{ name }}</mat-option>
|
||||||
|
}
|
||||||
|
</mat-select>
|
||||||
|
</mat-form-field>
|
||||||
|
}
|
||||||
|
@case ('columns') {
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
|
<mat-label>{{ param.label }} (en orden)</mat-label>
|
||||||
|
<mat-select multiple [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)">
|
||||||
|
@for (name of columnNames(); track name) {
|
||||||
|
<mat-option [value]="name">{{ name }}</mat-option>
|
||||||
|
}
|
||||||
|
</mat-select>
|
||||||
|
</mat-form-field>
|
||||||
|
}
|
||||||
|
@case ('integer') {
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
|
<mat-label>{{ param.label }}</mat-label>
|
||||||
|
<input matInput type="number" [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)" />
|
||||||
|
</mat-form-field>
|
||||||
|
}
|
||||||
|
@case ('boolean') {
|
||||||
|
<mat-checkbox [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)">{{ param.label }}</mat-checkbox>
|
||||||
|
}
|
||||||
|
@case ('mapping') {
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="rules__wide">
|
||||||
|
<mat-label>{{ param.label }}</mat-label>
|
||||||
|
<textarea matInput rows="3" placeholder="M = Masculino" [ngModel]="mappingText(param.name)" (ngModelChange)="setMappingText(param.name, $event)"></textarea>
|
||||||
|
<mat-hint>Una equivalencia por línea: valor = nuevo valor.</mat-hint>
|
||||||
|
</mat-form-field>
|
||||||
|
}
|
||||||
|
@default {
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
|
<mat-label>{{ param.label }}</mat-label>
|
||||||
|
<input matInput [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)" />
|
||||||
|
</mat-form-field>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (selectedSpec()) {
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
|
<mat-label>Mayúsculas</mat-label>
|
||||||
|
<mat-select [ngModel]="ruleCase()" (ngModelChange)="ruleCase.set($event)">
|
||||||
|
<mat-option value="">Sin cambio</mat-option>
|
||||||
|
<mat-option value="upper">MAYÚSCULAS</mat-option>
|
||||||
|
<mat-option value="lower">minúsculas</mat-option>
|
||||||
|
<mat-option value="title">Tipo Título</mat-option>
|
||||||
|
</mat-select>
|
||||||
|
</mat-form-field>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div class="rules__actions">
|
||||||
|
<button mat-stroked-button type="button" [disabled]="!ruleField() || !selectedSpec()" (click)="addRule()">
|
||||||
|
<mat-icon aria-hidden="true">add</mat-icon>Agregar regla
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
@if (ruleError(); as error) {
|
||||||
|
<p class="rules__error" role="alert">{{ error }}</p>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="rules__section" aria-labelledby="result-title">
|
||||||
|
<header class="rules__header">
|
||||||
|
<h3 id="result-title"><mat-icon aria-hidden="true">preview</mat-icon>Resultado</h3>
|
||||||
|
<button mat-stroked-button type="button" [disabled]="previewBusy()" (click)="preview()">
|
||||||
|
<mat-icon aria-hidden="true">visibility</mat-icon>Ver cómo quedarían las filas
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
@if (previewBusy()) {
|
||||||
|
<mat-progress-bar mode="indeterminate" />
|
||||||
|
}
|
||||||
|
@if (previewError(); as error) {
|
||||||
|
<p class="rules__error" role="alert">{{ error }}</p>
|
||||||
|
}
|
||||||
|
@if (previewRows(); as rows) {
|
||||||
|
<div class="rules__table-wrap">
|
||||||
|
<table class="rules__table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
@for (column of previewColumns(); track column) {
|
||||||
|
<th scope="col">{{ column }}</th>
|
||||||
|
}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@for (row of rows; track $index) {
|
||||||
|
<tr>
|
||||||
|
@for (column of previewColumns(); track column) {
|
||||||
|
<td>{{ cell(row[column]) }}</td>
|
||||||
|
}
|
||||||
|
</tr>
|
||||||
|
} @empty {
|
||||||
|
<tr><td>La fuente no dio filas.</td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rules {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 24px;
|
||||||
|
padding: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rules__section {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rules__header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
|
||||||
|
h3 {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
margin: 0;
|
||||||
|
font: var(--mat-sys-title-medium);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.rules__badge {
|
||||||
|
font: var(--mat-sys-label-medium);
|
||||||
|
color: var(--mat-sys-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rules__hint {
|
||||||
|
margin: 0;
|
||||||
|
font: var(--mat-sys-body-small);
|
||||||
|
color: var(--mat-sys-on-surface-variant);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rules__grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
|
||||||
|
gap: 12px 16px;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rules__wide {
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rules__actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rules__error {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--mat-sys-error);
|
||||||
|
font: var(--mat-sys-body-medium);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rule {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 4px 8px;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--mat-sys-surface-container);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rule__summary {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
color: var(--mat-sys-on-surface-variant);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rules__table-wrap {
|
||||||
|
overflow-x: auto;
|
||||||
|
max-height: 360px;
|
||||||
|
border: 1px solid var(--mat-sys-outline-variant);
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rules__table {
|
||||||
|
border-collapse: collapse;
|
||||||
|
font: var(--mat-sys-body-small);
|
||||||
|
|
||||||
|
th,
|
||||||
|
td {
|
||||||
|
padding: 4px 8px;
|
||||||
|
border-bottom: 1px solid var(--mat-sys-outline-variant);
|
||||||
|
text-align: left;
|
||||||
|
white-space: nowrap;
|
||||||
|
max-width: 240px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
th {
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
background: var(--mat-sys-surface-container-high);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
import { Component, computed, effect, inject, input, signal } from '@angular/core';
|
||||||
|
import { toSignal } from '@angular/core/rxjs-interop';
|
||||||
|
import { FormsModule } from '@angular/forms';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatCheckboxModule } from '@angular/material/checkbox';
|
||||||
|
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
import { MatInputModule } from '@angular/material/input';
|
||||||
|
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||||
|
import { MatSelectModule } from '@angular/material/select';
|
||||||
|
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||||
|
import { firstValueFrom } from 'rxjs';
|
||||||
|
import {
|
||||||
|
DerivationParam,
|
||||||
|
DerivationRule,
|
||||||
|
DerivationSpec,
|
||||||
|
DocumentColumnsConfig,
|
||||||
|
OcrMode,
|
||||||
|
Row,
|
||||||
|
apiErrorMessage,
|
||||||
|
} from '../../api/api.types';
|
||||||
|
import { ImportsApi } from '../../api/imports.api';
|
||||||
|
import { ImportFlow } from '../../domain/import-flow';
|
||||||
|
|
||||||
|
interface DocumentForm {
|
||||||
|
columns: string[];
|
||||||
|
group_by: string;
|
||||||
|
file_field: string;
|
||||||
|
ocr_mode: OcrMode;
|
||||||
|
include_pattern: string;
|
||||||
|
exclude_pattern: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What a plain column-to-field mapping can't express, for any kind of
|
||||||
|
* source: columns whose cells hold documents (read for every field and
|
||||||
|
* caption they print, which then become columns of their own), target
|
||||||
|
* fields computed from several columns, and a look at the rows as they
|
||||||
|
* would be written.
|
||||||
|
*
|
||||||
|
* The operations and their parameters come from the server
|
||||||
|
* (`/imports/derivations`), so a new operation needs no change here.
|
||||||
|
*/
|
||||||
|
@Component({
|
||||||
|
selector: 'app-mapping-rules',
|
||||||
|
imports: [
|
||||||
|
FormsModule,
|
||||||
|
MatButtonModule,
|
||||||
|
MatCheckboxModule,
|
||||||
|
MatFormFieldModule,
|
||||||
|
MatIconModule,
|
||||||
|
MatInputModule,
|
||||||
|
MatProgressBarModule,
|
||||||
|
MatSelectModule,
|
||||||
|
MatTooltipModule,
|
||||||
|
],
|
||||||
|
templateUrl: './mapping-rules.html',
|
||||||
|
styleUrl: './mapping-rules.scss',
|
||||||
|
})
|
||||||
|
export class MappingRules {
|
||||||
|
readonly flow = input.required<ImportFlow>();
|
||||||
|
private readonly api = inject(ImportsApi);
|
||||||
|
|
||||||
|
readonly catalog = toSignal(this.api.derivations());
|
||||||
|
readonly columnNames = computed(() => this.flow().sourceColumns().map((column) => column.name));
|
||||||
|
readonly fileFields = computed(() => this.flow().target.fields.filter((field) => field.type === 'binary' || field.name.endsWith('_blob')));
|
||||||
|
|
||||||
|
readonly documentForm = signal<DocumentForm>(this.emptyDocumentForm());
|
||||||
|
readonly documentsBusy = signal(false);
|
||||||
|
readonly documentsError = signal<string | null>(null);
|
||||||
|
|
||||||
|
readonly ruleField = signal<string>('');
|
||||||
|
readonly ruleOp = signal<string>('');
|
||||||
|
readonly ruleParams = signal<Record<string, unknown>>({});
|
||||||
|
readonly ruleCase = signal<string>('');
|
||||||
|
readonly ruleError = signal<string | null>(null);
|
||||||
|
|
||||||
|
readonly previewRows = signal<Row[] | null>(null);
|
||||||
|
readonly previewBusy = signal(false);
|
||||||
|
readonly previewError = signal<string | null>(null);
|
||||||
|
|
||||||
|
readonly selectedSpec = computed<DerivationSpec | undefined>(() =>
|
||||||
|
this.catalog()?.derivations.find((spec) => spec.op === this.ruleOp()),
|
||||||
|
);
|
||||||
|
|
||||||
|
readonly rules = computed(() =>
|
||||||
|
Object.entries(this.flow().derived()).map(([field, rule]) => ({ field, rule, summary: this.describe(rule) })),
|
||||||
|
);
|
||||||
|
|
||||||
|
readonly previewColumns = computed(() => {
|
||||||
|
const rows = this.previewRows() ?? [];
|
||||||
|
return [...new Set(rows.flatMap((row) => Object.keys(row)))];
|
||||||
|
});
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
// The form follows the flow: what it has configured, or the columns the server flagged.
|
||||||
|
effect(() => {
|
||||||
|
const flow = this.flow();
|
||||||
|
const current = flow.documents();
|
||||||
|
this.documentForm.set(current ? this.formFrom(current) : { ...this.emptyDocumentForm(), columns: flow.documentColumns() });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// -- documents -----------------------------------------------------------
|
||||||
|
|
||||||
|
patchDocuments(patch: Partial<DocumentForm>): void {
|
||||||
|
this.documentForm.update((form) => ({ ...form, ...patch }));
|
||||||
|
}
|
||||||
|
|
||||||
|
async applyDocuments(): Promise<void> {
|
||||||
|
const form = this.documentForm();
|
||||||
|
const flow = this.flow();
|
||||||
|
if (!form.columns.length) {
|
||||||
|
this.clearDocuments();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
flow.setDocuments({
|
||||||
|
columns: form.columns,
|
||||||
|
group_by: form.group_by || undefined,
|
||||||
|
file_field: form.file_field || undefined,
|
||||||
|
ocr_mode: form.ocr_mode,
|
||||||
|
include_pattern: form.include_pattern.trim() || undefined,
|
||||||
|
exclude_pattern: form.exclude_pattern.trim() || undefined,
|
||||||
|
});
|
||||||
|
this.documentsBusy.set(true);
|
||||||
|
this.documentsError.set(null);
|
||||||
|
try {
|
||||||
|
flow.useDocumentPreview(await firstValueFrom(this.api.documentColumns(await flow.toPayload())));
|
||||||
|
} catch (error) {
|
||||||
|
this.documentsError.set(apiErrorMessage(error, 'No se pudieron leer los documentos.'));
|
||||||
|
} finally {
|
||||||
|
this.documentsBusy.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
clearDocuments(): void {
|
||||||
|
this.flow().setDocuments(null);
|
||||||
|
this.documentsError.set(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
// -- derived fields ------------------------------------------------------
|
||||||
|
|
||||||
|
chooseOp(op: string): void {
|
||||||
|
this.ruleOp.set(op);
|
||||||
|
const spec = this.catalog()?.derivations.find((candidate) => candidate.op === op);
|
||||||
|
this.ruleParams.set(Object.fromEntries((spec?.params ?? []).map((param) => [param.name, this.initial(param)])));
|
||||||
|
this.ruleError.set(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
setParam(name: string, value: unknown): void {
|
||||||
|
this.ruleParams.update((params) => ({ ...params, [name]: value }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `clave = valor` lines, the text form of a `mapping` parameter. */
|
||||||
|
mappingText(name: string): string {
|
||||||
|
const value = this.ruleParams()[name];
|
||||||
|
return value && typeof value === 'object' ? Object.entries(value).map(([k, v]) => `${k} = ${v}`).join('\n') : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
setMappingText(name: string, text: string): void {
|
||||||
|
const entries = text
|
||||||
|
.split('\n')
|
||||||
|
.map((line) => line.split('='))
|
||||||
|
.filter((parts) => parts.length >= 2 && parts[0].trim())
|
||||||
|
.map(([key, ...rest]) => [key.trim(), rest.join('=').trim()]);
|
||||||
|
this.setParam(name, Object.fromEntries(entries));
|
||||||
|
}
|
||||||
|
|
||||||
|
addRule(): void {
|
||||||
|
const spec = this.selectedSpec();
|
||||||
|
const field = this.ruleField();
|
||||||
|
if (!spec || !field) return;
|
||||||
|
const params = this.ruleParams();
|
||||||
|
const missing = spec.params.filter((param) => param.required && this.blank(params[param.name]));
|
||||||
|
if (missing.length) {
|
||||||
|
this.ruleError.set(`Falta: ${missing.map((param) => param.label).join(', ')}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const rule: DerivationRule = { op: spec.op };
|
||||||
|
for (const param of spec.params) {
|
||||||
|
const value = params[param.name];
|
||||||
|
if (!this.blank(value)) rule[param.name] = param.kind === 'integer' ? Number(value) : value;
|
||||||
|
}
|
||||||
|
if (this.ruleCase()) rule.case = this.ruleCase();
|
||||||
|
this.flow().setDerived(field, rule);
|
||||||
|
this.ruleField.set('');
|
||||||
|
this.ruleOp.set('');
|
||||||
|
this.ruleParams.set({});
|
||||||
|
this.ruleCase.set('');
|
||||||
|
this.ruleError.set(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
removeRule(field: string): void {
|
||||||
|
this.flow().setDerived(field, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
// -- preview ---------------------------------------------------------------
|
||||||
|
|
||||||
|
async preview(): Promise<void> {
|
||||||
|
this.previewBusy.set(true);
|
||||||
|
this.previewError.set(null);
|
||||||
|
try {
|
||||||
|
const { rows } = await firstValueFrom(this.api.mappedPreview(await this.flow().toPayload(), 10));
|
||||||
|
this.previewRows.set(rows);
|
||||||
|
} catch (error) {
|
||||||
|
this.previewError.set(apiErrorMessage(error, 'No se pudo armar la vista previa.'));
|
||||||
|
} finally {
|
||||||
|
this.previewBusy.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cell(value: unknown): string {
|
||||||
|
if (value === null || value === undefined) return '';
|
||||||
|
return typeof value === 'object' ? JSON.stringify(value) : String(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private describe(rule: DerivationRule): string {
|
||||||
|
const spec = this.catalog()?.derivations.find((candidate) => candidate.op === rule.op);
|
||||||
|
const parts = (spec?.params ?? [])
|
||||||
|
.filter((param) => !this.blank(rule[param.name]))
|
||||||
|
.map((param) => `${param.label}: ${this.cell(rule[param.name])}`);
|
||||||
|
return [spec?.label ?? rule.op, ...parts, ...(rule.case ? [`(${rule.case})`] : [])].join(' · ');
|
||||||
|
}
|
||||||
|
|
||||||
|
private initial(param: DerivationParam): unknown {
|
||||||
|
if (param.kind === 'columns') return [];
|
||||||
|
if (param.kind === 'mapping') return {};
|
||||||
|
return param.default ?? (param.kind === 'boolean' ? false : '');
|
||||||
|
}
|
||||||
|
|
||||||
|
private blank(value: unknown): boolean {
|
||||||
|
return (
|
||||||
|
value === null ||
|
||||||
|
value === undefined ||
|
||||||
|
(typeof value === 'string' && !value.trim()) ||
|
||||||
|
(Array.isArray(value) && !value.length) ||
|
||||||
|
(typeof value === 'object' && !Array.isArray(value) && !Object.keys(value as object).length)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private emptyDocumentForm(): DocumentForm {
|
||||||
|
return { columns: [], group_by: '', file_field: '', ocr_mode: 'auto', include_pattern: '', exclude_pattern: '' };
|
||||||
|
}
|
||||||
|
|
||||||
|
private formFrom(config: DocumentColumnsConfig): DocumentForm {
|
||||||
|
return {
|
||||||
|
columns: config.columns,
|
||||||
|
group_by: typeof config.group_by === 'string' ? config.group_by : '',
|
||||||
|
file_field: config.file_field ?? '',
|
||||||
|
ocr_mode: config.ocr_mode ?? 'auto',
|
||||||
|
include_pattern: config.include_pattern ?? '',
|
||||||
|
exclude_pattern: config.exclude_pattern ?? '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -92,4 +92,40 @@ describe('ImportFlow', () => {
|
|||||||
expect(flow.autoMap()).toBe(1);
|
expect(flow.autoMap()).toBe(1);
|
||||||
expect(flow.mapping.toRecord()).toEqual({ Sexo: 'pac_sexo', Clave: 'pac_id_hospital' });
|
expect(flow.mapping.toRecord()).toEqual({ Sexo: 'pac_sexo', Clave: 'pac_id_hospital' });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('counts a derived field as covered, and mapping a column onto it drops the rule', async () => {
|
||||||
|
// Fails if `missingRequired` ignores `derived`, or a field could be fed by a column and a rule at once.
|
||||||
|
const flow = loadedFlow();
|
||||||
|
flow.setDerived('pac_id_hospital', { op: 'concat', columns: ['Clave', 'Sexo'], separator: '-' });
|
||||||
|
expect(flow.missingRequired()).toEqual([]);
|
||||||
|
expect((await flow.toPayload()).derived).toEqual({ pac_id_hospital: { op: 'concat', columns: ['Clave', 'Sexo'], separator: '-' } });
|
||||||
|
|
||||||
|
flow.map('Clave', 'pac_id_hospital');
|
||||||
|
expect(flow.derived()).toEqual({});
|
||||||
|
expect((await flow.toPayload()).derived).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sends document columns without blank settings and swaps in their columns until they are dropped', async () => {
|
||||||
|
// Fails if blank document settings reach the payload, or the source's own columns are lost when documents are dropped.
|
||||||
|
const flow = loadedFlow();
|
||||||
|
const own = flow.sourceColumns();
|
||||||
|
flow.setDocuments({ columns: ['Clave'], group_by: '', include_pattern: undefined, ocr_mode: 'auto' });
|
||||||
|
expect((await flow.toPayload()).documents).toEqual({ columns: ['Clave'], ocr_mode: 'auto' });
|
||||||
|
expect(flow.missingRequired()).toEqual([]);
|
||||||
|
|
||||||
|
flow.useDocumentPreview(preview({ columns: [...own, { name: 'Tipo de persona', inferred_type: 'string' }] }));
|
||||||
|
expect(flow.sourceColumns().map((c) => c.name)).toContain('Tipo de persona');
|
||||||
|
|
||||||
|
flow.setDocuments(null);
|
||||||
|
expect(flow.sourceColumns()).toEqual(own);
|
||||||
|
expect((await flow.toPayload()).documents).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('asks for the catalog fallback only when chosen', async () => {
|
||||||
|
// Fails if `catalog_fallback` is sent without the user switching it on, or not sent once they do.
|
||||||
|
const flow = loadedFlow();
|
||||||
|
expect((await flow.toPayload()).catalog_fallback).toBeUndefined();
|
||||||
|
flow.setCatalogFallback(true);
|
||||||
|
expect((await flow.toPayload()).catalog_fallback).toBe(true);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import { Signal, computed, signal } from '@angular/core';
|
|||||||
import { Observable, catchError, finalize, map, of, tap } from 'rxjs';
|
import { Observable, catchError, finalize, map, of, tap } from 'rxjs';
|
||||||
import {
|
import {
|
||||||
CommitSourceResult,
|
CommitSourceResult,
|
||||||
|
DerivationRule,
|
||||||
|
DocumentColumnsConfig,
|
||||||
ImportSourcePayload,
|
ImportSourcePayload,
|
||||||
PreviewResponse,
|
PreviewResponse,
|
||||||
RowError,
|
RowError,
|
||||||
@@ -47,9 +49,14 @@ export class ImportFlow {
|
|||||||
readonly mapping = new MappingSet();
|
readonly mapping = new MappingSet();
|
||||||
|
|
||||||
private readonly _preview = signal<PreviewResponse | null>(null);
|
private readonly _preview = signal<PreviewResponse | null>(null);
|
||||||
|
/** The source's own preview, kept while document columns replace it. */
|
||||||
|
private _sourcePreview: PreviewResponse | null = null;
|
||||||
private readonly _loading = signal(false);
|
private readonly _loading = signal(false);
|
||||||
private readonly _error = signal<string | null>(null);
|
private readonly _error = signal<string | null>(null);
|
||||||
private readonly _defaults = signal<Record<string, string>>({});
|
private readonly _defaults = signal<Record<string, string>>({});
|
||||||
|
private readonly _derived = signal<Record<string, DerivationRule>>({});
|
||||||
|
private readonly _documents = signal<DocumentColumnsConfig | null>(null);
|
||||||
|
private readonly _catalogFallback = signal(false);
|
||||||
private readonly _validation = signal<ValidationResult | null>(null);
|
private readonly _validation = signal<ValidationResult | null>(null);
|
||||||
private readonly _validating = signal(false);
|
private readonly _validating = signal(false);
|
||||||
private readonly _result = signal<CommitSourceResult | null>(null);
|
private readonly _result = signal<CommitSourceResult | null>(null);
|
||||||
@@ -58,6 +65,12 @@ export class ImportFlow {
|
|||||||
readonly loading: Signal<boolean> = this._loading.asReadonly();
|
readonly loading: Signal<boolean> = this._loading.asReadonly();
|
||||||
readonly error: Signal<string | null> = this._error.asReadonly();
|
readonly error: Signal<string | null> = this._error.asReadonly();
|
||||||
readonly defaults: Signal<Record<string, string>> = this._defaults.asReadonly();
|
readonly defaults: Signal<Record<string, string>> = this._defaults.asReadonly();
|
||||||
|
/** Target fields computed from source columns (`derived`), by field. */
|
||||||
|
readonly derived: Signal<Record<string, DerivationRule>> = this._derived.asReadonly();
|
||||||
|
/** Source columns read as documents, or `null` when none are. */
|
||||||
|
readonly documents: Signal<DocumentColumnsConfig | null> = this._documents.asReadonly();
|
||||||
|
/** Whether captions the catalog knows are stored too (`catalog_fallback`); off unless chosen. */
|
||||||
|
readonly catalogFallback: Signal<boolean> = this._catalogFallback.asReadonly();
|
||||||
readonly validation: Signal<ValidationResult | null> = this._validation.asReadonly();
|
readonly validation: Signal<ValidationResult | null> = this._validation.asReadonly();
|
||||||
readonly validating: Signal<boolean> = this._validating.asReadonly();
|
readonly validating: Signal<boolean> = this._validating.asReadonly();
|
||||||
readonly result: Signal<CommitSourceResult | null> = this._result.asReadonly();
|
readonly result: Signal<CommitSourceResult | null> = this._result.asReadonly();
|
||||||
@@ -65,18 +78,28 @@ export class ImportFlow {
|
|||||||
readonly sourceColumns = computed<SourceColumn[]>(() => this._preview()?.columns ?? []);
|
readonly sourceColumns = computed<SourceColumn[]>(() => this._preview()?.columns ?? []);
|
||||||
readonly totalRows = computed(() => this._preview()?.total_rows ?? null);
|
readonly totalRows = computed(() => this._preview()?.total_rows ?? null);
|
||||||
|
|
||||||
/** A field is covered when a column feeds it or it has a default value. */
|
/**
|
||||||
|
* A field is covered when a column feeds it, a rule computes it or it has
|
||||||
|
* a default value. With document columns, extraction may fill any field,
|
||||||
|
* so nothing is reported missing before validation says so.
|
||||||
|
*/
|
||||||
readonly missingRequired = computed<TargetField[]>(() => {
|
readonly missingRequired = computed<TargetField[]>(() => {
|
||||||
|
if (this._documents()) return [];
|
||||||
const mapped = this.mapping.byField();
|
const mapped = this.mapping.byField();
|
||||||
const defaults = this._defaults();
|
const defaults = this._defaults();
|
||||||
return this.target.fields.filter((f) => f.required && !mapped.has(f.name) && !defaults[f.name]?.trim());
|
const derived = this._derived();
|
||||||
|
return this.target.fields.filter((f) => f.required && !mapped.has(f.name) && !derived[f.name] && !defaults[f.name]?.trim());
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/** Columns no mapping, rule or document setting reads. */
|
||||||
readonly unmappedColumns = computed(() => {
|
readonly unmappedColumns = computed(() => {
|
||||||
const used = this.mapping.bySource();
|
const used = new Set([...this.mapping.bySource().keys(), ...this._documents()?.columns ?? []]);
|
||||||
return this.sourceColumns().filter((column) => !used.has(column.name));
|
return this.sourceColumns().filter((column) => !used.has(column.name));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/** Columns whose sampled cells hold documents. */
|
||||||
|
readonly documentColumns = computed<string[]>(() => this._preview()?.document_columns ?? []);
|
||||||
|
|
||||||
readonly pendingSuggestions = computed(() => this.mapping.items().filter((m) => m.confidence !== undefined).length);
|
readonly pendingSuggestions = computed(() => this.mapping.items().filter((m) => m.confidence !== undefined).length);
|
||||||
|
|
||||||
readonly status = computed<FlowStatus>(() => {
|
readonly status = computed<FlowStatus>(() => {
|
||||||
@@ -84,7 +107,8 @@ export class ImportFlow {
|
|||||||
if (this._error() || !this._preview()) return 'error';
|
if (this._error() || !this._preview()) return 'error';
|
||||||
if (this._result()) return 'loaded';
|
if (this._result()) return 'loaded';
|
||||||
if (this._validating()) return 'validating';
|
if (this._validating()) return 'validating';
|
||||||
if (this.missingRequired().length > 0 || this.mapping.size() + Object.keys(this.activeDefaults()).length === 0) {
|
const assigned = this.mapping.size() + Object.keys(this.activeDefaults()).length + Object.keys(this._derived()).length;
|
||||||
|
if (this.missingRequired().length > 0 || (assigned === 0 && !this._documents())) {
|
||||||
return 'incomplete';
|
return 'incomplete';
|
||||||
}
|
}
|
||||||
const validation = this._validation();
|
const validation = this._validation();
|
||||||
@@ -161,6 +185,9 @@ export class ImportFlow {
|
|||||||
|
|
||||||
map(source: string, field: string): void {
|
map(source: string, field: string): void {
|
||||||
this.mapping.assign(source, field);
|
this.mapping.assign(source, field);
|
||||||
|
if (this._derived()[field]) {
|
||||||
|
this._derived.update(({ [field]: _, ...rest }) => rest);
|
||||||
|
}
|
||||||
this.touch();
|
this.touch();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -188,9 +215,51 @@ export class ImportFlow {
|
|||||||
clearMapping(): void {
|
clearMapping(): void {
|
||||||
this.mapping.clear();
|
this.mapping.clear();
|
||||||
this._defaults.set({});
|
this._defaults.set({});
|
||||||
|
this._derived.set({});
|
||||||
|
this._documents.set(null);
|
||||||
this.touch();
|
this.touch();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Computes `field` with `rule`, replacing any column mapped to it; `null` removes the rule. */
|
||||||
|
setDerived(field: string, rule: DerivationRule | null): void {
|
||||||
|
if (rule) this.mapping.releaseField(field);
|
||||||
|
this._derived.update((derived) => {
|
||||||
|
const next = { ...derived };
|
||||||
|
if (rule) next[field] = rule;
|
||||||
|
else delete next[field];
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
this.touch();
|
||||||
|
}
|
||||||
|
|
||||||
|
setCatalogFallback(on: boolean): void {
|
||||||
|
this._catalogFallback.set(on);
|
||||||
|
this.touch();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reads some of the source's columns as documents; `null` stops reading them. */
|
||||||
|
setDocuments(config: DocumentColumnsConfig | null): void {
|
||||||
|
this._documents.set(config && config.columns.length ? config : null);
|
||||||
|
if (!this._documents()) this.useDocumentPreview(null);
|
||||||
|
this.touch();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shows, as the source's columns, its own plus every field and caption
|
||||||
|
* its documents print, so they can be mapped and used in rules; `null`
|
||||||
|
* goes back to the source's own columns.
|
||||||
|
*/
|
||||||
|
useDocumentPreview(preview: PreviewResponse | null): void {
|
||||||
|
if (preview) {
|
||||||
|
this._sourcePreview ??= this._preview();
|
||||||
|
this._preview.set({ ...preview, document_columns: this._sourcePreview?.document_columns ?? [] });
|
||||||
|
this.mapping.fillFrom(preview.suggested_mapping);
|
||||||
|
} else if (this._sourcePreview) {
|
||||||
|
this._preview.set(this._sourcePreview);
|
||||||
|
this._sourcePreview = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
setDefault(field: string, value: string | null): void {
|
setDefault(field: string, value: string | null): void {
|
||||||
this._defaults.update((defaults) => {
|
this._defaults.update((defaults) => {
|
||||||
const next = { ...defaults };
|
const next = { ...defaults };
|
||||||
@@ -215,6 +284,9 @@ export class ImportFlow {
|
|||||||
label: this.label,
|
label: this.label,
|
||||||
column_mapping: this.mapping.toRecord(),
|
column_mapping: this.mapping.toRecord(),
|
||||||
...(Object.keys(defaults).length ? { defaults } : {}),
|
...(Object.keys(defaults).length ? { defaults } : {}),
|
||||||
|
...(Object.keys(this._derived()).length ? { derived: this._derived() } : {}),
|
||||||
|
...(this._documents() ? { documents: withoutBlanks(this._documents()!) } : {}),
|
||||||
|
...(this._catalogFallback() ? { catalog_fallback: true } : {}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -256,3 +328,9 @@ export class ImportFlow {
|
|||||||
this._result.set(null);
|
this._result.set(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function withoutBlanks(config: DocumentColumnsConfig): DocumentColumnsConfig {
|
||||||
|
return Object.fromEntries(
|
||||||
|
Object.entries(config).filter(([, value]) => value !== undefined && value !== null && value !== ''),
|
||||||
|
) as unknown as DocumentColumnsConfig;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { listSavedSqlConnections, removeSqlConnection, saveSqlConnection } from './saved-sql-connections';
|
||||||
|
|
||||||
|
describe('saved SQL connections', () => {
|
||||||
|
beforeEach(() => localStorage.clear());
|
||||||
|
|
||||||
|
it('never stores a password field', () => {
|
||||||
|
const saved = saveSqlConnection({ label: 'HIS · lector@his.local', engine: 'mssql', host: 'his.local', port: 1433, database: 'HIS', user: 'lector' });
|
||||||
|
expect(Object.keys(saved)).not.toContain('password');
|
||||||
|
expect(JSON.parse(localStorage.getItem('isssteleon.connect.savedSqlConnections')!)[0]).not.toHaveProperty('password');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('upserts by connection shape instead of growing duplicates', () => {
|
||||||
|
const entry = { label: 'HIS', engine: 'mssql', host: 'his.local', port: 1433, database: 'HIS', user: 'lector' };
|
||||||
|
saveSqlConnection(entry);
|
||||||
|
saveSqlConnection({ ...entry, label: 'HIS (renamed)' });
|
||||||
|
const all = listSavedSqlConnections();
|
||||||
|
expect(all.length).toBe(1);
|
||||||
|
expect(all[0].label).toBe('HIS (renamed)');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps connections to different servers separate', () => {
|
||||||
|
saveSqlConnection({ label: 'A', engine: 'mssql', host: 'a.local', port: 1433, database: 'HIS', user: 'lector' });
|
||||||
|
saveSqlConnection({ label: 'B', engine: 'mysql', host: 'b.local', port: 3306, database: 'HIS', user: 'lector' });
|
||||||
|
expect(listSavedSqlConnections().length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('removes a saved connection by id', () => {
|
||||||
|
const saved = saveSqlConnection({ label: 'HIS', engine: 'mssql', host: 'his.local', port: 1433, database: 'HIS', user: 'lector' });
|
||||||
|
removeSqlConnection(saved.id);
|
||||||
|
expect(listSavedSqlConnections()).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('caps the list so it cannot grow without bound', () => {
|
||||||
|
for (let i = 0; i < 25; i++) {
|
||||||
|
saveSqlConnection({ label: `db${i}`, engine: 'mssql', host: `host${i}`, port: 1433, database: 'HIS', user: 'lector' });
|
||||||
|
}
|
||||||
|
expect(listSavedSqlConnections().length).toBeLessThanOrEqual(20);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('degrades to an empty list rather than throwing when storage is unreadable', () => {
|
||||||
|
const spy = vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
|
||||||
|
throw new Error('blocked');
|
||||||
|
});
|
||||||
|
expect(listSavedSqlConnections()).toEqual([]);
|
||||||
|
spy.mockRestore();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
const STORAGE_KEY = 'isssteleon.connect.savedSqlConnections';
|
||||||
|
const MAX_SAVED = 20;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A database connection's shape, remembered across visits so the form
|
||||||
|
* doesn't need retyping. Never the password: credentials travel with every
|
||||||
|
* request and are never stored (see `sql-source.ts`), so reconnecting
|
||||||
|
* through a saved entry still asks for it.
|
||||||
|
*/
|
||||||
|
export interface SavedSqlConnection {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
engine: string;
|
||||||
|
host: string;
|
||||||
|
port: number | null;
|
||||||
|
database: string;
|
||||||
|
user: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SavedSqlConnectionInput = Omit<SavedSqlConnection, 'id'>;
|
||||||
|
|
||||||
|
function connectionId(entry: SavedSqlConnectionInput): string {
|
||||||
|
return [entry.engine, entry.host, entry.port ?? '', entry.database, entry.user].join('|');
|
||||||
|
}
|
||||||
|
|
||||||
|
function readAll(): SavedSqlConnection[] {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(STORAGE_KEY);
|
||||||
|
const parsed = raw ? JSON.parse(raw) : [];
|
||||||
|
return Array.isArray(parsed) ? parsed : [];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeAll(entries: SavedSqlConnection[]): void {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(STORAGE_KEY, JSON.stringify(entries));
|
||||||
|
} catch {
|
||||||
|
// Private browsing, a cleared/blocked store, or a full quota: the form
|
||||||
|
// just won't remember anything this time, nothing to surface to the user.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listSavedSqlConnections(): SavedSqlConnection[] {
|
||||||
|
return readAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Upserts by connection shape (engine/host/port/database/user), newest first. */
|
||||||
|
export function saveSqlConnection(entry: SavedSqlConnectionInput): SavedSqlConnection {
|
||||||
|
const saved: SavedSqlConnection = { ...entry, id: connectionId(entry) };
|
||||||
|
const rest = readAll().filter((existing) => existing.id !== saved.id);
|
||||||
|
writeAll([saved, ...rest].slice(0, MAX_SAVED));
|
||||||
|
return saved;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removeSqlConnection(id: string): void {
|
||||||
|
writeAll(readAll().filter((existing) => existing.id !== id));
|
||||||
|
}
|
||||||
@@ -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 {
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; page: number; page_size: number; }
|
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; }
|
||||||
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
|
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
|
||||||
|
// A row names its patient with `pac_id` (a decimal string) or the legacy `id_seudonimo`.
|
||||||
export interface SeguimientoPaciente {
|
export interface SeguimientoPaciente {
|
||||||
id_seudonimo: string;
|
pac_id?: string;
|
||||||
|
id_seudonimo?: string;
|
||||||
grupo_edad: string;
|
grupo_edad: string;
|
||||||
estatus: SeguimientoStatus;
|
estatus: SeguimientoStatus;
|
||||||
ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null;
|
ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null;
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { inject, Injectable } from '@angular/core';
|
|||||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||||
import { map } from 'rxjs';
|
import { map } from 'rxjs';
|
||||||
import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models';
|
import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models';
|
||||||
|
import { identidadDe, identidadesDe } from './paciente-identidad';
|
||||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||||
const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string';
|
const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string';
|
||||||
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
|
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
|
||||||
@@ -19,12 +20,12 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse {
|
|||||||
|| !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string))
|
|| !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string))
|
||||||
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|
||||||
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => {
|
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => {
|
||||||
if (!record(item) || typeof item['id_seudonimo'] !== 'string' || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false;
|
if (!record(item) || !identidadDe(item) || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false;
|
||||||
const c = item['ultima_citologia'], h = item['ultimo_vph'];
|
const c = item['ultima_citologia'], h = item['ultimo_vph'];
|
||||||
return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && (c['calidad'] === null || typeof c['calidad'] === 'string'))
|
return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && (c['calidad'] === null || typeof c['calidad'] === 'string'))
|
||||||
&& (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean'))
|
&& (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean'))
|
||||||
&& (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad']));
|
&& (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad']));
|
||||||
})) throw new Error('Respuesta de seguimiento inválida');
|
}) || !identidadesDe(v['items'])) throw new Error('Respuesta de seguimiento inválida');
|
||||||
return v as unknown as SeguimientoResponse;
|
return v as unknown as SeguimientoResponse;
|
||||||
}
|
}
|
||||||
@Injectable({ providedIn: 'root' })
|
@Injectable({ providedIn: 'root' })
|
||||||
|
|||||||
@@ -16,11 +16,10 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
|||||||
afterEach(()=>{ fixture.destroy(); http.verify(); });
|
afterEach(()=>{ fixture.destroy(); http.verify(); });
|
||||||
function open() { fixture.componentRef.setInput('active',true); fixture.detectChanges(); return http.expectOne(r=>r.url==='/cacu/seguimiento'); }
|
function open() { fixture.componentRef.setInput('active',true); fixture.detectChanges(); return http.expectOne(r=>r.url==='/cacu/seguimiento'); }
|
||||||
function respond() { open().flush(fixtureData); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({categorias:{NORMAL:{etiqueta:'Normal'}}}); fixture.detectChanges(); }
|
function respond() { open().flush(fixtureData); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({categorias:{NORMAL:{etiqueta:'Normal'}}}); fixture.detectChanges(); }
|
||||||
it('prioridad deshabilitada con una sola opción y sin parámetros nuevos al consultar o paginar', () => {
|
it('sin selector de prioridad ni filtros de TEA, y sin parámetros nuevos al consultar o paginar', () => {
|
||||||
respond();
|
respond();
|
||||||
const select = fixture.nativeElement.querySelector('select[name="prioridad"]') as HTMLSelectElement;
|
expect(fixture.nativeElement.querySelector('select[name="prioridad"]')).toBeNull();
|
||||||
expect(select.disabled).toBe(true); expect(select.labels?.[0].textContent).toContain('Ordenar por prioridad');
|
expect(fixture.nativeElement.querySelector('select[name="mchat"]')).toBeNull();
|
||||||
expect(Array.from(select.options).map(o => o.text)).toEqual(['No disponible']);
|
|
||||||
const order = fixture.componentInstance.data!.items.map(i => i.id_seudonimo);
|
const order = fixture.componentInstance.data!.items.map(i => i.id_seudonimo);
|
||||||
expect(Array.from(fixture.nativeElement.querySelectorAll('tbody tr td:first-child')).map(e => (e as HTMLElement).textContent)).toEqual(order);
|
expect(Array.from(fixture.nativeElement.querySelectorAll('tbody tr td:first-child')).map(e => (e as HTMLElement).textContent)).toEqual(order);
|
||||||
fixture.componentInstance.apply();
|
fixture.componentInstance.apply();
|
||||||
@@ -92,14 +91,6 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
|||||||
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow();
|
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow();
|
||||||
open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull();
|
open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull();
|
||||||
});
|
});
|
||||||
it('tea conserva su estado pendiente sin consultas de pacientes', () => {
|
|
||||||
const dominio = 'tea';
|
|
||||||
fixture.componentRef.setInput('dominio',dominio); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true);
|
|
||||||
expect(fixture.nativeElement.textContent).toContain('El seguimiento aún no está disponible');
|
|
||||||
expect(fixture.nativeElement.textContent).not.toContain('Columnas propuestas para revisión.');
|
|
||||||
expect(fixture.nativeElement.querySelector('table')).not.toBeNull();
|
|
||||||
expect(fixture.nativeElement.querySelector('caption')).toBeNull();
|
|
||||||
});
|
|
||||||
it('valida parámetros antes del transporte sin confundir fechas del filtro general', () => {
|
it('valida parámetros antes del transporte sin confundir fechas del filtro general', () => {
|
||||||
const service=TestBed.inject(CacuSeguimientoService);
|
const service=TestBed.inject(CacuSeguimientoService);
|
||||||
for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow();
|
for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow();
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
// Display only codes confirmed by the cohort and CaMa catalog; preserve unknown values as received.
|
||||||
|
const EDADES: Readonly<Record<string, string>> = {
|
||||||
|
MENOR_40: 'Menores de 40 años', '<40': 'Menores de 40 años', '40-49': '40 a 49 años', '50-59': '50 a 59 años', '60-69': '60 a 69 años', '70+': '70 años o más', SIN_DATO: 'Sin dato',
|
||||||
|
};
|
||||||
|
const BIRADS = /^BIRADS_(4[ABC]?|5|6)$/;
|
||||||
|
const HISTOLOGIA: Readonly<Record<string, string>> = {
|
||||||
|
BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ',
|
||||||
|
CARCINOMA_INVASOR: 'Carcinoma invasor', DESCONOCIDO: 'Desconocido',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». Any other text is returned as it came. */
|
||||||
|
export const etiquetaBirads = (codigo: string) => BIRADS.test(codigo) ? 'BI-RADS ' + codigo.slice(7) : codigo;
|
||||||
|
/** «50-59» as «50 a 59 años». Any other text is returned as it came. */
|
||||||
|
export const etiquetaEdad = (codigo: string) => EDADES[codigo] ?? codigo;
|
||||||
|
export const etiquetaHistologia = (codigo: string) => HISTOLOGIA[codigo] ?? codigo;
|
||||||
|
|
||||||
|
const POR_CLAVE: Readonly<Record<string, (codigo: string) => string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia };
|
||||||
|
|
||||||
|
/** The label of a value of a filter of the cohort's list, or the value itself when its meaning is not confirmed. */
|
||||||
|
export const etiquetaDeFiltro = (clave: string, codigo: string) => (POR_CLAVE[clave] ?? ((c: string) => c))(codigo);
|
||||||
@@ -4,7 +4,7 @@ const pad = (n: number) => String(n).padStart(2, '0');
|
|||||||
* Name of a downloaded file. It carries the report kind, the cut-off date and the moment it was made, and never a
|
* Name of a downloaded file. It carries the report kind, the cut-off date and the moment it was made, and never a
|
||||||
* patient identifier, because file names end up in download lists, backups and mail attachments.
|
* patient identifier, because file names end up in download lists, backups and mail attachments.
|
||||||
*/
|
*/
|
||||||
export function exportFilename(kind: 'seguimiento-cancer-de-mama' | 'ficha-cancer-de-mama', corte: string, extension: 'xlsx' | 'pdf', now = new Date()): string {
|
export function exportFilename(kind: 'seguimiento-cancer-de-mama' | 'seguimiento-cancer-de-mama-seleccion' | 'ficha-cancer-de-mama', corte: string, extension: 'xlsx' | 'pdf', now = new Date()): string {
|
||||||
const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}`;
|
const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}`;
|
||||||
return `${kind}_corte-${corte.replace(/[^0-9-]/g, '')}_${stamp}.${extension}`;
|
return `${kind}_corte-${corte.replace(/[^0-9-]/g, '')}_${stamp}.${extension}`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core';
|
import { Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core';
|
||||||
import { DecimalPipe } from '@angular/common';
|
import { DecimalPipe } from '@angular/common';
|
||||||
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
import { Subscription } from 'rxjs';
|
import { Subscription } from 'rxjs';
|
||||||
import { Dominio } from '../indicadores.models';
|
import { Dominio } from '../indicadores.models';
|
||||||
import { SeguimientoTablaResponse, SeguimientoTablaService } from '../seguimiento-tabla.service';
|
import { SeguimientoTablaResponse, SeguimientoTablaService } from '../seguimiento-tabla.service';
|
||||||
@@ -54,6 +55,8 @@ export class TrackingExportBar {
|
|||||||
readonly respuesta = input.required<SeguimientoTablaResponse>();
|
readonly respuesta = input.required<SeguimientoTablaResponse>();
|
||||||
/** False while a page is being loaded, so the export never reads a query that is about to change. */
|
/** False while a page is being loaded, so the export never reads a query that is about to change. */
|
||||||
readonly habilitado = input(true);
|
readonly habilitado = input(true);
|
||||||
|
/** How the analysis named the selection this answer belongs to; it travels into the files. */
|
||||||
|
readonly seleccion = input<string | undefined>(undefined);
|
||||||
|
|
||||||
private readonly service = inject(SeguimientoTablaService);
|
private readonly service = inject(SeguimientoTablaService);
|
||||||
private subscription?: Subscription;
|
private subscription?: Subscription;
|
||||||
@@ -73,13 +76,22 @@ export class TrackingExportBar {
|
|||||||
// Identifies the query on screen: paging through its pages keeps it, changing a filter or the cut-off replaces it.
|
// Identifies the query on screen: paging through its pages keeps it, changing a filter or the cut-off replaces it.
|
||||||
private readonly queryKey = computed(() => {
|
private readonly queryKey = computed(() => {
|
||||||
const r = this.respuesta();
|
const r = this.respuesta();
|
||||||
return JSON.stringify([r.corte, r.ventana.meses, r.filtros, r.paginacion.total_items]);
|
return JSON.stringify([r.corte, r.ventana.meses, r.filtros, r.paginacion.total_items, this.seleccion() ?? null]);
|
||||||
});
|
});
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
inject(DestroyRef).onDestroy(() => this.subscription?.unsubscribe());
|
inject(DestroyRef).onDestroy(() => this.subscription?.unsubscribe());
|
||||||
// A result message belongs to the query it was made for: it goes away when another query is shown.
|
// A result message belongs to the query it was made for: it goes away when another query is shown. An export still
|
||||||
effect(() => { this.queryKey(); untracked(() => { if (this.estado() !== 'working') { this.listo.set(''); this.mensaje.set(''); if (this.estado() === 'error') this.estado.set('idle'); } }); });
|
// being read belongs to a query that is no longer on screen: it is cancelled, never downloaded as the current one.
|
||||||
|
effect(() => {
|
||||||
|
this.queryKey();
|
||||||
|
untracked(() => {
|
||||||
|
if (this.estado() === 'working') {
|
||||||
|
this.subscription?.unsubscribe();
|
||||||
|
this.estado.set('error'); this.listo.set(''); this.mensaje.set('La consulta cambió; se canceló la exportación. Vuelve a exportar.');
|
||||||
|
} else { this.listo.set(''); this.mensaje.set(''); if (this.estado() === 'error') this.estado.set('idle'); }
|
||||||
|
});
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
available(formato: ExportFormat): boolean {
|
available(formato: ExportFormat): boolean {
|
||||||
@@ -90,10 +102,11 @@ export class TrackingExportBar {
|
|||||||
if (!this.available(formato)) return;
|
if (!this.available(formato)) return;
|
||||||
this.estado.set('working'); this.mensaje.set(''); this.listo.set(''); this.progress.set({ fetched: 0, total: 0 });
|
this.estado.set('working'); this.mensaje.set(''); this.listo.set(''); this.progress.set({ fetched: 0, total: 0 });
|
||||||
this.subscription?.unsubscribe();
|
this.subscription?.unsubscribe();
|
||||||
|
const clave = this.queryKey(), seleccion = this.seleccion();
|
||||||
this.subscription = fetchAllTracking(this.service, this.dominio(), queryOf(this.respuesta()), EXPORT_LIMITS[formato]).subscribe({
|
this.subscription = fetchAllTracking(this.service, this.dominio(), queryOf(this.respuesta()), EXPORT_LIMITS[formato]).subscribe({
|
||||||
next: event => {
|
next: event => {
|
||||||
if (event.kind === 'progress') this.progress.set({ fetched: event.fetched, total: event.total });
|
if (event.kind === 'progress') this.progress.set({ fetched: event.fetched, total: event.total });
|
||||||
else void this.generar(formato, event.snapshot);
|
else void this.generar(formato, seleccion ? { ...event.snapshot, seleccion } : event.snapshot, clave);
|
||||||
},
|
},
|
||||||
error: error => this.fallar(error),
|
error: error => this.fallar(error),
|
||||||
});
|
});
|
||||||
@@ -104,13 +117,15 @@ export class TrackingExportBar {
|
|||||||
this.estado.set('idle');
|
this.estado.set('idle');
|
||||||
}
|
}
|
||||||
|
|
||||||
private async generar(formato: ExportFormat, snapshot: TrackingSnapshot) {
|
private async generar(formato: ExportFormat, snapshot: TrackingSnapshot, clave: string) {
|
||||||
try {
|
try {
|
||||||
// Each generator (and its library) downloads only when its button is used.
|
// Each generator (and its library) downloads only when its button is used.
|
||||||
const blob = formato === 'xlsx'
|
const blob = formato === 'xlsx'
|
||||||
? await (await import('./tracking-xlsx')).buildTrackingXlsx(snapshot)
|
? await (await import('./tracking-xlsx')).buildTrackingXlsx(snapshot)
|
||||||
: await (await import('./tracking-pdf')).buildTrackingPdf(snapshot);
|
: await (await import('./tracking-pdf')).buildTrackingPdf(snapshot);
|
||||||
downloadBlob(blob, exportFilename('seguimiento-cancer-de-mama', snapshot.corte, formato));
|
// The query on screen changed while the file was being made: it is not the one that was asked for.
|
||||||
|
if (clave !== this.queryKey()) return;
|
||||||
|
downloadBlob(blob, exportFilename(snapshot.seleccion ? 'seguimiento-cancer-de-mama-seleccion' : 'seguimiento-cancer-de-mama', snapshot.corte, formato));
|
||||||
this.estado.set('idle');
|
this.estado.set('idle');
|
||||||
this.listo.set(`Se generó el archivo con ${snapshot.items.length} registros.`);
|
this.listo.set(`Se generó el archivo con ${snapshot.items.length} registros.`);
|
||||||
} catch {
|
} catch {
|
||||||
@@ -120,7 +135,10 @@ export class TrackingExportBar {
|
|||||||
|
|
||||||
private fallar(error: unknown) {
|
private fallar(error: unknown) {
|
||||||
this.estado.set('error');
|
this.estado.set('error');
|
||||||
this.mensaje.set(error instanceof ExportLimitExceeded ? 'La consulta excede el límite de este formato. Acota los filtros.'
|
const estatus = error instanceof HttpErrorResponse ? error.status : 0;
|
||||||
|
this.mensaje.set(error instanceof ExportLimitExceeded || estatus === 413 ? 'La consulta excede el límite de este formato. Acota los filtros.'
|
||||||
|
: estatus === 403 ? 'No hay acceso para exportar esta lista, o la selección tiene muy pocos pacientes para publicarse.'
|
||||||
|
: estatus === 409 ? 'La cohorte cambió mientras se leía. Vuelve al análisis, consúltalo de nuevo y exporta otra vez.'
|
||||||
: error instanceof ExportInconsistent ? 'La lista cambió mientras se leía. Vuelve a consultar e intenta de nuevo.'
|
: error instanceof ExportInconsistent ? 'La lista cambió mientras se leía. Vuelve a consultar e intenta de nuevo.'
|
||||||
: 'No se pudo generar el archivo. Intenta nuevamente.');
|
: 'No se pudo generar el archivo. Intenta nuevamente.');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,157 @@
|
|||||||
|
// Covers the files of a list opened from the analysis: they state the selection, the cut-off and «Toda la cohorte», and
|
||||||
|
// hold exactly the patients the table holds, over several pages; and an export never outlives the query it was made for.
|
||||||
|
// Fixture: fixtures/cama_seguimiento.json, whose rows are repeated to make a list of several pages.
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { Observable, of, Subject } from 'rxjs';
|
||||||
|
import { strFromU8, unzipSync } from 'fflate';
|
||||||
|
import fixtureData from '../fixtures/cama_seguimiento.json';
|
||||||
|
import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from '../seguimiento-tabla.service';
|
||||||
|
import { TrackingExportBar } from './tracking-export-bar';
|
||||||
|
import { CONTEXTO } from '../indicadores-analisis.testing';
|
||||||
|
import { fetchAllTracking, queryOf } from './tracking-export-source';
|
||||||
|
import { TrackingSnapshot } from './tracking-export.models';
|
||||||
|
import { trackingDocument } from './tracking-pdf';
|
||||||
|
import { buildTrackingXlsx } from './tracking-xlsx';
|
||||||
|
|
||||||
|
const ETIQUETA = 'Cáncer confirmado: Categoría BI-RADS, BI-RADS 5';
|
||||||
|
const base = () => structuredClone(fixtureData) as unknown as Record<string, any>;
|
||||||
|
// A cohort of `n` patients, M-0001 onwards, served in the pages that were asked for, with the filters it applied.
|
||||||
|
function cohorte(n: number) {
|
||||||
|
const plantilla = (base()['items'] as Record<string, unknown>[])[0];
|
||||||
|
const todos = Array.from({ length: n }, (_, i) => ({ ...plantilla, id_seudonimo: `M-${String(i + 1).padStart(4, '0')}` }));
|
||||||
|
return (q: SeguimientoTablaQuery): SeguimientoTablaResponse => seguimientoTablaResponse({
|
||||||
|
...base(), ventana: { meses: q.meses, desde: '2025-01-01', hasta: '2026-10-20' }, corte: q.corte ?? '2026-10-20',
|
||||||
|
filtros: { ...base()['filtros'], ...q.filtros }, ...(q.contexto ?? {}),
|
||||||
|
paginacion: { page: q.page, page_size: q.page_size, total_items: n, total_pages: Math.ceil(n / q.page_size) },
|
||||||
|
items: todos.slice((q.page - 1) * q.page_size, q.page * q.page_size),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const consulta = (extra: Partial<SeguimientoTablaQuery> = {}): SeguimientoTablaQuery =>
|
||||||
|
({ corte: '2026-10-20', meses: 0, page: 1, page_size: 50, filtros: { birads: 'BIRADS_5' }, contexto: CONTEXTO, ...extra });
|
||||||
|
const textos = (nodo: unknown, salida: string[] = []): string[] => {
|
||||||
|
if (typeof nodo === 'string') salida.push(nodo); else if (Array.isArray(nodo)) nodo.forEach(n => textos(n, salida)); else if (nodo && typeof nodo === 'object') Object.values(nodo).forEach(n => textos(n, salida));
|
||||||
|
return salida;
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('Archivos de una selección del análisis', () => {
|
||||||
|
const servicio = { consultar: (_d: string, q: SeguimientoTablaQuery) => of(cohorte(450)(q)) } as unknown as SeguimientoTablaService;
|
||||||
|
|
||||||
|
it('el PDF y el XLSX dicen la selección, el corte y «Toda la cohorte», y traen los mismos pacientes que la tabla en todas sus páginas', async () => {
|
||||||
|
// Fails if a file loses the selection, calls the whole cohort «0 meses», or its patients differ from the table's pages.
|
||||||
|
const q = consulta();
|
||||||
|
// The table, page by page (50 per page), as the user would walk it.
|
||||||
|
const filasTabla: string[] = [];
|
||||||
|
for (let p = 1; p <= 9; p++) filasTabla.push(...cohorte(450)({ ...q, page: p }).items.map(i => String(i['id_seudonimo'])));
|
||||||
|
let snapshot!: TrackingSnapshot;
|
||||||
|
await new Promise<void>((ok, fallo) => fetchAllTracking(servicio, 'cama', { ...q, page_size: 200 }, 1000).subscribe({
|
||||||
|
next: e => { if (e.kind === 'done') snapshot = { ...e.snapshot, seleccion: ETIQUETA }; }, error: fallo, complete: ok }));
|
||||||
|
expect(snapshot.items.map(i => String(i['id_seudonimo']))).toEqual(filasTabla);
|
||||||
|
expect(new Set(filasTabla).size).toBe(450);
|
||||||
|
|
||||||
|
const pdf = textos(trackingDocument(snapshot, new Date(Date.UTC(2026, 10, 13, 18, 0)), 'data:image/png;base64,AAAA'));
|
||||||
|
expect(pdf).toContain('Selección del análisis'); expect(pdf).toContain(ETIQUETA);
|
||||||
|
expect(pdf).toContain('Fecha de corte'); expect(pdf).toContain('2026-10-20');
|
||||||
|
expect(pdf).toContain('Toda la cohorte, al 2026-10-20');
|
||||||
|
expect(pdf.some(t => /0 meses/.test(t))).toBe(false);
|
||||||
|
expect(pdf.filter(t => /^M-\d{4}$/.test(t))).toEqual(filasTabla);
|
||||||
|
const PROHIBIDO = /simulad|sint[eé]tic|entorno|\bdev\b|prueba|demostraci|ficticio|mock|valor cl[ií]nico/i;
|
||||||
|
expect(pdf.filter(t => PROHIBIDO.test(t))).toEqual([]);
|
||||||
|
|
||||||
|
const hojas = unzipSync(new Uint8Array(await (await buildTrackingXlsx(snapshot, new Date(Date.UTC(2026, 10, 13, 18, 0)))).arrayBuffer()));
|
||||||
|
const cadenas = strFromU8(hojas['xl/sharedStrings.xml']);
|
||||||
|
expect(cadenas).toContain(ETIQUETA); expect(cadenas).toContain('Selección del análisis'); expect(cadenas).toContain('Toda la cohorte, al 2026-10-20');
|
||||||
|
expect(cadenas).not.toMatch(/0 meses/);
|
||||||
|
expect(cadenas.replace(/<[^>]+>/g, ' ')).not.toMatch(PROHIBIDO);
|
||||||
|
expect([...cadenas.matchAll(/M-\d{4}/g)].map(m => m[0]).filter((v, i, a) => a.indexOf(v) === i)).toEqual(filasTabla);
|
||||||
|
});
|
||||||
|
it('sin una selección los archivos no llevan esa línea y conservan la ventana de meses', async () => {
|
||||||
|
// Fails if a plain list gets a selection line, or a window of months stops being written as dates and months.
|
||||||
|
const q = consulta({ meses: 3, filtros: {} });
|
||||||
|
let snapshot!: TrackingSnapshot;
|
||||||
|
await new Promise<void>((ok, fallo) => fetchAllTracking(servicio, 'cama', { ...q, page_size: 200 }, 1000).subscribe({ next: e => { if (e.kind === 'done') snapshot = e.snapshot; }, error: fallo, complete: ok }));
|
||||||
|
const pdf = textos(trackingDocument(snapshot, new Date(), 'data:image/png;base64,AAAA'));
|
||||||
|
expect(pdf).not.toContain('Selección del análisis');
|
||||||
|
expect(pdf).toContain('2025-01-01 al 2026-10-20 (3 meses)');
|
||||||
|
});
|
||||||
|
it('la consulta de una respuesta conserva la cohorte y su revisión, y todas las páginas del archivo la citan', async () => {
|
||||||
|
// Fails if the export reads a cohort's list without quoting its revision (the server refuses it) or from another one.
|
||||||
|
const respuesta = cohorte(450)(consulta());
|
||||||
|
expect(queryOf(respuesta)).toMatchObject({ corte: '2026-10-20', meses: 0, page: 1, page_size: 200, filtros: { birads: 'BIRADS_5' }, contexto: CONTEXTO });
|
||||||
|
const pedidas: SeguimientoTablaQuery[] = [];
|
||||||
|
const espia = { consultar: (_d: string, q: SeguimientoTablaQuery) => { pedidas.push(q); return of(cohorte(450)(q)); } } as unknown as SeguimientoTablaService;
|
||||||
|
await new Promise<void>((ok, fallo) => fetchAllTracking(espia, 'cama', queryOf(respuesta), 1000).subscribe({ error: fallo, complete: ok }));
|
||||||
|
expect(pedidas.map(q => q.page).sort()).toEqual([1, 2, 3]);
|
||||||
|
expect(pedidas.every(q => q.contexto?.revision === CONTEXTO.revision && q.contexto?.cohorte === CONTEXTO.cohorte && q.meses === 0)).toBe(true);
|
||||||
|
// A plain list quotes no cohort.
|
||||||
|
expect(queryOf(seguimientoTablaResponse(base())).contexto).toBeUndefined();
|
||||||
|
});
|
||||||
|
it('una página posterior de otra revisión hace fallar la lectura', async () => {
|
||||||
|
// Fails if a file mixes pages of two revisions of the cohort.
|
||||||
|
const respuestas = (q: SeguimientoTablaQuery) => of(q.page === 2 ? cohorte(450)({ ...q, contexto: { ...CONTEXTO, revision: 'f'.repeat(64) } }) : cohorte(450)(q));
|
||||||
|
const malo = { consultar: (_d: string, q: SeguimientoTablaQuery) => respuestas(q) } as unknown as SeguimientoTablaService;
|
||||||
|
const error = await new Promise<unknown>(ok => fetchAllTracking(malo, 'cama', { ...consulta(), page_size: 200 }, 1000).subscribe({ error: ok, complete: () => ok(undefined) }));
|
||||||
|
expect(error).toBeInstanceOf(Error);
|
||||||
|
});
|
||||||
|
it('una página posterior que pierde un filtro hace fallar la lectura: no se exporta un subconjunto de otra consulta', async () => {
|
||||||
|
// Fails if a file mixes the pages of the selection with a page of another population.
|
||||||
|
const respuestas = (q: SeguimientoTablaQuery) => of(q.page === 2 ? cohorte(450)({ ...q, filtros: {} }) : cohorte(450)(q));
|
||||||
|
const malo = { consultar: (_d: string, q: SeguimientoTablaQuery) => respuestas(q) } as unknown as SeguimientoTablaService;
|
||||||
|
const error = await new Promise<unknown>(ok => fetchAllTracking(malo, 'cama', { ...consulta(), page_size: 200 }, 1000).subscribe({ error: ok, complete: () => ok(undefined) }));
|
||||||
|
expect(error).toBeInstanceOf(Error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Exportación: la consulta cambia mientras se exporta', () => {
|
||||||
|
let respuestas: (q: SeguimientoTablaQuery) => Observable<SeguimientoTablaResponse>, descargas: string[];
|
||||||
|
let fixture: ReturnType<typeof TestBed.createComponent<TrackingExportBar>>;
|
||||||
|
beforeEach(() => {
|
||||||
|
descargas = [];
|
||||||
|
respuestas = q => of(cohorte(27)(q));
|
||||||
|
TestBed.configureTestingModule({ providers: [{ provide: SeguimientoTablaService, useValue: { consultar: (_d: string, q: SeguimientoTablaQuery) => respuestas(q) } }] });
|
||||||
|
vi.spyOn(URL, 'createObjectURL').mockImplementation(() => 'blob:test');
|
||||||
|
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
|
||||||
|
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { descargas.push(this.download); });
|
||||||
|
});
|
||||||
|
afterEach(() => { fixture?.destroy(); vi.restoreAllMocks(); });
|
||||||
|
const montar = (r: SeguimientoTablaResponse, seleccion?: string) => {
|
||||||
|
fixture = TestBed.createComponent(TrackingExportBar);
|
||||||
|
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('respuesta', r);
|
||||||
|
fixture.componentRef.setInput('seleccion', seleccion); fixture.detectChanges();
|
||||||
|
return fixture.nativeElement as HTMLElement;
|
||||||
|
};
|
||||||
|
const excel = (root: HTMLElement) => [...root.querySelectorAll('button')].find(b => b.textContent!.includes('Excel')) as HTMLButtonElement;
|
||||||
|
const esperar = async () => { for (let i = 0; i < 20; i++) { await fixture.whenStable(); await new Promise(r => setTimeout(r, 10)); fixture.detectChanges(); } };
|
||||||
|
|
||||||
|
it('un archivo de una selección se llama como tal y no lleva a ningún paciente en el nombre', async () => {
|
||||||
|
// Fails if the file of a selection is told apart from a plain list by nothing, or names a patient.
|
||||||
|
const root = montar(cohorte(27)(consulta()), ETIQUETA);
|
||||||
|
excel(root).click(); await esperar();
|
||||||
|
expect(descargas).toHaveLength(1);
|
||||||
|
expect(descargas[0]).toMatch(/^seguimiento-cancer-de-mama-seleccion_corte-2026-10-20_\d{8}-\d{4}\.xlsx$/);
|
||||||
|
expect(descargas[0]).not.toMatch(/M-\d|cama/i);
|
||||||
|
});
|
||||||
|
it('si la consulta en pantalla cambia mientras se lee, se cancela y no se descarga nada', async () => {
|
||||||
|
// Fails if a list read for the old selection is downloaded as the one now on screen.
|
||||||
|
const lenta = new Subject<SeguimientoTablaResponse>();
|
||||||
|
respuestas = () => lenta;
|
||||||
|
const root = montar(cohorte(27)(consulta()), ETIQUETA);
|
||||||
|
excel(root).click(); fixture.detectChanges();
|
||||||
|
expect(root.textContent).toContain('Preparando exportación');
|
||||||
|
fixture.componentRef.setInput('respuesta', cohorte(27)(consulta({ filtros: { birads: 'BIRADS_6' } })));
|
||||||
|
fixture.componentRef.setInput('seleccion', 'Cáncer confirmado: Categoría BI-RADS, BI-RADS 6'); fixture.detectChanges();
|
||||||
|
lenta.next(cohorte(27)(consulta()));
|
||||||
|
await esperar();
|
||||||
|
expect(descargas).toEqual([]);
|
||||||
|
expect(root.querySelector('[role=alert]')?.textContent).toContain('La consulta cambió; se canceló la exportación');
|
||||||
|
expect(excel(root).disabled).toBe(false);
|
||||||
|
});
|
||||||
|
it('si cambia mientras se genera el archivo, tampoco se descarga', async () => {
|
||||||
|
// Fails if a file finished after the selection changed still reaches the downloads.
|
||||||
|
const root = montar(cohorte(27)(consulta()), ETIQUETA);
|
||||||
|
excel(root).click();
|
||||||
|
fixture.componentRef.setInput('seleccion', 'Cáncer confirmado: Categoría BI-RADS, BI-RADS 6'); fixture.detectChanges();
|
||||||
|
await esperar();
|
||||||
|
expect(descargas).toEqual([]);
|
||||||
|
expect(root.querySelector('[role=alert]')?.textContent).toContain('La consulta cambió');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { concatWith, defer, from, map, mergeMap, Observable, of, startWith, switchMap, tap } from 'rxjs';
|
import { concatWith, defer, from, map, mergeMap, Observable, of, startWith, switchMap, tap } from 'rxjs';
|
||||||
import { Dominio } from '../indicadores.models';
|
import { Dominio } from '../indicadores.models';
|
||||||
import { PAGE_SIZE_MAX, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService } from '../seguimiento-tabla.service';
|
import { identidadesDe } from '../paciente-identidad';
|
||||||
|
import { consultaAplicada, contextoDe, PAGE_SIZE_MAX, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService } from '../seguimiento-tabla.service';
|
||||||
import { ExportInconsistent, ExportLimitExceeded, TrackingExportEvent, TrackingRow } from './tracking-export.models';
|
import { ExportInconsistent, ExportLimitExceeded, TrackingExportEvent, TrackingRow } from './tracking-export.models';
|
||||||
|
|
||||||
const CONCURRENCY = 3;
|
const CONCURRENCY = 3;
|
||||||
@@ -13,17 +14,14 @@ export function queryOf(response: SeguimientoTablaResponse): SeguimientoTablaQue
|
|||||||
page: 1,
|
page: 1,
|
||||||
page_size: PAGE_SIZE_MAX,
|
page_size: PAGE_SIZE_MAX,
|
||||||
filtros: Object.fromEntries(Object.entries(response.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])),
|
filtros: Object.fromEntries(Object.entries(response.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])),
|
||||||
|
// A cohort's list is exported as that cohort, at the revision it was read at: another revision is refused by the server.
|
||||||
|
contexto: contextoDe(response),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// The server must report having applied the window and the filters that were asked for; otherwise the file would
|
// The server must report having applied the window and the filters that were asked for; otherwise the file would
|
||||||
// hold rows of another query under the title of this one.
|
// hold rows of another query under the title of this one.
|
||||||
function sameQuery(query: SeguimientoTablaQuery, answer: SeguimientoTablaResponse): boolean {
|
const sameQuery = consultaAplicada;
|
||||||
const entries = (filters: Record<string, string | null | undefined>) =>
|
|
||||||
JSON.stringify(Object.entries(filters).filter(([, v]) => !!v).sort(([a], [b]) => a.localeCompare(b)));
|
|
||||||
return answer.ventana.meses === query.meses && (!query.corte || answer.corte === query.corte)
|
|
||||||
&& entries(query.filtros ?? {}) === entries(answer.filtros);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reads every row a follow-up query matches, page by page, with the cut-off fixed by the first answer.
|
* Reads every row a follow-up query matches, page by page, with the cut-off fixed by the first answer.
|
||||||
@@ -44,7 +42,7 @@ export function fetchAllTracking(service: SeguimientoTablaService, dominio: Domi
|
|||||||
mergeMap(page => ask({ ...pinned, page }).pipe(map(answer => ({ page, answer }))), CONCURRENCY),
|
mergeMap(page => ask({ ...pinned, page }).pipe(map(answer => ({ page, answer }))), CONCURRENCY),
|
||||||
tap(({ page, answer }) => {
|
tap(({ page, answer }) => {
|
||||||
if (answer.paginacion.page !== page || answer.paginacion.total_items !== total || answer.paginacion.total_pages !== pages
|
if (answer.paginacion.page !== page || answer.paginacion.total_items !== total || answer.paginacion.total_pages !== pages
|
||||||
|| answer.corte !== first.corte) throw new ExportInconsistent('The list changed while it was being read');
|
|| answer.corte !== first.corte || !sameQuery(pinned, answer)) throw new ExportInconsistent('The list changed while it was being read');
|
||||||
collected.set(page, answer.items);
|
collected.set(page, answer.items);
|
||||||
}),
|
}),
|
||||||
map((): TrackingExportEvent => ({ kind: 'progress', fetched: count(), total })),
|
map((): TrackingExportEvent => ({ kind: 'progress', fetched: count(), total })),
|
||||||
@@ -53,8 +51,8 @@ export function fetchAllTracking(service: SeguimientoTablaService, dominio: Domi
|
|||||||
startWith<TrackingExportEvent>({ kind: 'progress', fetched: first.items.length, total }),
|
startWith<TrackingExportEvent>({ kind: 'progress', fetched: first.items.length, total }),
|
||||||
concatWith(defer(() => {
|
concatWith(defer(() => {
|
||||||
const items = [...collected.entries()].sort(([a], [b]) => a - b).flatMap(([, rows]) => rows);
|
const items = [...collected.entries()].sort(([a], [b]) => a - b).flatMap(([, rows]) => rows);
|
||||||
const ids = new Set(items.map(item => item['id_seudonimo']));
|
// Every row has the identity the table shows, and no patient (or episode) appears on two pages.
|
||||||
if (items.length !== total || ids.size !== total) throw new ExportInconsistent('The pages do not add up to the announced total');
|
if (items.length !== total || !identidadesDe(items)) throw new ExportInconsistent('The pages do not add up to the announced total');
|
||||||
return of<TrackingExportEvent>({
|
return of<TrackingExportEvent>({
|
||||||
kind: 'done',
|
kind: 'done',
|
||||||
snapshot: { corte: first.corte, ventana: first.ventana, filtros: first.filtros, filtros_disponibles: first.filtros_disponibles, columnas: first.columnas, items },
|
snapshot: { corte: first.corte, ventana: first.ventana, filtros: first.filtros, filtros_disponibles: first.filtros_disponibles, columnas: first.columnas, items },
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { SeguimientoTablaResponse, SeguimientoValor } from '../seguimiento-tabla.service';
|
import { etiquetaVentana, SeguimientoTablaResponse, SeguimientoValor } from '../seguimiento-tabla.service';
|
||||||
|
|
||||||
/** Largest number of rows each format accepts. A query above the limit is refused, never truncated. */
|
/** Largest number of rows each format accepts. A query above the limit is refused, never truncated. */
|
||||||
export const EXPORT_LIMITS = { xlsx: 5000, pdf: 1000 } as const;
|
export const EXPORT_LIMITS = { xlsx: 5000, pdf: 1000 } as const;
|
||||||
@@ -8,6 +8,8 @@ export type TrackingRow = Record<string, SeguimientoValor>;
|
|||||||
|
|
||||||
/** Everything one export needs: the first answer (columns, filters, window) and all the rows it announced. */
|
/** Everything one export needs: the first answer (columns, filters, window) and all the rows it announced. */
|
||||||
export interface TrackingSnapshot {
|
export interface TrackingSnapshot {
|
||||||
|
/** How the analysis named the selection this list opens, when it does; the files carry it so they say where they come from. */
|
||||||
|
seleccion?: string;
|
||||||
corte: string;
|
corte: string;
|
||||||
ventana: SeguimientoTablaResponse['ventana'];
|
ventana: SeguimientoTablaResponse['ventana'];
|
||||||
filtros: SeguimientoTablaResponse['filtros'];
|
filtros: SeguimientoTablaResponse['filtros'];
|
||||||
@@ -16,6 +18,12 @@ export interface TrackingSnapshot {
|
|||||||
items: TrackingRow[];
|
items: TrackingRow[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The window as the files state it: the whole cohort up to the cut-off, or the dates and months of the window. */
|
||||||
|
export function ventanaConsultada(snapshot: Pick<TrackingSnapshot, 'ventana'>): string {
|
||||||
|
const { meses, desde, hasta } = snapshot.ventana;
|
||||||
|
return meses === 0 ? `Toda la cohorte, al ${hasta}` : `${desde} al ${hasta} (${etiquetaVentana(meses)})`;
|
||||||
|
}
|
||||||
|
|
||||||
export type TrackingExportEvent =
|
export type TrackingExportEvent =
|
||||||
| { kind: 'progress'; fetched: number; total: number }
|
| { kind: 'progress'; fetched: number; total: number }
|
||||||
| { kind: 'done'; snapshot: TrackingSnapshot };
|
| { kind: 'done'; snapshot: TrackingSnapshot };
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { renderPdf, PdfDefinition } from './pdf-engine';
|
import { renderPdf, PdfDefinition } from './pdf-engine';
|
||||||
import { COLORS, institutionalDocument, loadLogo } from './pdf-template';
|
import { COLORS, institutionalDocument, loadLogo } from './pdf-template';
|
||||||
import { displayText, exportColumns } from './tracking-export-table';
|
import { displayText, exportColumns } from './tracking-export-table';
|
||||||
import { TrackingSnapshot } from './tracking-export.models';
|
import { TrackingSnapshot, ventanaConsultada } from './tracking-export.models';
|
||||||
|
|
||||||
export const TRACKING_TITLE = 'Cáncer de mama';
|
export const TRACKING_TITLE = 'Cáncer de mama';
|
||||||
|
|
||||||
@@ -11,8 +11,9 @@ const zebra = { ...rule, fillColor: (row: number) => (row === 0 ? undefined : ro
|
|||||||
/** What the query was: cut-off, window, each announced filter with its chosen option, and how many rows follow. */
|
/** What the query was: cut-off, window, each announced filter with its chosen option, and how many rows follow. */
|
||||||
function parameters(snapshot: TrackingSnapshot) {
|
function parameters(snapshot: TrackingSnapshot) {
|
||||||
const rows: unknown[][] = [
|
const rows: unknown[][] = [
|
||||||
|
...(snapshot.seleccion ? [['Selección del análisis', snapshot.seleccion]] : []),
|
||||||
['Fecha de corte', snapshot.corte],
|
['Fecha de corte', snapshot.corte],
|
||||||
['Ventana consultada', `${snapshot.ventana.desde} al ${snapshot.ventana.hasta} (${snapshot.ventana.meses} ${snapshot.ventana.meses === 1 ? 'mes' : 'meses'})`],
|
['Ventana consultada', ventanaConsultada(snapshot)],
|
||||||
...snapshot.filtros_disponibles.map(f => [f.etiqueta, f.opciones.find(o => o.codigo === snapshot.filtros[f.clave])?.etiqueta ?? 'Todos']),
|
...snapshot.filtros_disponibles.map(f => [f.etiqueta, f.opciones.find(o => o.codigo === snapshot.filtros[f.clave])?.etiqueta ?? 'Todos']),
|
||||||
['Registros', String(snapshot.items.length)],
|
['Registros', String(snapshot.items.length)],
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { Feature, SheetData } from 'write-excel-file/browser';
|
import type { Feature, SheetData } from 'write-excel-file/browser';
|
||||||
import { neutralizeFormula } from './cell-sanitizer';
|
import { neutralizeFormula } from './cell-sanitizer';
|
||||||
import { flatTable } from './tracking-export-table';
|
import { flatTable } from './tracking-export-table';
|
||||||
import { TrackingSnapshot } from './tracking-export.models';
|
import { TrackingSnapshot, ventanaConsultada } from './tracking-export.models';
|
||||||
|
|
||||||
export const DATA_SHEET = 'Seguimiento';
|
export const DATA_SHEET = 'Seguimiento';
|
||||||
export const PARAMETERS_SHEET = 'Parámetros';
|
export const PARAMETERS_SHEET = 'Parámetros';
|
||||||
@@ -49,8 +49,9 @@ export function parameterRows(snapshot: TrackingSnapshot, now: Date): SheetData
|
|||||||
return [
|
return [
|
||||||
[header('Parámetro'), header('Valor')],
|
[header('Parámetro'), header('Valor')],
|
||||||
row('Reporte', 'Cáncer de mama'),
|
row('Reporte', 'Cáncer de mama'),
|
||||||
|
...(snapshot.seleccion ? [row('Selección del análisis', snapshot.seleccion)] : []),
|
||||||
row('Fecha de corte', snapshot.corte),
|
row('Fecha de corte', snapshot.corte),
|
||||||
row('Ventana consultada', `${snapshot.ventana.desde} al ${snapshot.ventana.hasta} (${snapshot.ventana.meses} ${snapshot.ventana.meses === 1 ? 'mes' : 'meses'})`),
|
row('Ventana consultada', ventanaConsultada(snapshot)),
|
||||||
...filters,
|
...filters,
|
||||||
row('Total de registros', snapshot.items.length),
|
row('Total de registros', snapshot.items.length),
|
||||||
row('Generado', generatedAt(now)),
|
row('Generado', generatedAt(now)),
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
// The parts of FHIR R4 the WebApi's `/<domain>/fhir/` endpoints serve, read loosely: every field is optional and the
|
||||||
|
// readers below decide what a missing one means.
|
||||||
|
|
||||||
|
export interface Coding { system?: string; code?: string; display?: string }
|
||||||
|
export interface Concept { coding?: Coding[]; text?: string }
|
||||||
|
export interface Quantity { value?: number; unit?: string }
|
||||||
|
export interface Extension {
|
||||||
|
url: string;
|
||||||
|
valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number;
|
||||||
|
valueDate?: string; valueDateTime?: string; valueCoding?: Coding; valueReference?: { reference?: string };
|
||||||
|
extension?: Extension[];
|
||||||
|
}
|
||||||
|
export interface Resource {
|
||||||
|
resourceType: string;
|
||||||
|
id?: string;
|
||||||
|
meta?: { tag?: Coding[] };
|
||||||
|
extension?: Extension[];
|
||||||
|
[field: string]: unknown;
|
||||||
|
}
|
||||||
|
export interface Bundle extends Resource {
|
||||||
|
total?: number;
|
||||||
|
entry?: { fullUrl?: string; resource: Resource; search?: { mode?: string } }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CODE_SYSTEM = 'https://isssteleon.org/fhir/CodeSystem/';
|
||||||
|
|
||||||
|
export function code(concept: Concept | undefined): string | undefined {
|
||||||
|
return concept?.coding?.[0]?.code;
|
||||||
|
}
|
||||||
|
export function display(concept: Concept | undefined): string | undefined {
|
||||||
|
return concept?.coding?.[0]?.display ?? concept?.text;
|
||||||
|
}
|
||||||
|
// The code of a concept from `system` (a name under the project's CodeSystem base, or a full URL).
|
||||||
|
export function codeIn(concept: Concept | undefined, system: string): string | undefined {
|
||||||
|
const url = system.includes('://') ? system : CODE_SYSTEM + system;
|
||||||
|
return concept?.coding?.find(c => c.system === url)?.code;
|
||||||
|
}
|
||||||
|
// The extensions named `name` (the last segment of their URL).
|
||||||
|
export function extensions(owner: { extension?: Extension[] } | undefined, name: string): Extension[] {
|
||||||
|
return (owner?.extension ?? []).filter(e => e.url === name || e.url.endsWith('/' + name));
|
||||||
|
}
|
||||||
|
export function extension(owner: { extension?: Extension[] } | undefined, name: string): Extension | undefined {
|
||||||
|
return extensions(owner, name)[0];
|
||||||
|
}
|
||||||
|
export function resources(bundle: Bundle | undefined, type?: string): Resource[] {
|
||||||
|
return (bundle?.entry ?? []).map(e => e.resource).filter(r => !type || r.resourceType === type);
|
||||||
|
}
|
||||||
|
export function isSimulated(resource: Resource): boolean {
|
||||||
|
return !!resource.meta?.tag?.some(t => t.code === 'simulado');
|
||||||
|
}
|
||||||
|
// `Patient/P-1` -> `P-1`.
|
||||||
|
export function referenceId(reference: { reference?: string } | undefined): string | undefined {
|
||||||
|
return reference?.reference?.split('/').pop();
|
||||||
|
}
|
||||||
+85
@@ -0,0 +1,85 @@
|
|||||||
|
{
|
||||||
|
"resourceType": "Bundle",
|
||||||
|
"type": "searchset",
|
||||||
|
"total": 1,
|
||||||
|
"entry": [
|
||||||
|
{
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "MeasureReport",
|
||||||
|
"status": "complete",
|
||||||
|
"type": "summary",
|
||||||
|
"measure": "cacu/CACU_DIAS_TOMA_DIAGNOSTICO|0.2.3",
|
||||||
|
"date": "2026-11-08T06:47:32.900609+00:00",
|
||||||
|
"period": {
|
||||||
|
"start": "2025-07-01",
|
||||||
|
"end": "2025-12-31"
|
||||||
|
},
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
|
||||||
|
"valueInteger": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-evento",
|
||||||
|
"valueDate": "2026-11-08"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
|
||||||
|
"valueDateTime": "2026-11-08T06:47:32.766239+00:00"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"group": [
|
||||||
|
{
|
||||||
|
"id": "TOTAL",
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 4
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "measure-observation"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 2
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"measureScore": {
|
||||||
|
"value": 100.5,
|
||||||
|
"unit": "d",
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/q1",
|
||||||
|
"valueDecimal": 70.25
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/q3",
|
||||||
|
"valueDecimal": 130.75
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"improvementNotation": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||||
|
"code": "decrease"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
{
|
||||||
|
"resourceType": "Bundle",
|
||||||
|
"type": "searchset",
|
||||||
|
"total": 1,
|
||||||
|
"entry": [
|
||||||
|
{
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "MeasureReport",
|
||||||
|
"status": "complete",
|
||||||
|
"type": "summary",
|
||||||
|
"measure": "cacu/CACU_EU13|0.3.2",
|
||||||
|
"date": "2026-11-08T00:28:51.413089+00:00",
|
||||||
|
"period": {
|
||||||
|
"start": "2025-01-01",
|
||||||
|
"end": "2025-06-30"
|
||||||
|
},
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
|
||||||
|
"valueInteger": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
|
||||||
|
"valueDateTime": "2026-11-08T00:28:51.351883+00:00"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"group": [
|
||||||
|
{
|
||||||
|
"id": "principal",
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 4
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "denominator"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 4
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "numerator"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 0
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"measureScore": {
|
||||||
|
"value": 0.0
|
||||||
|
},
|
||||||
|
"stratifier": [
|
||||||
|
{
|
||||||
|
"code": [
|
||||||
|
{
|
||||||
|
"text": "grupo_edad"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"stratum": [
|
||||||
|
{
|
||||||
|
"value": {
|
||||||
|
"text": "45-54"
|
||||||
|
},
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 4
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "denominator"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 4
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "numerator"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 0
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"measureScore": {
|
||||||
|
"value": 0.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,295 @@
|
|||||||
|
{
|
||||||
|
"resourceType": "Bundle",
|
||||||
|
"type": "searchset",
|
||||||
|
"total": 2,
|
||||||
|
"entry": [
|
||||||
|
{
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "MeasureReport",
|
||||||
|
"status": "complete",
|
||||||
|
"type": "summary",
|
||||||
|
"measure": "cacu/CACU_EU7|0.3.3",
|
||||||
|
"date": "2026-11-08T00:28:56.089006+00:00",
|
||||||
|
"period": {
|
||||||
|
"start": "2025-01-01",
|
||||||
|
"end": "2025-06-30"
|
||||||
|
},
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
|
||||||
|
"valueInteger": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
|
||||||
|
"valueDateTime": "2026-11-08T00:28:56.025101+00:00"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"group": [
|
||||||
|
{
|
||||||
|
"id": "TOTAL",
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 4
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "measure-observation"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 4
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"stratifier": [
|
||||||
|
{
|
||||||
|
"code": [
|
||||||
|
{
|
||||||
|
"text": "resultado"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"stratum": [
|
||||||
|
{
|
||||||
|
"value": {
|
||||||
|
"text": "LIEBG"
|
||||||
|
},
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"value": {
|
||||||
|
"text": "NEGATIVO"
|
||||||
|
},
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 2
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"value": {
|
||||||
|
"text": "SIN_DATO"
|
||||||
|
},
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": [
|
||||||
|
{
|
||||||
|
"text": "grupo_edad"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"stratum": [
|
||||||
|
{
|
||||||
|
"value": {
|
||||||
|
"text": "45-54"
|
||||||
|
},
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 4
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "MeasureReport",
|
||||||
|
"status": "complete",
|
||||||
|
"type": "summary",
|
||||||
|
"measure": "cacu/CACU_EU7|0.3.3",
|
||||||
|
"date": "2026-11-08T00:28:56.099338+00:00",
|
||||||
|
"period": {
|
||||||
|
"start": "2025-07-01",
|
||||||
|
"end": "2025-12-31"
|
||||||
|
},
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
|
||||||
|
"valueInteger": 2
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
|
||||||
|
"valueDateTime": "2026-11-08T00:28:56.025101+00:00"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"group": [
|
||||||
|
{
|
||||||
|
"id": "TOTAL",
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 4
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "measure-observation"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 4
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"stratifier": [
|
||||||
|
{
|
||||||
|
"code": [
|
||||||
|
{
|
||||||
|
"text": "resultado"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"stratum": [
|
||||||
|
{
|
||||||
|
"value": {
|
||||||
|
"text": "LIEAG"
|
||||||
|
},
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"value": {
|
||||||
|
"text": "NEGATIVO"
|
||||||
|
},
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"value": {
|
||||||
|
"text": "SIN_DATO"
|
||||||
|
},
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 2
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": [
|
||||||
|
{
|
||||||
|
"text": "grupo_edad"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"stratum": [
|
||||||
|
{
|
||||||
|
"value": {
|
||||||
|
"text": "45-54"
|
||||||
|
},
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 4
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
{
|
||||||
|
"resourceType": "Bundle",
|
||||||
|
"type": "searchset",
|
||||||
|
"total": 2,
|
||||||
|
"entry": [
|
||||||
|
{
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "MeasureReport",
|
||||||
|
"status": "complete",
|
||||||
|
"type": "summary",
|
||||||
|
"measure": "cacu/IND1|0.3.2",
|
||||||
|
"date": "2026-11-08T00:28:50.038223+00:00",
|
||||||
|
"period": {
|
||||||
|
"start": "2025-01-01",
|
||||||
|
"end": "2025-06-30"
|
||||||
|
},
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
|
||||||
|
"valueInteger": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
|
||||||
|
"valueDateTime": "2026-11-08T00:28:49.977023+00:00"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"group": [
|
||||||
|
{
|
||||||
|
"id": "principal",
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 4
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "denominator"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 4
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "numerator"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"measureScore": {
|
||||||
|
"value": 0.25
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"improvementNotation": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||||
|
"code": "decrease"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "MeasureReport",
|
||||||
|
"status": "complete",
|
||||||
|
"type": "summary",
|
||||||
|
"measure": "cacu/IND1|0.3.2",
|
||||||
|
"date": "2026-11-08T00:28:50.044435+00:00",
|
||||||
|
"period": {
|
||||||
|
"start": "2025-07-01",
|
||||||
|
"end": "2025-12-31"
|
||||||
|
},
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
|
||||||
|
"valueInteger": 2
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
|
||||||
|
"valueDateTime": "2026-11-08T00:28:49.977023+00:00"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"group": [
|
||||||
|
{
|
||||||
|
"id": "principal",
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 4
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "denominator"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 4
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "numerator"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"measureScore": {
|
||||||
|
"value": 0.25
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"improvementNotation": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||||
|
"code": "decrease"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "dimensiones": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "medidas": [{"clave": "maligno", "etiqueta": "Carcinoma in situ o invasor"}, {"clave": "invasor", "etiqueta": "Carcinoma invasor"}], "horizontes_dias": [30, 90, 180, 365], "tipos_periodo": ["mes", "semestre"], "secciones": [{"clave": "resumen", "titulo": "Indicadores de la cohorte", "estado": "disponible", "motivo": null}, {"clave": "distribucion", "titulo": "Distribución de pacientes", "estado": "disponible", "motivo": null}, {"clave": "comparacion", "titulo": "Comparación entre grupos", "estado": "disponible", "motivo": null}, {"clave": "mapa", "titulo": "Mapa entre variables", "estado": "disponible", "motivo": null}, {"clave": "tendencia", "titulo": "Tendencia en el tiempo", "estado": "disponible", "motivo": null}], "no_disponibles": [{"clave": "supervivencia", "titulo": "Supervivencia", "motivo": "No hay estado vital ni fecha de defunción en las fuentes."}, {"clave": "recaida", "titulo": "Recaída", "motivo": "No hay registro de recurrencia ni de tratamiento en las fuentes."}, {"clave": "adherencia_tratamiento", "titulo": "Adherencia al tratamiento", "motivo": "No hay tabla de tratamientos ni de visitas de seguimiento."}, {"clave": "curvas_tiempo_a_evento", "titulo": "Curvas de incidencia acumulada y de supervivencia", "motivo": "El seguimiento de quien no tuvo el evento no está registrado: no hay censura verificable ni tiempo cero común, y la muerte como riesgo competitivo no existe."}, {"clave": "riesgos_proporcionales", "titulo": "Razones de riesgo (Cox), log-rank y tiempo medio restringido", "motivo": "Dependen de las curvas anteriores."}, {"clave": "brca_estadio_tamano", "titulo": "BRCA, estadio clínico y tamaño tumoral", "motivo": "No hay registros de estas variables en las fuentes."}]}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "birads", "medida": "maligno", "denominador": "pacientes con resultado de biopsia conocido", "grupos": [{"estado": "suprimido", "casos": null, "total": null, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4", "etiqueta": "BI-RADS 4", "seleccion": {"birads": "BIRADS_4"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A", "seleccion": {"birads": "BIRADS_4A"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B", "seleccion": {"birads": "BIRADS_4B"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C", "seleccion": {"birads": "BIRADS_4C"}}, {"estado": "suprimido", "casos": null, "total": null, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_5", "etiqueta": "BI-RADS 5", "seleccion": {"birads": "BIRADS_5"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_6", "etiqueta": "BI-RADS 6", "seleccion": {"birads": "BIRADS_6"}}], "prueba": {"valida": false, "motivo": "Hacen falta al menos dos grupos con datos publicados.", "nombre": "Chi cuadrada de homogeneidad"}}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "grupo_edad", "medida": "invasor", "denominador": "pacientes con resultado de biopsia conocido", "grupos": [{"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "<40", "etiqueta": "<40", "seleccion": {"grupo_edad": "<40"}}, {"estado": "disponible", "casos": 5, "total": 12, "valor": 41.67, "ic_bajo": 19.33, "ic_alto": 68.05, "codigo": "40-49", "etiqueta": "40-49", "seleccion": {"grupo_edad": "40-49"}}, {"estado": "disponible", "casos": 6, "total": 13, "valor": 46.15, "ic_bajo": 23.21, "ic_alto": 70.86, "codigo": "50-59", "etiqueta": "50-59", "seleccion": {"grupo_edad": "50-59"}}, {"estado": "disponible", "casos": 8, "total": 17, "valor": 47.06, "ic_bajo": 26.17, "ic_alto": 69.04, "codigo": "60-69", "etiqueta": "60-69", "seleccion": {"grupo_edad": "60-69"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "70+", "etiqueta": "70+", "seleccion": {"grupo_edad": "70+"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "SIN_DATO", "etiqueta": "Sin dato", "seleccion": {"grupo_edad": "SIN_DATO"}}], "prueba": {"valida": true, "estadistico": 0.0889, "gl": 2, "p": 0.9565070599102384, "nombre": "Chi cuadrada de homogeneidad"}}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "biopsia", "total": 61, "items": [{"codigo": "BENIGNO", "etiqueta": "Benigno", "suprimido": false, "n": 21, "porcentaje": 34.43, "ic_bajo": 23.75, "ic_alto": 46.95, "seleccion": {"biopsia": "BENIGNO"}}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"biopsia": "CARCINOMA_IN_SITU"}}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"biopsia": "CARCINOMA_INVASOR"}}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"biopsia": "SIN_DATO"}}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada", "suprimido": false, "n": 19, "porcentaje": 31.15, "ic_bajo": 20.94, "ic_alto": 43.59, "seleccion": {"biopsia": "SIN_BIOPSIA"}}]}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "birads", "total": 61, "items": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4", "suprimido": false, "n": 33, "porcentaje": 54.1, "ic_bajo": 41.72, "ic_alto": 65.99, "seleccion": {"birads": "BIRADS_4"}}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4A"}}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4B"}}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4C"}}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"birads": "BIRADS_5"}}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"birads": "BIRADS_6"}}]}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "grupo_edad", "total": 61, "items": [{"codigo": "<40", "etiqueta": "<40", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "<40"}}, {"codigo": "40-49", "etiqueta": "40-49", "suprimido": false, "n": 16, "porcentaje": 26.23, "ic_bajo": 16.84, "ic_alto": 38.44, "seleccion": {"grupo_edad": "40-49"}}, {"codigo": "50-59", "etiqueta": "50-59", "suprimido": false, "n": 19, "porcentaje": 31.15, "ic_bajo": 20.94, "ic_alto": 43.59, "seleccion": {"grupo_edad": "50-59"}}, {"codigo": "60-69", "etiqueta": "60-69", "suprimido": false, "n": 26, "porcentaje": 42.62, "ic_bajo": 31.02, "ic_alto": 55.1, "seleccion": {"grupo_edad": "60-69"}}, {"codigo": "70+", "etiqueta": "70+", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "70+"}}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "SIN_DATO"}}]}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"simulado": true, "cohorte": "cama_birads_v1", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "escenario": "diagnostico", "corte": "2026-11-16", "umbral_supresion": 5, "unidad": "paciente", "denominador": "pacientes elegibles con última mastografía reportada BI-RADS 4 a 6", "grupos": [{"codigo": "BIRADS_4", "n": 33, "suprimido": false}, {"codigo": "BIRADS_4A", "n": 0, "suprimido": false}, {"codigo": "BIRADS_4B", "n": 0, "suprimido": false}, {"codigo": "BIRADS_4C", "n": 0, "suprimido": false}, {"codigo": "BIRADS_5", "n": null, "suprimido": true}, {"codigo": "BIRADS_6", "n": null, "suprimido": true}], "horizonte_dias": 0, "indicadores": []}
|
||||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
|||||||
|
{"error": "la selección tiene menos de 5 pacientes: su lista no se publica.", "motivo": "supresion"}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "horizonte_dias": 90, "indicadores": [{"clave": "cohorte", "titulo": "Pacientes en la cohorte BI-RADS 4 a 6", "descripcion": "Pacientes cuya última mastografía reportada al corte es BI-RADS 4, 5 o 6.", "unidad": "pacientes", "estado": "disponible", "valor": 61, "ic_bajo": null, "ic_alto": null, "n": 61, "denominador": null, "q1": null, "q3": null, "motivo": null}, {"clave": "con_biopsia", "titulo": "Con biopsia reportada", "descripcion": "Pacientes de la cohorte con al menos un reporte de biopsia de esa mastografía, entre las de la cohorte.", "unidad": "%", "estado": "disponible", "valor": 68.85, "ic_bajo": 56.41, "ic_alto": 79.06, "n": 42, "denominador": 61, "q1": null, "q3": null, "motivo": null}, {"clave": "maligno_conocido", "titulo": "Resultado maligno entre las biopsias con resultado", "descripcion": "Carcinoma in situ o invasor entre las pacientes de la cohorte con resultado de biopsia conocido. No es incidencia: el denominador son pacientes ya biopsiadas.", "unidad": "%", "estado": "disponible", "valor": 50.0, "ic_bajo": 35.53, "ic_alto": 64.47, "n": 21, "denominador": 42, "q1": null, "q3": null, "motivo": null}, {"clave": "invasor_conocido", "titulo": "Carcinoma invasor entre las biopsias con resultado", "descripcion": "Carcinoma invasor entre las pacientes de la cohorte con resultado de biopsia conocido.", "unidad": "%", "estado": "disponible", "valor": 45.24, "ic_bajo": 31.22, "ic_alto": 60.05, "n": 19, "denominador": 42, "q1": null, "q3": null, "motivo": null}, {"clave": "biopsia_90d", "titulo": "Biopsia reportada en 90 días", "descripcion": "Pacientes cuya biopsia se reportó dentro de 90 días de la mastografía, entre las que ya cumplieron 90 días al corte.", "unidad": "%", "estado": "disponible", "valor": 75.56, "ic_bajo": 61.33, "ic_alto": 85.76, "n": 34, "denominador": 45, "q1": null, "q3": null, "motivo": null}, {"clave": "maligno_90d", "titulo": "Cáncer confirmado en 90 días", "descripcion": "Pacientes con un reporte de biopsia maligna dentro de 90 días de la mastografía, entre las que ya cumplieron 90 días al corte. No es incidencia acumulada: no hay seguimiento de quien no tuvo biopsia.", "unidad": "%", "estado": "disponible", "valor": 40.0, "ic_bajo": 27.02, "ic_alto": 54.55, "n": 18, "denominador": 45, "q1": null, "q3": null, "motivo": null}, {"clave": "dias_a_biopsia", "titulo": "Días de la mastografía al reporte de biopsia", "descripcion": "Mediana y cuartiles entre las pacientes con biopsia reportada.", "unidad": "días", "estado": "disponible", "valor": 27.5, "ic_bajo": null, "ic_alto": null, "n": 42, "denominador": null, "q1": 19.25, "q3": 30.75, "motivo": null}], "no_disponibles": [{"clave": "supervivencia", "titulo": "Supervivencia", "motivo": "No hay estado vital ni fecha de defunción en las fuentes."}, {"clave": "recaida", "titulo": "Recaída", "motivo": "No hay registro de recurrencia ni de tratamiento en las fuentes."}, {"clave": "adherencia_tratamiento", "titulo": "Adherencia al tratamiento", "motivo": "No hay tabla de tratamientos ni de visitas de seguimiento."}, {"clave": "curvas_tiempo_a_evento", "titulo": "Curvas de incidencia acumulada y de supervivencia", "motivo": "El seguimiento de quien no tuvo el evento no está registrado: no hay censura verificable ni tiempo cero común, y la muerte como riesgo competitivo no existe."}, {"clave": "riesgos_proporcionales", "titulo": "Razones de riesgo (Cox), log-rank y tiempo medio restringido", "motivo": "Dependen de las curvas anteriores."}, {"clave": "brca_estadio_tamano", "titulo": "BRCA, estadio clínico y tamaño tumoral", "motivo": "No hay registros de estas variables en las fuentes."}]}
|
||||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
|||||||
|
{"corte": "2026-11-16", "umbral_supresion": 5, "tipo_periodo": "semestre", "unidad": "reportes", "poblacion": "Reportes de mastografía con BI-RADS reportado y reportes de biopsia vinculados a una de esas mastografías, de todas las pacientes; no la cohorte de Seguimiento", "alcance_biopsias": "Solo biopsias que se pueden ligar a una mastografía con BI-RADS reportado (mastografía, orden, reporte); una biopsia sin mastografía ligada no se cuenta", "denominador": "reportes de biopsia con resultado conocido en el periodo", "periodos": [{"periodo": "2025-S1", "inicio": "2025-01-01", "fin": "2025-06-30", "incompleto": false, "reportes_mastografia": {"total": 96, "por_categoria": {"4_a_6": {"n": 31, "suprimido": false}, "otras": {"n": 65, "suprimido": false}}}, "reportes_biopsia": {"total": 24, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 15, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 16, "total": 24, "valor": 66.67, "ic_bajo": 46.71, "ic_alto": 82.03}}, {"periodo": "2025-S2", "inicio": "2025-07-01", "fin": "2025-12-31", "incompleto": false, "reportes_mastografia": {"total": 97, "por_categoria": {"4_a_6": {"n": 37, "suprimido": false}, "otras": {"n": 60, "suprimido": false}}}, "reportes_biopsia": {"total": 25, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 13, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 14, "total": 25, "valor": 56.0, "ic_bajo": 37.07, "ic_alto": 73.33}}, {"periodo": "2026-S1", "inicio": "2026-01-01", "fin": "2026-06-30", "incompleto": false, "reportes_mastografia": {"total": 97, "por_categoria": {"4_a_6": {"n": 25, "suprimido": false}, "otras": {"n": 72, "suprimido": false}}}, "reportes_biopsia": {"total": 18, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 11, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 13, "total": 18, "valor": 72.22, "ic_bajo": 49.13, "ic_alto": 87.5}}, {"periodo": "2026-S2", "inicio": "2026-07-01", "fin": "2026-12-31", "incompleto": true, "reportes_mastografia": {"total": 72, "por_categoria": {"4_a_6": {"n": 27, "suprimido": false}, "otras": {"n": 45, "suprimido": false}}}, "reportes_biopsia": {"total": 19, "por_grado": {"BENIGNO": {"n": 9, "suprimido": false}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": null, "suprimido": true}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 10, "total": 19, "valor": 52.63, "ic_bajo": 31.71, "ic_alto": 72.67}}]}
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,842 @@
|
|||||||
|
{
|
||||||
|
"resourceType": "Bundle",
|
||||||
|
"type": "searchset",
|
||||||
|
"total": 8,
|
||||||
|
"link": [
|
||||||
|
{
|
||||||
|
"relation": "self",
|
||||||
|
"url": "http://127.0.0.1:28091/cama/fhir/Measure?_count=50&_offset=0"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"entry": [
|
||||||
|
{
|
||||||
|
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIOPSIAS",
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "Measure",
|
||||||
|
"id": "CAMA-BIOPSIAS",
|
||||||
|
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIOPSIAS",
|
||||||
|
"version": "0.2.0",
|
||||||
|
"name": "cama_biopsias",
|
||||||
|
"title": "Distribución de resultados de biopsia",
|
||||||
|
"status": "active",
|
||||||
|
"description": "Cuántas biopsias reportadas en el semestre caen en cada grado histológico. Se cuenta cada biopsia, no cada paciente. «Sin dato»: el reporte no trae grado.",
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||||
|
"valueCode": "C2"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||||
|
"valueCode": "semestre"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||||
|
"valueCode": "mes"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"scoring": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||||
|
"code": "cohort"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"group": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||||
|
"code": "TOTAL"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": "Unidades del periodo",
|
||||||
|
"criteria": {
|
||||||
|
"language": "text/x-dbt-metric",
|
||||||
|
"expression": "cama_biopsias"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"stratifier": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||||
|
"code": "grado"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"subjectCodeableConcept": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||||
|
"code": "examen"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"search": {
|
||||||
|
"mode": "match"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS",
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "Measure",
|
||||||
|
"id": "CAMA-BIRADS",
|
||||||
|
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS",
|
||||||
|
"version": "0.2.0",
|
||||||
|
"name": "cama_birads",
|
||||||
|
"title": "Distribución de BI-RADS",
|
||||||
|
"status": "active",
|
||||||
|
"description": "Cuántas pacientes caen en cada categoría de BI-RADS en el semestre, cada una en la más grave de sus mastografías. «Sin dato»: ninguna de sus mastografías tiene reporte con BI-RADS.",
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||||
|
"valueCode": "C2"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||||
|
"valueCode": "semestre"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||||
|
"valueCode": "mes"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"scoring": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||||
|
"code": "cohort"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"group": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||||
|
"code": "TOTAL"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": "Unidades del periodo",
|
||||||
|
"criteria": {
|
||||||
|
"language": "text/x-dbt-metric",
|
||||||
|
"expression": "cama_birads"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"stratifier": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||||
|
"code": "birads"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"subjectCodeableConcept": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||||
|
"code": "paciente"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"search": {
|
||||||
|
"mode": "match"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS-CANCER-INVASOR",
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "Measure",
|
||||||
|
"id": "CAMA-BIRADS-CANCER-INVASOR",
|
||||||
|
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS-CANCER-INVASOR",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"name": "cama_birads_cancer_invasor",
|
||||||
|
"title": "BI-RADS de los cánceres invasores",
|
||||||
|
"status": "active",
|
||||||
|
"description": "De las pacientes con una biopsia reportada en el periodo con carcinoma invasor, cuántas tenían cada BI-RADS en la mastografía que originó su biopsia más reciente, por edad y por las características del tumor: estadio clínico, etapa, subtipo molecular y tamaño. Las características vienen de los reportes leídos por texto y son provisionales. «Sin dato»: la biopsia no se ligó a una mastografía con BI-RADS.",
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||||
|
"valueCode": "C2"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||||
|
"valueCode": "semestre"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||||
|
"valueCode": "mes"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"scoring": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||||
|
"code": "cohort"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"group": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||||
|
"code": "TOTAL"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": "Unidades del periodo",
|
||||||
|
"criteria": {
|
||||||
|
"language": "text/x-dbt-metric",
|
||||||
|
"expression": "cama_birads_cancer_invasor"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"stratifier": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||||
|
"code": "birads"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||||
|
"code": "grupo_edad"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"text": "grupo_edad"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||||
|
"code": "estadio"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"text": "Estadio clínico"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||||
|
"code": "etapa"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"text": "Etapa"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||||
|
"code": "clasificacion"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"text": "Subtipo molecular"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||||
|
"code": "tamano"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"text": "Tamaño tumoral (T)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"subjectCodeableConcept": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||||
|
"code": "paciente"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"search": {
|
||||||
|
"mode": "match"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS456-MASTOGRAFIA",
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "Measure",
|
||||||
|
"id": "CAMA-BIRADS456-MASTOGRAFIA",
|
||||||
|
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS456-MASTOGRAFIA",
|
||||||
|
"version": "0.2.0",
|
||||||
|
"name": "cama_birads_456_mastografia",
|
||||||
|
"title": "Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6",
|
||||||
|
"status": "active",
|
||||||
|
"description": "Cuántas mastografías tomadas en el periodo tienen BI-RADS 4, 5 o 6, cada una con su categoría.",
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||||
|
"valueCode": "C2"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||||
|
"valueCode": "semestre"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||||
|
"valueCode": "mes"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"scoring": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||||
|
"code": "cohort"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"group": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||||
|
"code": "TOTAL"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": "Unidades del periodo",
|
||||||
|
"criteria": {
|
||||||
|
"language": "text/x-dbt-metric",
|
||||||
|
"expression": "cama_birads_456_mastografia"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"stratifier": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||||
|
"code": "birads"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"subjectCodeableConcept": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||||
|
"code": "examen"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"search": {
|
||||||
|
"mode": "match"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS456-PACIENTE",
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "Measure",
|
||||||
|
"id": "CAMA-BIRADS456-PACIENTE",
|
||||||
|
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS456-PACIENTE",
|
||||||
|
"version": "0.2.0",
|
||||||
|
"name": "cama_birads_456_paciente",
|
||||||
|
"title": "Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6",
|
||||||
|
"status": "active",
|
||||||
|
"description": "Cuántas pacientes tienen como BI-RADS más grave del periodo un 4, 5 o 6, cada una en la más grave de sus mastografías.",
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||||
|
"valueCode": "C2"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||||
|
"valueCode": "semestre"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||||
|
"valueCode": "mes"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"scoring": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||||
|
"code": "cohort"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"group": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||||
|
"code": "TOTAL"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": "Unidades del periodo",
|
||||||
|
"criteria": {
|
||||||
|
"language": "text/x-dbt-metric",
|
||||||
|
"expression": "cama_birads_456_paciente"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"stratifier": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||||
|
"code": "birads"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"subjectCodeableConcept": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||||
|
"code": "paciente"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"search": {
|
||||||
|
"mode": "match"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-CONFIRMACION-BIRADS45",
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "Measure",
|
||||||
|
"id": "CAMA-CONFIRMACION-BIRADS45",
|
||||||
|
"url": "https://isssteleon.org/fhir/Measure/CAMA-CONFIRMACION-BIRADS45",
|
||||||
|
"version": "0.2.0",
|
||||||
|
"name": "cama_confirmacion_birads45",
|
||||||
|
"title": "Tasa de confirmación histopatológica",
|
||||||
|
"status": "active",
|
||||||
|
"description": "De las mastografías del semestre con BI-RADS de sospecha, las que tienen una biopsia reportada originada por esa mastografía. A la fecha de corte: sin un plazo máximo, el valor puede subir mientras lleguen reportes. No dice si la biopsia confirmó cáncer.",
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||||
|
"valueCode": "C1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||||
|
"valueCode": "semestre"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||||
|
"valueCode": "mes"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"scoring": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||||
|
"code": "proportion"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"group": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||||
|
"code": "principal"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": "Unidades del periodo",
|
||||||
|
"criteria": {
|
||||||
|
"language": "text/x-dbt-metric",
|
||||||
|
"expression": "cama_confirmacion_birads45_denominador"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "denominator"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": "Denominador",
|
||||||
|
"criteria": {
|
||||||
|
"language": "text/x-dbt-metric",
|
||||||
|
"expression": "cama_confirmacion_birads45_denominador"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "numerator"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": "Numerador",
|
||||||
|
"criteria": {
|
||||||
|
"language": "text/x-dbt-metric",
|
||||||
|
"expression": "cama_confirmacion_birads45_numerador"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"subjectCodeableConcept": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||||
|
"code": "episodio"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"improvementNotation": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||||
|
"code": "increase"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"search": {
|
||||||
|
"mode": "match"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-DIAS-TOMA-DIAGNOSTICO",
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "Measure",
|
||||||
|
"id": "CAMA-DIAS-TOMA-DIAGNOSTICO",
|
||||||
|
"url": "https://isssteleon.org/fhir/Measure/CAMA-DIAS-TOMA-DIAGNOSTICO",
|
||||||
|
"version": "0.2.2",
|
||||||
|
"name": "cama_dias_toma_diagnostico",
|
||||||
|
"title": "Tiempo de tamizaje a diagnóstico",
|
||||||
|
"status": "active",
|
||||||
|
"description": "Días naturales de la toma de cada mastografía del semestre a la primera nota médica posterior que la resuelve: un diagnóstico CIE-10 de la lista (normal, benigno, lesión o cáncer), escrito por una de las especialidades que diagnostican, dentro del horizonte y a la fecha de corte. Entran todas las mastografías, sean de tamizaje o no; se excluyen las de pacientes con un diagnóstico de cáncer de mama anterior a la toma.",
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||||
|
"valueCode": "C3r"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||||
|
"valueCode": "semestre"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||||
|
"valueCode": "mes"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"scoring": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||||
|
"code": "continuous-variable"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"group": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||||
|
"code": "TOTAL"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": "Unidades del periodo",
|
||||||
|
"criteria": {
|
||||||
|
"language": "text/x-dbt-metric",
|
||||||
|
"expression": "cama_dias_toma_diagnostico"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "measure-observation"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": "Unidades con valor",
|
||||||
|
"criteria": {
|
||||||
|
"language": "text/x-dbt-metric",
|
||||||
|
"expression": "cama_dias_toma_diagnostico"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "measure-population-exclusion"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": "Unidades sin valor",
|
||||||
|
"criteria": {
|
||||||
|
"language": "text/x-dbt-metric",
|
||||||
|
"expression": "cama_dias_toma_diagnostico"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"subjectCodeableConcept": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||||
|
"code": "examen"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"improvementNotation": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||||
|
"code": "decrease"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"search": {
|
||||||
|
"mode": "match"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-EU38A",
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "Measure",
|
||||||
|
"id": "CAMA-EU38A",
|
||||||
|
"url": "https://isssteleon.org/fhir/Measure/CAMA-EU38A",
|
||||||
|
"version": "0.2.1",
|
||||||
|
"name": "cama_eu38a",
|
||||||
|
"title": "Días de la toma de la mastografía a su resultado",
|
||||||
|
"status": "active",
|
||||||
|
"description": "Días naturales de la toma de cada mastografía del semestre a su resultado, a la fecha de corte. Las que aún no tienen resultado y siguen dentro del horizonte no se miden; las que lo pasaron sin resultado cuentan en los excluidos.",
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||||
|
"valueCode": "C3r"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||||
|
"valueCode": "semestre"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||||
|
"valueCode": "mes"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"scoring": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||||
|
"code": "continuous-variable"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"group": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||||
|
"code": "TOTAL"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"population": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "initial-population"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": "Unidades del periodo",
|
||||||
|
"criteria": {
|
||||||
|
"language": "text/x-dbt-metric",
|
||||||
|
"expression": "cama_eu38a"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "measure-observation"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": "Unidades con valor",
|
||||||
|
"criteria": {
|
||||||
|
"language": "text/x-dbt-metric",
|
||||||
|
"expression": "cama_eu38a"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||||
|
"code": "measure-population-exclusion"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": "Unidades sin valor",
|
||||||
|
"criteria": {
|
||||||
|
"language": "text/x-dbt-metric",
|
||||||
|
"expression": "cama_eu38a"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"subjectCodeableConcept": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||||
|
"code": "examen"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"improvementNotation": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||||
|
"code": "decrease"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"search": {
|
||||||
|
"mode": "match"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
|||||||
|
{"error": "la selección tiene menos de 5 pacientes: su lista no se publica.", "motivo": "supresion"}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"simulado": true, "cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "a2c95b755ba3ccab288c148153e14be1e958aadff1f5a320a4d54e84b3cae745", "corte": "2026-11-17", "ventana": {"meses": 6, "desde": "2026-05-18", "hasta": "2026-11-17"}, "filtros": {"birads": "BIRADS_5", "grupo_edad": null, "biopsia": null}, "filtros_disponibles": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "columnas": [{"clave": "pac_id", "etiqueta": "Identificador de paciente"}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad"}, {"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]}, {"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de reporte"}]}], "paginacion": {"page": 1, "page_size": 50, "total_items": 16, "total_pages": 1}, "items": [{"pac_id": "251", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-11-05", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "185", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "95", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-15", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-11-14"}, {"pac_id": "188", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-04", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-20"}, {"pac_id": "126", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-27", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-04"}, {"pac_id": "52", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "220", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-19", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}, {"pac_id": "254", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-11", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-09-16"}, {"pac_id": "129", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-22", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-08-20"}, {"pac_id": "117", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-21", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-08-09"}, {"pac_id": "101", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-03", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-07-31"}, {"pac_id": "225", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-02", "biopsia": "CARCINOMA_IN_SITU", "biopsia_fecha": "2026-07-31"}, {"pac_id": "287", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-14", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-07-13"}, {"pac_id": "55", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-09", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-06-30"}, {"pac_id": "7", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-02", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "260", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-05-21", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-06-07"}]}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"simulado": true, "cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "a2c95b755ba3ccab288c148153e14be1e958aadff1f5a320a4d54e84b3cae745", "corte": "2026-11-17", "ventana": {"meses": 3, "desde": "2026-08-18", "hasta": "2026-11-17"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "filtros_disponibles": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "columnas": [{"clave": "pac_id", "etiqueta": "Identificador de paciente"}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad"}, {"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]}, {"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de reporte"}]}], "paginacion": {"page": 1, "page_size": 50, "total_items": 16, "total_pages": 1}, "items": [{"pac_id": "251", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-11-05", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "54", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "185", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "255", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-21", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "95", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-15", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-11-14"}, {"pac_id": "4", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-10", "biopsia": "BENIGNO", "biopsia_fecha": "2026-11-06"}, {"pac_id": "256", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-08", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "188", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-04", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-20"}, {"pac_id": "239", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-09-14", "biopsia": "BENIGNO", "biopsia_fecha": "2026-10-06"}, {"pac_id": "245", "grupo_edad": "40-49", "birads": "BIRADS_4", "mastografia_fecha": "2026-09-09", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "186", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-31", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}, {"pac_id": "282", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-29", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-10"}, {"pac_id": "126", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-27", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-04"}, {"pac_id": "31", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "52", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "220", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-19", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}]}
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
@@ -3,7 +3,6 @@ import { TestBed } from '@angular/core/testing';
|
|||||||
import { provideHttpClient } from '@angular/common/http';
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
import { By } from '@angular/platform-browser';
|
import { By } from '@angular/platform-browser';
|
||||||
import { MatSelect } from '@angular/material/select';
|
|
||||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||||
@@ -28,7 +27,6 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
|||||||
fixture.componentRef.setInput('indicador', { id: 'i', titulo: 'I', contrato: 'C2', figuras, tipos_periodo: ['semestre'] });
|
fixture.componentRef.setInput('indicador', { id: 'i', titulo: 'I', contrato: 'C2', figuras, tipos_periodo: ['semestre'] });
|
||||||
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges();
|
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges();
|
||||||
}
|
}
|
||||||
function select() { return fixture.debugElement.query(By.directive(MatSelect)).componentInstance as MatSelect; }
|
|
||||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).filter(e => e.componentInstance.result().status !== 'deferred'); }
|
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).filter(e => e.componentInstance.result().status !== 'deferred'); }
|
||||||
function request(id: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + id)); }
|
function request(id: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + id)); }
|
||||||
function open() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); }
|
function open() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); }
|
||||||
@@ -47,13 +45,9 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
|||||||
expect(fixture.componentInstance.indicador.contrato).toBe(contrato);
|
expect(fixture.componentInstance.indicador.contrato).toBe(contrato);
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para selector, consulta y memoria', () => {
|
it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para consulta y memoria', () => {
|
||||||
fixture.destroy(); create(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c2_barras', 'fig_c2_donas', 'fig_c9_futura']);
|
fixture.destroy(); create(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c2_barras', 'fig_c2_donas', 'fig_c9_futura']);
|
||||||
fixture.componentRef.setInput('indicador', { ...fixture.componentInstance.indicador, contrato: 'C1' }); fixture.detectChanges();
|
fixture.componentRef.setInput('indicador', { ...fixture.componentInstance.indicador, contrato: 'C1' }); fixture.detectChanges();
|
||||||
expect(select().options.map(option => [option.value, option.viewValue])).toEqual([
|
|
||||||
['fig_c1_grupos', 'Grupos'], ['fig_c2_apiladas', 'Barras apiladas'],
|
|
||||||
['fig_c2_barras', 'Barras'], ['fig_c2_donas', 'Donas'], ['fig_c9_futura', 'Representación 5'],
|
|
||||||
]);
|
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
open(); request('fig_c1_grupos').flush({ data: [], layout: {} });
|
open(); request('fig_c1_grupos').flush({ data: [], layout: {} });
|
||||||
for (const [id, label] of [
|
for (const [id, label] of [
|
||||||
@@ -62,7 +56,7 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
|||||||
['fig_c2_donas', 'Donas'],
|
['fig_c2_donas', 'Donas'],
|
||||||
['fig_c9_futura', 'Representación 5'],
|
['fig_c9_futura', 'Representación 5'],
|
||||||
]) {
|
]) {
|
||||||
select().selectionChange.emit({ source: select(), value: id }); fixture.detectChanges();
|
fixture.componentInstance.selectFigure(id); fixture.detectChanges();
|
||||||
const pending = request(id);
|
const pending = request(id);
|
||||||
expect(pending.request.url).toBe('/cacu/indicadores/i/figuras/' + id);
|
expect(pending.request.url).toBe('/cacu/indicadores/i/figuras/' + id);
|
||||||
expect(pending.request.params.get('tema')).toBe('claro');
|
expect(pending.request.params.get('tema')).toBe('claro');
|
||||||
@@ -74,9 +68,9 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
|||||||
}
|
}
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('una opción publicada está deshabilitada y sólo consulta esa figura', () => {
|
it('no ofrece selector de representación y sólo consulta la figura mostrada', () => {
|
||||||
fixture.destroy(); create(['f']); open(); expect(select().disabled).toBe(true);
|
fixture.destroy(); create(['f', 'g']); open(); expect(fixture.nativeElement.querySelector('mat-select')).toBeNull();
|
||||||
expect(select().options.map(o => o.value)).toEqual(['f']); request('f').flush({ data: [], layout: {} }); http.expectNone(() => true);
|
request('f').flush({ data: [], layout: {} }); http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('comparte una sola solicitud de metadatos entre las dos figuras y asocia por ID exacto', () => {
|
it('comparte una sola solicitud de metadatos entre las dos figuras y asocia por ID exacto', () => {
|
||||||
fixture.componentRef.setInput('indicador', { id: 'cacu_eu13', titulo: 'EU13', contrato: 'C2',
|
fixture.componentRef.setInput('indicador', { id: 'cacu_eu13', titulo: 'EU13', contrato: 'C2',
|
||||||
@@ -98,9 +92,8 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
|||||||
expect(cards.every(card => card.interpretation.every(line => line !== 'No debe asignarse.'))).toBe(true);
|
expect(cards.every(card => card.interpretation.every(line => line !== 'No debe asignarse.'))).toBe(true);
|
||||||
});
|
});
|
||||||
it('múltiples opciones habilitan el selector, mantienen una representación y cancelan cambios rápidos', () => {
|
it('múltiples opciones habilitan el selector, mantienen una representación y cancelan cambios rápidos', () => {
|
||||||
open(); const first = request('f'); expect(select().disabled).toBe(false);
|
open(); const first = request('f'); expect(panels()).toHaveLength(1);
|
||||||
expect(select().options.map(o => o.value)).toEqual(['f', 'g']); expect(panels()).toHaveLength(1);
|
fixture.componentInstance.selectFigure('g'); fixture.detectChanges();
|
||||||
select().selectionChange.emit({ source: select(), value: 'g' }); fixture.detectChanges();
|
|
||||||
const next = request('g'); expect(first.cancelled).toBe(true); expect(panels()).toHaveLength(1);
|
const next = request('g'); expect(first.cancelled).toBe(true); expect(panels()).toHaveLength(1);
|
||||||
expect(next.request.params.get('periodos')).toBe('2025-S1');
|
expect(next.request.params.get('periodos')).toBe('2025-S1');
|
||||||
fixture.componentInstance.selectFigure('f'); fixture.detectChanges(); expect(next.cancelled).toBe(true);
|
fixture.componentInstance.selectFigure('f'); fixture.detectChanges(); expect(next.cancelled).toBe(true);
|
||||||
|
|||||||
@@ -2,8 +2,6 @@ import { ChangeDetectorRef, Component, effect, ElementRef, inject, Input, OnChan
|
|||||||
import { catchError, of, Subscription } from 'rxjs';
|
import { catchError, of, Subscription } from 'rxjs';
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
import { MatCardModule } from '@angular/material/card';
|
import { MatCardModule } from '@angular/material/card';
|
||||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
|
||||||
import { MatSelectModule } from '@angular/material/select';
|
|
||||||
import { MatIconModule } from '@angular/material/icon';
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
import { Dominio, Indicador, IndicadorMetadatos, Tema } from './indicadores.models';
|
import { Dominio, Indicador, IndicadorMetadatos, Tema } from './indicadores.models';
|
||||||
import { GlobalApplied, IndicadoresMemory } from './indicadores-memory';
|
import { GlobalApplied, IndicadoresMemory } from './indicadores-memory';
|
||||||
@@ -29,14 +27,16 @@ import { parConteos } from './indicadores-conteos-pareados';
|
|||||||
@Component({
|
@Component({
|
||||||
selector: 'app-indicador-catalog-card',
|
selector: 'app-indicador-catalog-card',
|
||||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos' },
|
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos' },
|
||||||
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, 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"
|
||||||
@@ -44,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">
|
||||||
@@ -64,19 +64,9 @@ 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) {
|
||||||
@if (!sobrio && (!pair.length || otherFigures.length)) {
|
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
|
||||||
<mat-label>Representación gráfica</mat-label>
|
|
||||||
<mat-select [value]="selectedFigure" [disabled]="indicador.figuras.length === 1"
|
|
||||||
[attr.aria-label]="'Representación gráfica de ' + indicador.titulo" (selectionChange)="selectFigure($event.value)">
|
|
||||||
@if (pair.length) { <mat-option [value]="pair[0]">Dona y barras</mat-option> }
|
|
||||||
@for (figure of (pair.length ? otherFigures : indicador.figuras); track figure) { <mat-option [value]="figure">{{ figureDisplayName(figure, indicador.figuras) }}</mat-option> }
|
|
||||||
</mat-select>
|
|
||||||
</mat-form-field>
|
|
||||||
}
|
|
||||||
<div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual">
|
<div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual">
|
||||||
@for (figure of displayFigures; track panelIdentity(figure)) {
|
@for (figure of displayFigures; track panelIdentity(figure)) {
|
||||||
<div class="representation-panel">
|
<div class="representation-panel">
|
||||||
@@ -156,7 +146,6 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
|||||||
get tiempos() { return parTiempos(this.dominio, this.indicador.id); }
|
get tiempos() { return parTiempos(this.dominio, this.indicador.id); }
|
||||||
// Exams and patients of the same finding, drawn together on the exams' card.
|
// Exams and patients of the same finding, drawn together on the exams' card.
|
||||||
get conteos() { return parConteos(this.dominio, this.indicador.id); }
|
get conteos() { return parConteos(this.dominio, this.indicador.id); }
|
||||||
get otherFigures() { return this.indicador.figuras.filter(id => !this.pair.includes(id)); }
|
|
||||||
get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
|
get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
|
||||||
get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; }
|
get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; }
|
||||||
private updateNumeric() {
|
private updateNumeric() {
|
||||||
|
|||||||
@@ -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 o 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!" [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,17 +3,28 @@
|
|||||||
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.
|
||||||
|
.donut-chart { --plot-min-width: 230px; }
|
||||||
summary { cursor: pointer; padding-block: .75rem; }
|
summary { cursor: pointer; padding-block: .75rem; }
|
||||||
summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||||
.table-scroll { overflow: auto; }
|
.table-scroll { overflow: auto; }
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
|
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, signal, SimpleChanges } from '@angular/core';
|
||||||
import { HttpErrorResponse } from '@angular/common/http';
|
import { 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,38 +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;
|
||||||
// On a narrow screen the donut's long label gives way to a legend under it.
|
private anchoDona = 390;
|
||||||
private readonly estrecha = typeof matchMedia === 'function' ? matchMedia('(max-width: 520px)') : undefined;
|
private anchoPacientes = 390;
|
||||||
private readonly alCambiarAncho = () => { if (this.model) this.draw(); };
|
|
||||||
constructor() { this.estrecha?.addEventListener('change', this.alCambiarAncho); }
|
|
||||||
|
|
||||||
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]);
|
||||||
@@ -68,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();
|
||||||
@@ -108,12 +115,24 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
|
|||||||
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
|
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
|
||||||
this.periodIndex += step; this.draw();
|
this.periodIndex += step; this.draw();
|
||||||
}
|
}
|
||||||
|
ajustarAnchoDona(ancho: number) {
|
||||||
|
if (ancho === this.anchoDona) return;
|
||||||
|
this.anchoDona = ancho;
|
||||||
|
const m = this.model;
|
||||||
|
if (m) this.donutFigure = donaConteos(m, this.par, this.tema, ancho);
|
||||||
|
}
|
||||||
|
ajustarAnchoPacientes(ancho: number) {
|
||||||
|
if (ancho === this.anchoPacientes) return;
|
||||||
|
this.anchoPacientes = ancho;
|
||||||
|
const m = this.model;
|
||||||
|
if (m) this.patientsFigure = donaPacientes(m, this.par, this.tema, ancho);
|
||||||
|
}
|
||||||
private draw() {
|
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.estrecha?.matches ?? false);
|
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(); this.estrecha?.removeEventListener('change', this.alCambiarAncho); }
|
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -83,7 +83,23 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
@if (state.status === 'ready' && state.donutLegend?.length) {
|
@if (state.status === 'ready' && state.highlight; as h) {
|
||||||
|
<div class="highlight-legend" role="group" aria-label="Resaltar partes de la figura">
|
||||||
|
<p class="highlight-status" role="status" aria-live="polite">Selección: {{ highlightStatus }}</p>
|
||||||
|
<button type="button" class="highlight-back" (click)="highlightBack()" [disabled]="!highlightSelection.group && !highlightSelection.item">Volver</button>
|
||||||
|
@for (row of highlightRows(h); track row.group?.id ?? '') {
|
||||||
|
<div class="highlight-keys" role="group" [attr.aria-label]="row.group ? row.group.label + ' y sus categorías' : 'Categorías'">
|
||||||
|
@if (row.group; as g) {
|
||||||
|
<button type="button" class="highlight-group" [attr.aria-pressed]="highlightSelection.group === g.id" (click)="highlight('group', g.id)"><span class="legend-swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.label }}</button>
|
||||||
|
}
|
||||||
|
@for (c of row.items; track c.id) {
|
||||||
|
<button type="button" [attr.aria-pressed]="highlightSelection.item === c.id" [disabled]="!!highlightSelection.group && c.group !== highlightSelection.group"
|
||||||
|
[attr.aria-label]="c.short ? c.label : null" (click)="highlight('item', c.id)"><span class="legend-swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.short ?? c.label }}</button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
} @else if (state.status === 'ready' && state.donutLegend?.length) {
|
||||||
<div class="donut-static-legend" role="list" aria-label="Leyenda de la dona">
|
<div class="donut-static-legend" role="list" aria-label="Leyenda de la dona">
|
||||||
@for (entry of state.donutLegend; track entry.label) {
|
@for (entry of state.donutLegend; track entry.label) {
|
||||||
<span class="donut-static-legend__item" role="listitem">
|
<span class="donut-static-legend__item" role="listitem">
|
||||||
@@ -94,7 +110,7 @@
|
|||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
<div class="plot-slot" [hidden]="state.status !== 'ready'">
|
<div class="plot-slot" [hidden]="state.status !== 'ready'">
|
||||||
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ', ' + selected?.id + ', ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
|
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend || state.highlight ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ', ' + selected?.id + ', ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
<div class="figure-footer" [hidden]="state.status !== 'ready'">
|
<div class="figure-footer" [hidden]="state.status !== 'ready'">
|
||||||
|
|||||||
@@ -37,7 +37,7 @@
|
|||||||
:host(.methodology-expanded) .figure-card { grid-row: auto; }
|
:host(.methodology-expanded) .figure-card { grid-row: auto; }
|
||||||
.figure-title { display: block; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); font-family: var(--issste-font-heading); overflow-wrap: anywhere; }
|
.figure-title { display: block; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); font-family: var(--issste-font-heading); overflow-wrap: anywhere; }
|
||||||
.state { padding: 1.25rem; margin: 0; overflow-wrap: anywhere; }
|
.state { padding: 1.25rem; margin: 0; overflow-wrap: anywhere; }
|
||||||
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; }
|
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b7d251; --mat-sys-outline: #a1aabd; }
|
||||||
.figure-id { padding: .25rem 1rem 0; margin: 0; font: var(--mat-sys-body-small); opacity: .8; overflow-wrap: anywhere; }
|
.figure-id { padding: .25rem 1rem 0; margin: 0; font: var(--mat-sys-body-small); opacity: .8; overflow-wrap: anywhere; }
|
||||||
@media (max-width: 550px) { .methodology-detail { padding: var(--issste-space-3); } }
|
@media (max-width: 550px) { .methodology-detail { padding: var(--issste-space-3); } }
|
||||||
|
|
||||||
@@ -113,3 +113,16 @@
|
|||||||
@media (prefers-reduced-motion: reduce) {
|
@media (prefers-reduced-motion: reduce) {
|
||||||
.donut-children-region, .donut-children-region.expanded { transition: none; transform: none; }
|
.donut-children-region, .donut-children-region.expanded { transition: none; transform: none; }
|
||||||
}
|
}
|
||||||
|
// Highlight buttons, as in CaCu's «Distribución de resultados citológicos».
|
||||||
|
.highlight-legend { display: grid; gap: .5rem; padding: .5rem .75rem .75rem; color: var(--issste-text); }
|
||||||
|
.dark .highlight-legend { color: #eef1f7; }
|
||||||
|
.highlight-status { margin: 0; font-weight: 600; }
|
||||||
|
.highlight-back { justify-self: start; }
|
||||||
|
.highlight-keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||||
|
.highlight-legend button { display: inline-flex; align-items: center; gap: .4rem; min-height: 36px; padding: .3rem .75rem; text-align: start;
|
||||||
|
overflow-wrap: anywhere; color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 999px; font: inherit; cursor: pointer; }
|
||||||
|
.highlight-legend button:disabled { opacity: .45; cursor: default; }
|
||||||
|
.highlight-legend button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
|
||||||
|
.highlight-legend button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||||
|
.highlight-legend .legend-swatch { border-radius: 50%; }
|
||||||
|
.highlight-legend .highlight-group { font-weight: 600; }
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ import { figureIdentity, identityElementId } from './indicadores-identities';
|
|||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
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 { 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 {
|
||||||
@@ -22,6 +24,10 @@ export interface FigureState {
|
|||||||
categoryLabels?: readonly CategoryLabel[];
|
categoryLabels?: readonly CategoryLabel[];
|
||||||
minimumPlotWidth?: number;
|
minimumPlotWidth?: number;
|
||||||
donutLegend?: readonly DonutLegendEntry[];
|
donutLegend?: readonly DonutLegendEntry[];
|
||||||
|
// The figure already lays out its own rings (C1 double donut): show the legend, keep the figure as is.
|
||||||
|
ownLayout?: boolean;
|
||||||
|
// Legend buttons that highlight one part of the figure (CaCu style).
|
||||||
|
highlight?: FigureHighlight;
|
||||||
plotWidth?: number;
|
plotWidth?: number;
|
||||||
plotHeight?: number;
|
plotHeight?: number;
|
||||||
message?: string;
|
message?: string;
|
||||||
@@ -57,14 +63,15 @@ 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';
|
||||||
}
|
}
|
||||||
@Input({ required: true }) set state(value: FigureState) {
|
@Input({ required: true }) set state(value: FigureState) {
|
||||||
if (value.status !== 'ready' || value.figure !== this.currentState?.figure
|
if (value.status !== 'ready' || value.figure !== this.currentState?.figure
|
||||||
|| JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; }
|
|| JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; this.highlightSelection = {}; }
|
||||||
this.currentState = value;
|
this.currentState = value;
|
||||||
if (value.status === 'ready') {
|
if (value.status === 'ready') {
|
||||||
this.updateDonut();
|
this.updateDonut();
|
||||||
@@ -87,7 +94,8 @@ export class IndicadorFigureCard implements OnChanges {
|
|||||||
? { ...presentationFigure, layout: { ...presentationFigure.layout, height: this.state.plotHeight } } : presentationFigure;
|
? { ...presentationFigure, layout: { ...presentationFigure.layout, height: this.state.plotHeight } } : presentationFigure;
|
||||||
this.chartFigure = source && hierarchy
|
this.chartFigure = source && hierarchy
|
||||||
? donutView(source, hierarchy, this.activeParent, this.state.plotWidth)
|
? donutView(source, hierarchy, this.activeParent, this.state.plotWidth)
|
||||||
: source && this.state.donutLegend ? donutSimpleView(source) : source;
|
: source && this.state.highlight ? highlightFigure(source, this.state.highlight, this.highlightSelection)
|
||||||
|
: source && this.state.donutLegend && !this.state.ownLayout ? donutSimpleView(source) : source;
|
||||||
}
|
}
|
||||||
expandParent(parent: string) {
|
expandParent(parent: string) {
|
||||||
if (this.state.status !== 'ready' || !this.state.hierarchy?.parents.includes(parent)
|
if (this.state.status !== 'ready' || !this.state.hierarchy?.parents.includes(parent)
|
||||||
@@ -109,9 +117,28 @@ export class IndicadorFigureCard implements OnChanges {
|
|||||||
target?.focus();
|
target?.focus();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
highlightSelection: HighlightSelection = {};
|
||||||
|
readonly highlightRows = highlightRows;
|
||||||
|
get highlightStatus() { return this.state.highlight ? highlightLabel(this.state.highlight, this.highlightSelection) : ''; }
|
||||||
|
highlight(kind: 'group' | 'item', id: string) {
|
||||||
|
if (!this.state.highlight) return;
|
||||||
|
this.highlightSelection = toggleHighlight(this.state.highlight, this.highlightSelection, kind, id);
|
||||||
|
this.updateDonut();
|
||||||
|
}
|
||||||
|
highlightBack() {
|
||||||
|
const sel = this.highlightSelection;
|
||||||
|
this.highlightSelection = sel.item && sel.group ? { group: sel.group } : {};
|
||||||
|
this.updateDonut();
|
||||||
|
}
|
||||||
plotClicked(event: unknown) {
|
plotClicked(event: unknown) {
|
||||||
if (!event || typeof event !== 'object' || !('points' in event) || !Array.isArray(event.points)) return;
|
if (!event || typeof event !== 'object' || !('points' in event) || !Array.isArray(event.points)) return;
|
||||||
const point = event.points[0];
|
const point = event.points[0];
|
||||||
|
if (this.state.highlight) {
|
||||||
|
const hit = typeof point?.curveNumber === 'number' && typeof point.pointNumber === 'number'
|
||||||
|
? highlightAt(this.state.highlight, { trace: point.curveNumber, index: point.pointNumber }) : undefined;
|
||||||
|
if (hit) this.highlight(hit.kind, hit.id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label);
|
if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label);
|
||||||
else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label);
|
else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -215,10 +215,10 @@ describe('IndicadorFigurePanel', () => {
|
|||||||
expect(JSON.stringify(page.result().figure)).toBe(original);
|
expect(JSON.stringify(page.result().figure)).toBe(original);
|
||||||
expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno');
|
expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno');
|
||||||
});
|
});
|
||||||
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita o Todos', () => {
|
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita', () => {
|
||||||
load(); figure().flush({ data: [], layout: {} });
|
load(); figure().flush({ data: [], layout: {} });
|
||||||
const control = filters();
|
const control = filters();
|
||||||
control.changeMode('manual');
|
control.select([]);
|
||||||
expect(control.canApply).toBe(false);
|
expect(control.canApply).toBe(false);
|
||||||
apply();
|
apply();
|
||||||
http.expectNone(req => req.url.includes('/figuras/'));
|
http.expectNone(req => req.url.includes('/figuras/'));
|
||||||
@@ -228,18 +228,13 @@ describe('IndicadorFigurePanel', () => {
|
|||||||
expect(state?.applied?.selection.mode).toBe('todos');
|
expect(state?.applied?.selection.mode).toBe('todos');
|
||||||
apply();
|
apply();
|
||||||
const manual = figure();
|
const manual = figure();
|
||||||
expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
expect(manual.request.params.get('periodos')).toBe('2025-S2');
|
||||||
control.select([]);
|
control.select([]);
|
||||||
expect(manual.cancelled).toBe(false);
|
expect(manual.cancelled).toBe(false);
|
||||||
expect(control.canApply).toBe(false);
|
expect(control.canApply).toBe(false);
|
||||||
apply();
|
apply();
|
||||||
http.expectNone(req => req.url.includes('/figuras/'));
|
http.expectNone(req => req.url.includes('/figuras/'));
|
||||||
control.changeMode('todos');
|
manual.flush({ data: [], layout: {} });
|
||||||
apply();
|
|
||||||
expect(manual.cancelled).toBe(true);
|
|
||||||
const all = figure();
|
|
||||||
expect(all.request.params.has('periodos')).toBe(false);
|
|
||||||
all.flush({ data: [], layout: {} });
|
|
||||||
});
|
});
|
||||||
it('UX-07B cambia perfil y restaura desde el original sin HTTP ni pérdida de host o revisión', () => {
|
it('UX-07B cambia perfil y restaura desde el original sin HTTP ni pérdida de host o revisión', () => {
|
||||||
load(); const received = { data: [{ y: [0, null], marker: { color: 'gray' } }], layout: { paper_bgcolor: 'white' }, future: 42 };
|
load(); const received = { data: [{ y: [0, null], marker: { color: 'gray' } }], layout: { paper_bgcolor: 'white' }, future: 42 };
|
||||||
@@ -300,7 +295,7 @@ describe('IndicadorFigurePanel', () => {
|
|||||||
});
|
});
|
||||||
it('mantiene resultado y referencia aplicada mientras se edita un borrador', () => {
|
it('mantiene resultado y referencia aplicada mientras se edita un borrador', () => {
|
||||||
load(); figure().flush({ data: [{ y: [0, null] }], layout: {} });
|
load(); figure().flush({ data: [{ y: [0, null] }], layout: {} });
|
||||||
const control = filters(); control.changeMode('manual');
|
const control = filters(); control.select([]);
|
||||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
expect(page.result().figure?.data[0]['y']).toEqual([0, null]);
|
expect(page.result().figure?.data[0]['y']).toEqual([0, null]);
|
||||||
@@ -308,9 +303,9 @@ describe('IndicadorFigurePanel', () => {
|
|||||||
expect(fixture.nativeElement.textContent).toContain('Filtro general aplicado: Todos con reporte');
|
expect(fixture.nativeElement.textContent).toContain('Filtro general aplicado: Todos con reporte');
|
||||||
http.expectNone(r => r.url.includes('/figuras/'));
|
http.expectNone(r => r.url.includes('/figuras/'));
|
||||||
});
|
});
|
||||||
it.each([{ periodos: ['2025-S1'] }, { periodos: ['2025-S1', '2025-S2'] }])('404 de conjunto conserva borrador y reintenta la última aplicación', ({ periodos }) => {
|
it.each([{ periodos: ['2025-S1'] }])('404 de un periodo conserva borrador y reintenta la última aplicación', ({ periodos }) => {
|
||||||
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
||||||
const control = filters(); control.changeMode('manual'); control.year = '2025';
|
const control = filters(); control.select([]); control.year = '2025';
|
||||||
for (const period of periodos) { control.unit = period.slice(-2); control.add(); }
|
for (const period of periodos) { control.unit = period.slice(-2); control.add(); }
|
||||||
apply();
|
apply();
|
||||||
const req = figure();
|
const req = figure();
|
||||||
@@ -320,7 +315,6 @@ describe('IndicadorFigurePanel', () => {
|
|||||||
expect(page.result().figure).toBeUndefined();
|
expect(page.result().figure).toBeUndefined();
|
||||||
expect(page.result().message).toContain('esta selección');
|
expect(page.result().message).toContain('esta selección');
|
||||||
expect(page.result().message).not.toContain('2025');
|
expect(page.result().message).not.toContain('2025');
|
||||||
if (periodos.length > 1) expect(page.result().message).toContain('conjunto de periodos');
|
|
||||||
expect(control.selectedPeriods).toEqual(periodos);
|
expect(control.selectedPeriods).toEqual(periodos);
|
||||||
control.select([]);
|
control.select([]);
|
||||||
page.requestFigure();
|
page.requestFigure();
|
||||||
@@ -333,7 +327,7 @@ describe('IndicadorFigurePanel', () => {
|
|||||||
});
|
});
|
||||||
it('reintento y tema utilizan la selección aplicada aunque el borrador sea diferente', () => {
|
it('reintento y tema utilizan la selección aplicada aunque el borrador sea diferente', () => {
|
||||||
load(); figure().flush({ data: [], layout: {} });
|
load(); figure().flush({ data: [], layout: {} });
|
||||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||||
apply(); figure().flush({ data: [{ y: [20] }], layout: {} });
|
apply(); figure().flush({ data: [{ y: [20] }], layout: {} });
|
||||||
control.unit = 'S2'; control.add();
|
control.unit = 'S2'; control.add();
|
||||||
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
|
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
|
||||||
@@ -344,17 +338,17 @@ describe('IndicadorFigurePanel', () => {
|
|||||||
page.requestFigure();
|
page.requestFigure();
|
||||||
const retry = figure(); expect(retry.request.params.get('periodos')).toBe('2025-S1');
|
const retry = figure(); expect(retry.request.params.get('periodos')).toBe('2025-S1');
|
||||||
retry.flush({ data: [], layout: {} });
|
retry.flush({ data: [], layout: {} });
|
||||||
expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
|
expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||||
});
|
});
|
||||||
it('descarta respuestas obsoletas de aplicaciones sucesivas', () => {
|
it('descarta respuestas obsoletas de aplicaciones sucesivas', () => {
|
||||||
load(); figure().flush({ data: [], layout: {} });
|
load(); figure().flush({ data: [], layout: {} });
|
||||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||||
apply(); const old = figure();
|
apply(); const old = figure();
|
||||||
control.unit = 'S2'; control.add();
|
control.unit = 'S2'; control.add();
|
||||||
expect(old.cancelled).toBe(false);
|
expect(old.cancelled).toBe(false);
|
||||||
apply(); const current = figure();
|
apply(); const current = figure();
|
||||||
expect(old.cancelled).toBe(true);
|
expect(old.cancelled).toBe(true);
|
||||||
expect(current.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
expect(current.request.params.get('periodos')).toBe('2025-S2');
|
||||||
current.flush({ data: [{ y: [12] }], layout: {} });
|
current.flush({ data: [{ y: [12] }], layout: {} });
|
||||||
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
|
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
|
||||||
expect(page.result().figure?.data[0]['y']).toEqual([12]);
|
expect(page.result().figure?.data[0]['y']).toEqual([12]);
|
||||||
@@ -362,7 +356,7 @@ describe('IndicadorFigurePanel', () => {
|
|||||||
|
|
||||||
it('UX-06E.B1 alterna ayuda sin HTTP y conserva filtros, borrador, memoria y panel', () => {
|
it('UX-06E.B1 alterna ayuda sin HTTP y conserva filtros, borrador, memoria y panel', () => {
|
||||||
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
||||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
const result = page.result(), filterState = state, snapshot = JSON.stringify(filterState);
|
const result = page.result(), filterState = state, snapshot = JSON.stringify(filterState);
|
||||||
const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance;
|
const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance;
|
||||||
|
|||||||
@@ -13,6 +13,9 @@ import { figureIdentity, identityElementId } from './indicadores-identities';
|
|||||||
import { DonutHierarchy, DonutSelection, donutHierarchy, donutLegend, donutPeriod } from './indicadores-donut-drilldown';
|
import { DonutHierarchy, DonutSelection, donutHierarchy, donutLegend, donutPeriod } from './indicadores-donut-drilldown';
|
||||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||||
import { c2Capability, c2Figure } from './indicadores-c2-adapter';
|
import { c2Capability, c2Figure } from './indicadores-c2-adapter';
|
||||||
|
import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2';
|
||||||
|
import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut';
|
||||||
|
import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones';
|
||||||
import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
|
import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
|
||||||
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
|
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
|
||||||
import { c2GeneralSelection } from './indicadores-c2-general-selection';
|
import { c2GeneralSelection } from './indicadores-c2-general-selection';
|
||||||
@@ -245,6 +248,26 @@ export class IndicadorFigurePanel implements OnChanges {
|
|||||||
const state = this.presentStratified(data); this.stratifiedData = data; return state;
|
const state = this.presentStratified(data); this.stratifiedData = data; return state;
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
if (c1DonutCapability(this.indicador.contrato, selection.figura)) {
|
||||||
|
if (selection.tipoPeriodo !== 'semestre' || selection.periodos?.length !== 1)
|
||||||
|
return of({ status: 'incompatible', message: 'Esta figura muestra un solo semestre. Elige el intervalo semestral y un periodo.' } as FigureState);
|
||||||
|
return this.snapshots.datos(selection.dominio!, selection.indicador, 'semestre', selection.periodos, this.indicador.version, { estrato: C1_DONUT_ESTRATO }).pipe(map(data => {
|
||||||
|
const adapted = c1DonutFigure(data, selection);
|
||||||
|
if (adapted.status !== 'supported') return { status: 'incompatible', message: adapted.reason } as FigureState;
|
||||||
|
return { ...this.present(adapted.figure, selection), source: 'datos' as const, footnotes: adapted.notes,
|
||||||
|
highlight: adapted.highlight, ownLayout: true, plotHeight: selection.figura === C1_AGE_BARS ? 400 : undefined,
|
||||||
|
emptyMessage: adapted.total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined };
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
if (c1AlterationCapability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) {
|
||||||
|
return this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo, selection.periodos, this.indicador.version).pipe(map(data => {
|
||||||
|
const adapted = c1AlterationFigure(data, selection);
|
||||||
|
if (adapted.status !== 'supported') return { status: 'incompatible', message: adapted.reason } as FigureState;
|
||||||
|
return { ...this.present(adapted.figure, selection), source: 'datos' as const, footnotes: adapted.notes,
|
||||||
|
highlight: adapted.highlight, ownLayout: true, plotHeight: 400,
|
||||||
|
emptyMessage: adapted.total === 0 ? 'Ningún niño tiene su primer EEG de buena calidad en la selección; no hay un porcentaje que representar.' : undefined };
|
||||||
|
}));
|
||||||
|
}
|
||||||
if (c2Capability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) {
|
if (c2Capability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) {
|
||||||
// Both panels, KPI and numeric table share the exact same transport key.
|
// Both panels, KPI and numeric table share the exact same transport key.
|
||||||
// Do not catch /datos errors here: a backend failure is a real error state.
|
// Do not catch /datos errors here: a backend failure is a real error state.
|
||||||
@@ -265,6 +288,13 @@ export class IndicadorFigurePanel implements OnChanges {
|
|||||||
return this.publishedFigure(selection, 'Partición multiperiodo no verificable', data);
|
return this.publishedFigure(selection, 'Partición multiperiodo no verificable', data);
|
||||||
}
|
}
|
||||||
const adapted = c2Figure(data, selection);
|
const adapted = c2Figure(data, selection);
|
||||||
|
if (adapted.status === 'supported' && selection.dominio === 'tea') {
|
||||||
|
const base = { source: 'datos' as const, footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage };
|
||||||
|
if (selection.figura === 'fig_c2_donas') {
|
||||||
|
const tea = teaC2Donut(adapted.model, selection.tema, adapted.figure.layout['title']);
|
||||||
|
if (tea) return of({ ...this.present(tea.figure, selection), ...base, highlight: tea.highlight, ownLayout: true });
|
||||||
|
} else return of({ ...this.present(adapted.figure, selection), ...base, highlight: c2BarsHighlight(adapted.model) });
|
||||||
|
}
|
||||||
return adapted.status === 'supported'
|
return adapted.status === 'supported'
|
||||||
? of({ ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const,
|
? of({ ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const,
|
||||||
footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage })
|
footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage })
|
||||||
|
|||||||
@@ -1,20 +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 punto es el porcentaje de pacientes de esa categoría BI-RADS cuyo resultado de biopsia pertenece a la selección, entre las que tienen resultado; la línea es su intervalo de confianza de 95 %. «Sin biopsia reportada» y «Sin dato» no entran en el denominador y se muestran aparte, en la tabla de valores publicados.</p>
|
||||||
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
|
@if (metadata) {
|
||||||
</section>
|
@for (guide of readingGuide; track guide.figura) {
|
||||||
|
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
|
||||||
|
<h3>{{ guide.nombre }}</h3>
|
||||||
|
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
|
||||||
|
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
|
||||||
|
</section>
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
</div>
|
||||||
</div>
|
}
|
||||||
}
|
</div>
|
||||||
|
</div>
|
||||||
@switch (status()) {
|
@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 ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando la histopatología por BI-RADS" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
|
||||||
@@ -30,19 +37,25 @@
|
|||||||
</nav>
|
</nav>
|
||||||
}
|
}
|
||||||
@if (model; as m) {
|
@if (model; as m) {
|
||||||
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}. {{ reading }}</p>
|
|
||||||
@if (status() === 'empty') { <p role="status">No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.</p> }
|
@if (status() === 'empty') { <p role="status">No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.</p> }
|
||||||
@else {
|
@else {
|
||||||
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
|
<div class="legend">
|
||||||
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista general de la histopatología">Volver</button>
|
<div class="tab-bar">
|
||||||
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
<div class="tabs" role="tablist" aria-label="Seleccionar resultado de biopsia">
|
||||||
@for (g of m.grupos; track g.id; let i = $index) {
|
@for (g of m.grupos; track g.id; let gi = $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>
|
<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>
|
||||||
<div class="keys" role="group" aria-label="Categorías del anillo exterior">
|
<div class="child-groups">
|
||||||
@for (c of m.categorias; track c.id; let i = $index) {
|
@for (g of m.grupos; track g.id) {
|
||||||
<button type="button" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
<div class="tab-panel" role="group" [id]="'histo-panel-' + g.id" [attr.aria-labelledby]="'histo-tab-' + g.id">
|
||||||
|
@for (c of m.categorias; track c.id; let ci = $index) {
|
||||||
|
@if (c.grupo === g.id) {
|
||||||
|
<button type="button" class="child" [style.--swatch]="c.color" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', ci)"><span class="swatch" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</div>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -51,13 +64,10 @@
|
|||||||
@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>
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ 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, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||||
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
import { filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||||
import { httpMessage } from './indicadores-http';
|
import { httpMessage } from './indicadores-http';
|
||||||
import { Celda } from './indicadores-confirmacion-citologia';
|
import { Celda } from './indicadores-confirmacion-citologia';
|
||||||
@@ -43,6 +43,7 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
|||||||
donutFigure?: PlotlyFigure;
|
donutFigure?: PlotlyFigure;
|
||||||
ratesFigure?: PlotlyFigure;
|
ratesFigure?: PlotlyFigure;
|
||||||
helpOpen = false;
|
helpOpen = false;
|
||||||
|
private helpPinned = false;
|
||||||
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;
|
||||||
@@ -54,7 +55,11 @@ 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 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 isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; }
|
||||||
@@ -71,7 +76,23 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
|||||||
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
|
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
|
toggleHelp() {
|
||||||
|
if (this.helpPinned) { this.helpPinned = false; this.helpOpen = false; return; }
|
||||||
|
this.helpPinned = true;
|
||||||
|
this.showHelp();
|
||||||
|
}
|
||||||
|
showHelp() {
|
||||||
|
if (this.helpOpen) return;
|
||||||
|
this.helpOpen = true;
|
||||||
|
this.metadataRequested.emit();
|
||||||
|
}
|
||||||
|
hideHelp() { if (!this.helpPinned) this.helpOpen = false; }
|
||||||
|
onHelpFocusOut(event: FocusEvent) {
|
||||||
|
const next = event.relatedTarget;
|
||||||
|
if (next instanceof Node && (event.currentTarget as Node).contains(next)) return;
|
||||||
|
this.helpPinned = false;
|
||||||
|
this.helpOpen = false;
|
||||||
|
}
|
||||||
|
|
||||||
ngOnChanges(changes: SimpleChanges) {
|
ngOnChanges(changes: SimpleChanges) {
|
||||||
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_BIRADS })
|
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_BIRADS })
|
||||||
|
|||||||
@@ -27,6 +27,10 @@ import { IndicadorKpiCard } from './indicador-kpi-card';
|
|||||||
expect(fixture.nativeElement.querySelector('.value').textContent).toContain('Valor de prueba');
|
expect(fixture.nativeElement.querySelector('.value').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 (showPeriod && 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; }
|
||||||
@@ -33,6 +40,7 @@ import { MatCardModule } from '@angular/material/card';
|
|||||||
// CaMa's cards are as tall as their grid row.
|
// CaMa's cards are as tall as their grid row.
|
||||||
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
|
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
|
||||||
:host-context(.kpi-section[data-domain='cama']) mat-card { flex: 1 1 auto; height: auto; }
|
:host-context(.kpi-section[data-domain='cama']) mat-card { flex: 1 1 auto; height: auto; }
|
||||||
|
:host-context(.kpi-section[data-domain='cama']) .value { font-size: 1.65rem; }
|
||||||
`,
|
`,
|
||||||
})
|
})
|
||||||
export class IndicadorKpiCard {
|
export class IndicadorKpiCard {
|
||||||
@@ -40,12 +48,18 @@ export class IndicadorKpiCard {
|
|||||||
@Input() value?: string | number | null;
|
@Input() value?: string | number | null;
|
||||||
@Input() unit?: string;
|
@Input() unit?: string;
|
||||||
@Input() temporalReference?: string;
|
@Input() temporalReference?: string;
|
||||||
|
// CaMa's opportunity strip shares one period, shown by the parent instead of on every card.
|
||||||
|
@Input() showPeriod = true;
|
||||||
@Input() loading = false;
|
@Input() loading = false;
|
||||||
@Input() notes: string[] = [];
|
@Input() notes: string[] = [];
|
||||||
@Input() state = 'Pendiente de definición';
|
@Input() state = 'Pendiente de definición';
|
||||||
// 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(' ');
|
||||||
|
|||||||
@@ -27,9 +27,14 @@ describe('KPI integración con autoridad global', () => {
|
|||||||
if (!initial) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
|
if (!initial) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
|
||||||
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
|
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
|
||||||
http.expectOne('/' + domain + '/indicadores').flush(KPI_BY_DOMAIN[domain].slice(missing ? 1 : 0).map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] })));
|
http.expectOne('/' + domain + '/indicadores').flush(KPI_BY_DOMAIN[domain].slice(missing ? 1 : 0).map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] })));
|
||||||
for (const request of http.match(r => r.url.endsWith('/periodos'))) request.flush({ id: request.request.url.split('/').at(-2), periodos: periods.map(periodo => ({ tipo: 'semestre', periodo })) });
|
flushPeriodos(() => periods.map(periodo => ({ tipo: 'semestre', periodo })));
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
}
|
}
|
||||||
|
// Availability runs four requests at a time; flushing one batch starts the next.
|
||||||
|
function flushPeriodos(periodos: () => unknown[]) {
|
||||||
|
for (let pending = http.match(r => r.url.endsWith('/periodos')); pending.length; pending = http.match(r => r.url.endsWith('/periodos')))
|
||||||
|
pending.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: periodos() }));
|
||||||
|
}
|
||||||
// Regression assertions below target the original KPI contracts. The added lab
|
// Regression assertions below target the original KPI contracts. The added lab
|
||||||
// consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts.
|
// consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts.
|
||||||
// Satisfy its independent request with an explicit empty response, never diagnosis data.
|
// Satisfy its independent request with an explicit empty response, never diagnosis data.
|
||||||
@@ -56,7 +61,7 @@ describe('KPI integración con autoridad global', () => {
|
|||||||
expect(panels().map(p => p.definition.id)).toEqual([]);
|
expect(panels().map(p => p.definition.id)).toEqual([]);
|
||||||
expect(panels().every(p => p.result().state === 'Esperando filtro aplicado')).toBe(true); http.expectNone(r => r.url.endsWith('/datos'));
|
expect(panels().every(p => p.result().state === 'Esperando filtro aplicado')).toBe(true); http.expectNone(r => r.url.endsWith('/datos'));
|
||||||
});
|
});
|
||||||
it('TEA consulta sus tres destacados y muestra conteo, porcentaje y mediana', () => {
|
it('TEA consulta sus cinco destacados y muestra conteo, porcentajes y mediana', () => {
|
||||||
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); http.expectOne('/cacu/indicadores').flush([]);
|
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); http.expectOne('/cacu/indicadores').flush([]);
|
||||||
load('tea'); const initial = requests();
|
load('tea'); const initial = requests();
|
||||||
expect(initial.map(r => r.request.url)).toEqual(['/tea/indicadores/' + KPI_BY_DOMAIN.tea[0].id + '/datos']);
|
expect(initial.map(r => r.request.url)).toEqual(['/tea/indicadores/' + KPI_BY_DOMAIN.tea[0].id + '/datos']);
|
||||||
@@ -64,8 +69,10 @@ describe('KPI integración con autoridad global', () => {
|
|||||||
const req = requests();
|
const req = requests();
|
||||||
expect(req.map(r => r.request.url)).toEqual(KPI_BY_DOMAIN.tea.slice(1).map(d => '/tea/indicadores/' + d.id + '/datos'));
|
expect(req.map(r => r.request.url)).toEqual(KPI_BY_DOMAIN.tea.slice(1).map(d => '/tea/indicadores/' + d.id + '/datos'));
|
||||||
req.forEach((r, i) => r.flush(response(i + 1, 'tea'))); fixture.detectChanges();
|
req.forEach((r, i) => r.flush(response(i + 1, 'tea'))); fixture.detectChanges();
|
||||||
expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7]]);
|
expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7], ['Disponible', '40.0'], ['Disponible', '40.0']]);
|
||||||
expect(panels()[1].result().info).toContain('2 de 5 pacientes con nota médica con diagnóstico CIE-10 F84.0.');
|
expect(panels()[1].result().info).toContain('2 de 5 pacientes con nota médica con diagnóstico CIE-10 F84.0.');
|
||||||
|
expect(panels()[3].result().info).toBe('2 de 5 pacientes con diagnóstico confirmado tienen un EEG de buena calidad.');
|
||||||
|
expect(panels()[4].result().info).toBe('2 de 5 pacientes con diagnóstico confirmado no tienen todavía un EEG de buena calidad.');
|
||||||
});
|
});
|
||||||
it('dos KPI reales y un placeholder manejan 404, error y éxito sin cifras anteriores', () => {
|
it('dos KPI reales y un placeholder manejan 404, error y éxito sin cifras anteriores', () => {
|
||||||
load('cacu'); const req = requests(); expect(req).toHaveLength(2); expect(panels().every(p => p.result().loading)).toBe(true);
|
load('cacu'); const req = requests(); expect(req).toHaveLength(2); expect(panels().every(p => p.result().loading)).toBe(true);
|
||||||
@@ -80,7 +87,7 @@ describe('KPI integración con autoridad global', () => {
|
|||||||
it('borrador no consulta; aplicar equivalente tampoco; revisión distinta cancela las tres anteriores', () => {
|
it('borrador no consulta; aplicar equivalente tampoco; revisión distinta cancela las tres anteriores', () => {
|
||||||
load('cacu'); const initial = requests(); initial.forEach((r,i) => r.flush(response(i)));
|
load('cacu'); const initial = requests(); initial.forEach((r,i) => r.flush(response(i)));
|
||||||
const editor = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
const editor = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||||
editor.changeMode('manual'); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
|
editor.select([]); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
|
||||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(0);
|
fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(0);
|
||||||
expect(panels().map(p => p.result().value)).toEqual([5, 7]);
|
expect(panels().map(p => p.result().value)).toEqual([5, 7]);
|
||||||
expect(single.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
expect(single.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
||||||
@@ -164,7 +171,7 @@ describe('KPI integración con autoridad global', () => {
|
|||||||
TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cacu');
|
TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cacu');
|
||||||
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges();
|
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges();
|
||||||
http.expectOne('/cacu/indicadores').flush(KPI_BY_DOMAIN.cacu.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre'] })));
|
http.expectOne('/cacu/indicadores').flush(KPI_BY_DOMAIN.cacu.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre'] })));
|
||||||
http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [] })); fixture.detectChanges();
|
flushPeriodos(() => []); fixture.detectChanges();
|
||||||
expect(panels()).toHaveLength(2); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true);
|
expect(panels()).toHaveLength(2); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true);
|
||||||
http.expectNone(r => r.url.endsWith('/datos'));
|
http.expectNone(r => r.url.endsWith('/datos'));
|
||||||
});
|
});
|
||||||
@@ -176,14 +183,21 @@ describe('KPI integración con autoridad global', () => {
|
|||||||
req.forEach(r => r.flush({ ...response(KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')), domain), notas: ['Nota del pie de la figura.'] }));
|
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(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.'),
|
||||||
]));
|
]));
|
||||||
|
if (domain === 'cama') {
|
||||||
|
expect(fixture.nativeElement.querySelector('.kpi-period')?.textContent).toBe('Periodo 2025-S1');
|
||||||
|
expect(cards.every(card => !card.textContent?.includes('2025-S1'))).toBe(true);
|
||||||
|
} else {
|
||||||
|
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([expect.stringContaining('2025-S1')]));
|
||||||
|
}
|
||||||
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
|
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
|
||||||
// CaCu and CaMa cards say only their own line, as in the reference; the kit notes are the figure footer and the definitions.
|
// CaCu and CaMa cards say only their own line, as in the reference; the kit notes are the figure footer and the definitions.
|
||||||
expect(fixture.nativeElement.textContent.includes('Nota del pie de la figura.')).toBe(false);
|
expect(fixture.nativeElement.textContent.includes('Nota del pie de la figura.')).toBe(false);
|
||||||
|
|||||||
@@ -19,7 +19,8 @@ interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; ver
|
|||||||
imports: [IndicadorKpiCard, MatButtonModule],
|
imports: [IndicadorKpiCard, MatButtonModule],
|
||||||
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
|
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
|
||||||
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
|
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
|
||||||
[loading]="result().loading ?? false" [notes]="dominio === 'tea' ? result().notes ?? [] : []" [quietWhenAvailable]="dominio === 'cama'" />
|
[loading]="result().loading ?? false" [notes]="dominio === 'tea' ? result().notes ?? [] : []" [quietWhenAvailable]="dominio === 'cama'"
|
||||||
|
[showPeriod]="dominio !== 'cama'" />
|
||||||
@if (result().state === 'Error de consulta') {
|
@if (result().state === 'Error de consulta') {
|
||||||
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
|
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
|
||||||
}`,
|
}`,
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import { Component, inject, Input, OnChanges, signal } from '@angular/core';
|
||||||
|
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||||
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
|
import { Dominio, PlotlyFigure } from './indicadores.models';
|
||||||
|
import { proportionFigure } from './measure-report';
|
||||||
|
import { MeasureReportService } from './measure-report.service';
|
||||||
|
|
||||||
|
/** A proportion drawn from the WebApi's FHIR `MeasureReport`s: the data comes as the standard, the figure is ours. */
|
||||||
|
@Component({
|
||||||
|
selector: 'app-indicador-measure-report',
|
||||||
|
imports: [MatProgressBarModule, PlotlyChart],
|
||||||
|
template: `
|
||||||
|
@if (status() === 'loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando indicador" /> }
|
||||||
|
@if (status() === 'error') { <p role="alert">No se pudo cargar el indicador.</p> }
|
||||||
|
@if (figure(); as figure) { <app-plotly-chart [figure]="figure" [label]="titulo" /> }
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class IndicadorMeasureReport implements OnChanges {
|
||||||
|
@Input({ required: true }) dominio!: Dominio;
|
||||||
|
@Input({ required: true }) indicador!: string;
|
||||||
|
@Input({ required: true }) titulo!: string;
|
||||||
|
@Input({ required: true }) periodos!: string[];
|
||||||
|
@Input() estrato?: string;
|
||||||
|
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
|
||||||
|
readonly figure = signal<PlotlyFigure | undefined>(undefined);
|
||||||
|
private readonly service = inject(MeasureReportService);
|
||||||
|
|
||||||
|
ngOnChanges() {
|
||||||
|
this.status.set('loading');
|
||||||
|
this.service.series(this.dominio, this.indicador, this.periodos).subscribe({
|
||||||
|
next: series => { this.figure.set(proportionFigure(series, this.titulo, this.estrato)); this.status.set('ready'); },
|
||||||
|
error: () => { this.figure.set(undefined); this.status.set('error'); },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
@@ -49,47 +51,35 @@
|
|||||||
</section>
|
</section>
|
||||||
} @else {
|
} @else {
|
||||||
<section aria-label="Editor de filtros generales del proyecto">
|
<section aria-label="Editor de filtros generales del proyecto">
|
||||||
@if (state.tipo === 'mes') { <p class="filter-help">Para consultar meses debes elegir periodos explícitos. Todos con reporte utiliza semestres.</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> }
|
||||||
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de tiempo del borrador ya no está publicado para este proyecto. Elige un intervalo de tiempo disponible.</p> }
|
|
||||||
<div class="fields">
|
<div class="fields">
|
||||||
@if (types.length > 1 || !types.includes(state.tipo)) {
|
<div class="interval">
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de tiempo</mat-label>
|
<span class="field-label" id="filtro-intervalo">Intervalo de análisis</span>
|
||||||
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
<mat-button-toggle-group aria-labelledby="filtro-intervalo" hideSingleSelectionIndicator [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
||||||
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mes' : 'Semestre' }}</mat-option> }
|
@if (types.includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
|
||||||
</mat-select>
|
@if (types.includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
|
||||||
</mat-form-field>
|
</mat-button-toggle-group>
|
||||||
}
|
</div>
|
||||||
@if (state.tipo === 'semestre' && state.tipo === types[0]) {
|
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Modalidad</mat-label>
|
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
|
||||||
<mat-select [ngModel]="entry.draft.mode === 'todos' ? 'todos' : 'manual'" (ngModelChange)="changeMode($event)">
|
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
|
||||||
<mat-select-trigger><span class="select-value">{{ entry.draft.mode === 'todos' ? 'Todos con reporte' : 'Elegir periodos' }}</span></mat-select-trigger>
|
@for (period of options; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
|
||||||
<mat-option value="todos">Todos con reporte</mat-option>
|
@if (availability) {
|
||||||
<mat-option value="manual">Elegir periodos</mat-option>
|
@for (period of unavailableSelection; track period) { <mat-option [value]="period" disabled>{{ period }}, disponibilidad no confirmada</mat-option> }
|
||||||
</mat-select>
|
}
|
||||||
</mat-form-field>
|
</mat-select>
|
||||||
}
|
<mat-hint>{{ availability ? 'Existe reporte en al menos un indicador del dominio; la cobertura puede variar.' : 'Disponibilidad desconocida hasta consultar.' }}</mat-hint>
|
||||||
@if (entry.draft.mode !== 'todos') {
|
</mat-form-field>
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodos seleccionados</mat-label>
|
|
||||||
<mat-select multiple [ngModel]="selectedPeriods" (ngModelChange)="select($event)">
|
|
||||||
<mat-select-trigger><span class="select-value">{{ selectedPeriods.join(', ') }}</span></mat-select-trigger>
|
|
||||||
@for (period of options; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
|
|
||||||
@if (availability) {
|
|
||||||
@for (period of unavailableSelection; track period) { <mat-option [value]="period" disabled>{{ period }}, disponibilidad no confirmada</mat-option> }
|
|
||||||
}
|
|
||||||
</mat-select>
|
|
||||||
<mat-hint>{{ availability ? 'Existe reporte en al menos un indicador del dominio; la cobertura puede variar.' : 'Disponibilidad desconocida hasta consultar.' }}</mat-hint>
|
|
||||||
</mat-form-field>
|
|
||||||
}
|
|
||||||
</div>
|
</div>
|
||||||
@if (availability) {
|
@if (availability) {
|
||||||
@if (availability.status === 'loading') { <p role="status">Consultando periodos disponibles…</p> }
|
@if (availability.status === 'loading') { <p role="status">Consultando periodos disponibles…</p> }
|
||||||
@else if (availability.status === 'error') {
|
@else if (availability.status === 'error') {
|
||||||
<p role="alert">No se pudo completar la consulta de periodos disponibles.</p>
|
<p role="alert">No se pudo completar la consulta de periodos disponibles.</p>
|
||||||
<button type="button" mat-stroked-button (click)="retryAvailability.emit()">Reintentar disponibilidad</button>
|
<button type="button" mat-stroked-button (click)="retryAvailability.emit()">Reintentar disponibilidad</button>
|
||||||
} @else if (!options.length) { <p role="status">Sin reportes disponibles para este intervalo de tiempo.</p> }
|
} @else if (!options.length) { <p role="status">Sin reportes disponibles para este intervalo de análisis.</p> }
|
||||||
@if (entry.draft.mode === 'explicit' && unavailableSelection.length) { <p role="status">La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.</p> }
|
@if (entry.draft.mode === 'explicit' && unavailableSelection.length) { <p role="status">La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.</p> }
|
||||||
}
|
}
|
||||||
@if (!availability && entry.draft.mode !== 'todos') {
|
@if (!availability) {
|
||||||
<p class="filter-help">Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.</p>
|
<p class="filter-help">Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.</p>
|
||||||
<div class="fields period-builder">
|
<div class="fields period-builder">
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Año</mat-label><input matInput [(ngModel)]="year" inputmode="numeric" maxlength="4" /></mat-form-field>
|
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Año</mat-label><input matInput [(ngModel)]="year" inputmode="numeric" maxlength="4" /></mat-form-field>
|
||||||
@@ -108,7 +98,7 @@
|
|||||||
}
|
}
|
||||||
@if (error) { <p class="error" role="alert">{{ error }}</p> }
|
@if (error) { <p class="error" role="alert">{{ error }}</p> }
|
||||||
<p class="draft-summary">Selección en edición: {{ summary }}</p>
|
<p class="draft-summary">Selección en edición: {{ summary }}</p>
|
||||||
@if (!canApply) { <p role="status">Selecciona al menos un periodo válido para aplicar.</p> }
|
@if (!canApply) { <p role="status">Selecciona un periodo válido para aplicar.</p> }
|
||||||
@if (!hasPending) { <p class="pending">Sin cambios pendientes.</p> }
|
@if (!hasPending) { <p class="pending">Sin cambios pendientes.</p> }
|
||||||
@if (hasPending) { <p class="pending" role="status">Hay cambios sin aplicar.</p> }
|
@if (hasPending) { <p class="pending" role="status">Hay cambios sin aplicar.</p> }
|
||||||
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply || (!hasPending && !initialPresentation)" (click)="apply.emit()">Aplicar</button>
|
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply || (!hasPending && !initialPresentation)" (click)="apply.emit()">Aplicar</button>
|
||||||
|
|||||||
@@ -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; }
|
||||||
@@ -21,7 +38,7 @@ p { overflow-wrap: anywhere; line-height: 1.5; margin: var(--issste-space-3) 0;
|
|||||||
.remove { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); }
|
.remove { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); }
|
||||||
.remove button { min-height: 44px; }
|
.remove button { min-height: 44px; }
|
||||||
.apply-button { min-height: 44px; margin-top: var(--issste-space-2); }
|
.apply-button { min-height: 44px; margin-top: var(--issste-space-2); }
|
||||||
.fields.compact { align-items: center; }
|
.fields.compact { align-items: end; }
|
||||||
.fields.compact mat-form-field { flex: 0 1 14rem; }
|
.fields.compact mat-form-field { flex: 0 1 14rem; }
|
||||||
.fields.compact .apply-button { margin-top: 0; }
|
.fields.compact .apply-button { margin-top: 0; }
|
||||||
@media (max-width: 550px) {
|
@media (max-width: 550px) {
|
||||||
|
|||||||
@@ -18,6 +18,10 @@ describe('UX-04 control asistido', () => {
|
|||||||
control = fixture.componentInstance;
|
control = fixture.componentInstance;
|
||||||
});
|
});
|
||||||
afterEach(() => fixture.destroy());
|
afterEach(() => fixture.destroy());
|
||||||
|
function periodSelect() {
|
||||||
|
return fixture.debugElement.queryAll(By.css('mat-form-field'))
|
||||||
|
.find(f => f.nativeElement.textContent.includes('Periodo seleccionado'))!.query(By.directive(MatSelect));
|
||||||
|
}
|
||||||
it('en modo compacto agregar otro periodo sustituye la selección anterior', () => {
|
it('en modo compacto agregar otro periodo sustituye la selección anterior', () => {
|
||||||
fixture.componentRef.setInput('compact', true); fixture.detectChanges();
|
fixture.componentRef.setInput('compact', true); fixture.detectChanges();
|
||||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||||
@@ -25,18 +29,15 @@ describe('UX-04 control asistido', () => {
|
|||||||
expect(control.selectedPeriods).toEqual(['2025-S2']);
|
expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||||
expect(control.entry.added).toEqual(['2025-S1', '2025-S2']);
|
expect(control.entry.added).toEqual(['2025-S1', '2025-S2']);
|
||||||
});
|
});
|
||||||
it('UX-06C: valores largos del trigger preservan Todos, selección explícita y borrador vacío', async () => {
|
it('UX-06C: el trigger muestra el periodo explícito y el borrador vacío no se aplica', async () => {
|
||||||
await fixture.whenStable(); fixture.detectChanges();
|
|
||||||
expect(fixture.nativeElement.querySelector('.select-value')?.textContent).toContain('Todos con reporte');
|
|
||||||
fixture.componentRef.setInput('state', {
|
fixture.componentRef.setInput('state', {
|
||||||
...control.state, editors: { ...control.state.editors, semestre: {
|
...control.state, editors: { ...control.state.editors, semestre: {
|
||||||
added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] },
|
added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S2'] },
|
||||||
} },
|
} },
|
||||||
});
|
});
|
||||||
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
||||||
const values = Array.from(fixture.nativeElement.querySelectorAll('.select-value') as NodeListOf<HTMLElement>);
|
const values = Array.from(fixture.nativeElement.querySelectorAll('.select-value') as NodeListOf<HTMLElement>);
|
||||||
expect(values.map(e => e.textContent)).toContain('2025-S1, 2025-S2');
|
expect(values.map(e => e.textContent)).toContain('2025-S2');
|
||||||
expect(values.map(e => e.textContent)).toContain('Elegir periodos');
|
|
||||||
fixture.componentRef.setInput('state', {
|
fixture.componentRef.setInput('state', {
|
||||||
...control.state, editors: { ...control.state.editors, semestre: {
|
...control.state, editors: { ...control.state.editors, semestre: {
|
||||||
added: ['2025-S1', '2025-S2'], draft: { mode: 'empty' },
|
added: ['2025-S1', '2025-S2'], draft: { mode: 'empty' },
|
||||||
@@ -50,10 +51,11 @@ describe('UX-04 control asistido', () => {
|
|||||||
it('UX-04A: el selector vacío no reescribe el FormControl en cada detección', async () => {
|
it('UX-04A: el selector vacío no reescribe el FormControl en cada detección', async () => {
|
||||||
// Bound the pre-fix reproduction: do not wait for an unstable fixture forever.
|
// Bound the pre-fix reproduction: do not wait for an unstable fixture forever.
|
||||||
fixture.changeDetectorRef.detach();
|
fixture.changeDetectorRef.detach();
|
||||||
control.changeMode('manual');
|
control.select([]);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
await Promise.resolve();
|
await Promise.resolve();
|
||||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
const select = periodSelect();
|
||||||
|
expect(select.componentInstance.multiple).toBe(false);
|
||||||
const model = select.injector.get(NgModel);
|
const model = select.injector.get(NgModel);
|
||||||
const writes = vi.spyOn(model.control, 'setValue');
|
const writes = vi.spyOn(model.control, 'setValue');
|
||||||
const edits = vi.spyOn(control.edited, 'emit');
|
const edits = vi.spyOn(control.edited, 'emit');
|
||||||
@@ -61,16 +63,16 @@ describe('UX-04 control asistido', () => {
|
|||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
await Promise.resolve();
|
await Promise.resolve();
|
||||||
}
|
}
|
||||||
expect(model.control.value).toEqual([]);
|
expect(model.control.value).toBeNull();
|
||||||
expect(writes).not.toHaveBeenCalled();
|
expect(writes).not.toHaveBeenCalled();
|
||||||
expect(edits).not.toHaveBeenCalled();
|
expect(edits).not.toHaveBeenCalled();
|
||||||
expect(control.state.applied?.selection.mode).toBe('todos');
|
expect(control.state.applied?.selection.mode).toBe('todos');
|
||||||
});
|
});
|
||||||
it('UX-04A: meses vacíos se estabilizan al abrir y cerrar selección múltiple', async () => {
|
it('UX-04A: meses vacíos se estabilizan al abrir y cerrar el selector', async () => {
|
||||||
control.changeTipo('mes');
|
control.changeTipo('mes');
|
||||||
control.year = '2025'; control.unit = '01'; control.add(); control.select([]);
|
control.year = '2025'; control.unit = '01'; control.add(); control.select([]);
|
||||||
fixture.detectChanges(); await fixture.whenStable();
|
fixture.detectChanges(); await fixture.whenStable();
|
||||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
const select = periodSelect();
|
||||||
const model = select.injector.get(NgModel);
|
const model = select.injector.get(NgModel);
|
||||||
const writes = vi.spyOn(model.control, 'setValue');
|
const writes = vi.spyOn(model.control, 'setValue');
|
||||||
for (let i = 0; i < 3; i++) {
|
for (let i = 0; i < 3; i++) {
|
||||||
@@ -85,7 +87,7 @@ describe('UX-04 control asistido', () => {
|
|||||||
expect(control.canApply).toBe(false);
|
expect(control.canApply).toBe(false);
|
||||||
});
|
});
|
||||||
it('normaliza el año y rechaza agregar duplicados', () => {
|
it('normaliza el año y rechaza agregar duplicados', () => {
|
||||||
control.changeMode('manual');
|
control.select([]);
|
||||||
control.year = '1'; control.unit = 'S1'; control.add();
|
control.year = '1'; control.unit = 'S1'; control.add();
|
||||||
expect(control.selectedPeriods).toEqual(['0001-S1']);
|
expect(control.selectedPeriods).toEqual(['0001-S1']);
|
||||||
control.add();
|
control.add();
|
||||||
@@ -93,7 +95,7 @@ describe('UX-04 control asistido', () => {
|
|||||||
expect(control.entry.added).toEqual(['0001-S1']);
|
expect(control.entry.added).toEqual(['0001-S1']);
|
||||||
});
|
});
|
||||||
it.each([['0', 'S1'], ['10000', 'S1'], ['2025', 'S3'], ['abc', 'S1'], ['', 'S1']])('rechaza año/unidad %s %s', (year, unit) => {
|
it.each([['0', 'S1'], ['10000', 'S1'], ['2025', 'S3'], ['abc', 'S1'], ['', 'S1']])('rechaza año/unidad %s %s', (year, unit) => {
|
||||||
control.changeMode('manual'); control.year = year; control.unit = unit; control.add();
|
control.select([]); control.year = year; control.unit = unit; control.add();
|
||||||
expect(control.error).toContain('unidad válida'); expect(control.canApply).toBe(false);
|
expect(control.error).toContain('unidad válida'); expect(control.canApply).toBe(false);
|
||||||
});
|
});
|
||||||
it.each(['00', '13', 'S1'])('rechaza unidad mensual %s', unit => {
|
it.each(['00', '13', 'S1'])('rechaza unidad mensual %s', unit => {
|
||||||
@@ -101,21 +103,22 @@ describe('UX-04 control asistido', () => {
|
|||||||
expect(control.entry.added).toEqual([]); expect(control.canApply).toBe(false);
|
expect(control.entry.added).toEqual([]); expect(control.canApply).toBe(false);
|
||||||
});
|
});
|
||||||
it('conserva borradores independientes sin convertir periodos', () => {
|
it('conserva borradores independientes sin convertir periodos', () => {
|
||||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||||
control.changeTipo('mes'); control.year = '2026'; control.unit = '12'; control.add();
|
control.changeTipo('mes'); control.year = '2026'; control.unit = '12'; control.add();
|
||||||
control.changeTipo('semestre'); expect(control.selectedPeriods).toEqual(['2025-S1']);
|
control.changeTipo('semestre'); expect(control.selectedPeriods).toEqual(['2025-S1']);
|
||||||
control.changeTipo('mes'); expect(control.selectedPeriods).toEqual(['2026-12']);
|
control.changeTipo('mes'); expect(control.selectedPeriods).toEqual(['2026-12']);
|
||||||
expect(control.state.applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' } });
|
expect(control.state.applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' } });
|
||||||
});
|
});
|
||||||
it('deselecciona sin eliminar opciones y elimina sin botones dentro de opciones', () => {
|
it('un solo periodo: agregar otro lo reemplaza y varios se rechazan; elimina sin botones dentro de opciones', () => {
|
||||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||||
control.unit = 'S2'; control.add();
|
control.unit = 'S2'; control.add();
|
||||||
control.select(['2025-S2']);
|
expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||||
|
control.select(['2025-S1', '2025-S2']); expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||||
expect(control.entry.added).toEqual(['2025-S1', '2025-S2']);
|
expect(control.entry.added).toEqual(['2025-S1', '2025-S2']);
|
||||||
control.remove('2025-S1'); expect(control.selectedPeriods).toEqual(['2025-S2']);
|
control.remove('2025-S1'); expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
const select = periodSelect();
|
||||||
expect(select).toBeTruthy();
|
expect(select.componentInstance.multiple).toBe(false);
|
||||||
expect(select.nativeElement.querySelector('button')).toBeNull();
|
expect(select.nativeElement.querySelector('button')).toBeNull();
|
||||||
expect(fixture.nativeElement.textContent).toContain('Eliminar 2025-S2');
|
expect(fixture.nativeElement.textContent).toContain('Eliminar 2025-S2');
|
||||||
fixture.nativeElement.querySelector('.remove button').click();
|
fixture.nativeElement.querySelector('.remove button').click();
|
||||||
@@ -126,7 +129,7 @@ describe('UX-04 control asistido', () => {
|
|||||||
it('emite edición y aplicación por separado y explica la disponibilidad desconocida', () => {
|
it('emite edición y aplicación por separado y explica la disponibilidad desconocida', () => {
|
||||||
const edited = vi.spyOn(control.edited, 'emit');
|
const edited = vi.spyOn(control.edited, 'emit');
|
||||||
const apply = vi.spyOn(control.apply, 'emit');
|
const apply = vi.spyOn(control.apply, 'emit');
|
||||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||||
expect(edited).toHaveBeenCalledTimes(2); expect(apply).not.toHaveBeenCalled();
|
expect(edited).toHaveBeenCalledTimes(2); expect(apply).not.toHaveBeenCalled();
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar');
|
expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar');
|
||||||
@@ -135,11 +138,20 @@ 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('no ofrece Todos en meses cuando el primero es semestre', () => {
|
it('ofrece el intervalo de análisis mensual o semestral, sin Modalidad', () => {
|
||||||
control.changeTipo('mes'); fixture.detectChanges();
|
const labels = Array.from(fixture.nativeElement.querySelectorAll('mat-label') as NodeListOf<HTMLElement>).map(l => l.textContent);
|
||||||
expect(fixture.nativeElement.textContent).not.toContain('Todos los meses');
|
expect(fixture.nativeElement.querySelector('.field-label').textContent).toBe('Intervalo de análisis');
|
||||||
control.changeMode('todos'); expect(control.entry.draft.mode).toBe('empty');
|
expect(labels).not.toContain('Modalidad');
|
||||||
control.changeTipo('semestre'); control.changeTipo('mes');
|
expect([...fixture.nativeElement.querySelectorAll('mat-button-toggle')].map((b: HTMLElement) => b.textContent!.trim())).toEqual(['Mensual', 'Semestral']);
|
||||||
expect(control.entry.draft.mode).toBe('empty');
|
});
|
||||||
|
it('al cambiar de intervalo elige el periodo más reciente con reporte', () => {
|
||||||
|
fixture.componentRef.setInput('availability', { status: 'ready', byIndicator: {}, errors: {},
|
||||||
|
options: { semestre: ['2025-S2', '2025-S1'], mes: ['2025-12', '2025-11'] } });
|
||||||
|
fixture.detectChanges();
|
||||||
|
control.changeTipo('mes');
|
||||||
|
expect(control.selectedPeriods).toEqual(['2025-12']);
|
||||||
|
control.select(['2025-11']); control.changeTipo('semestre'); control.changeTipo('mes');
|
||||||
|
// A period already chosen for that interval is kept.
|
||||||
|
expect(control.selectedPeriods).toEqual(['2025-11']);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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',
|
||||||
@@ -32,7 +33,7 @@ export class IndicadorPeriodFilters implements OnChanges {
|
|||||||
ngOnChanges() { this.year = this.unit = this.error = ''; }
|
ngOnChanges() { this.year = this.unit = this.error = ''; }
|
||||||
get entry() { return this.state.editors[this.state.tipo]!; }
|
get entry() { return this.state.editors[this.state.tipo]!; }
|
||||||
// NgModel schedules a microtask and markForCheck when its input reference changes.
|
// NgModel schedules a microtask and markForCheck when its input reference changes.
|
||||||
// Keep the empty multiple-select value stable so an unchanged draft can settle.
|
// Keep the empty selection stable so an unchanged draft can settle.
|
||||||
private readonly emptyPeriods: string[] = [];
|
private readonly emptyPeriods: string[] = [];
|
||||||
get selectedPeriods() { return this.entry.draft.mode === 'explicit' ? this.entry.draft.periodos : this.emptyPeriods; }
|
get selectedPeriods() { return this.entry.draft.mode === 'explicit' ? this.entry.draft.periodos : this.emptyPeriods; }
|
||||||
get options() { return this.availability ? this.availability.options[this.state.tipo] : this.entry.added; }
|
get options() { return this.availability ? this.availability.options[this.state.tipo] : this.entry.added; }
|
||||||
@@ -45,21 +46,21 @@ export class IndicadorPeriodFilters implements OnChanges {
|
|||||||
get hasPending() { return pending(this.state); }
|
get hasPending() { return pending(this.state); }
|
||||||
get summary() { return describePeriods(this.state.tipo, this.entry.draft); }
|
get summary() { return describePeriods(this.state.tipo, this.entry.draft); }
|
||||||
get appliedSummary() { return this.state.applied ? describePeriods(this.state.applied.tipo, this.state.applied.selection) : 'Todavía no hay selección aplicada'; }
|
get appliedSummary() { return this.state.applied ? describePeriods(this.state.applied.tipo, this.state.applied.selection) : 'Todavía no hay selección aplicada'; }
|
||||||
|
// There is no "every period" choice in the editor: a new interval starts on its most recent
|
||||||
|
// period with a report (options are sorted newest first).
|
||||||
changeTipo(tipo: TipoPeriodo) {
|
changeTipo(tipo: TipoPeriodo) {
|
||||||
if (!this.types.includes(tipo)) return;
|
if (!this.types.includes(tipo)) return;
|
||||||
this.state.tipo = tipo;
|
this.state.tipo = tipo;
|
||||||
this.state.editors[tipo] ??= newEditor(tipo, this.types[0]);
|
this.state.editors[tipo] ??= newEditor(tipo, this.types[0]);
|
||||||
this.year = this.unit = this.error = '';
|
this.year = this.unit = this.error = '';
|
||||||
|
if (this.entry.draft.mode !== 'explicit' && this.availability?.status === 'ready' && this.options.length)
|
||||||
|
this.entry.draft = { mode: 'explicit', periodos: [this.options[0]] };
|
||||||
this.edited.emit();
|
this.edited.emit();
|
||||||
}
|
}
|
||||||
changeMode(mode: 'todos' | 'manual') {
|
// Only one period can be chosen: cards and figures never combine periods.
|
||||||
if (mode === 'todos' && (this.state.tipo !== 'semestre' || this.state.tipo !== this.types[0])) return;
|
|
||||||
this.entry.draft = mode === 'todos' ? { mode: 'todos' } : { mode: 'empty' };
|
|
||||||
this.error = '';
|
|
||||||
this.edited.emit();
|
|
||||||
}
|
|
||||||
select(values: string[]) {
|
select(values: string[]) {
|
||||||
const unique = [...new Set(this.compact ? values.slice(-1) : values)];
|
const unique = [...new Set(this.compact ? values.slice(-1) : values)];
|
||||||
|
if (unique.length > 1) return;
|
||||||
if (unique.some(p => !this.options.includes(p) || parsePeriodos(p, this.state.tipo)?.[0] !== p)) return;
|
if (unique.some(p => !this.options.includes(p) || parsePeriodos(p, this.state.tipo)?.[0] !== p)) return;
|
||||||
this.entry.draft = unique.length ? { mode: 'explicit', periodos: unique as [string, ...string[]] } : { mode: 'empty' };
|
this.entry.draft = unique.length ? { mode: 'explicit', periodos: unique as [string, ...string[]] } : { mode: 'empty' };
|
||||||
this.edited.emit();
|
this.edited.emit();
|
||||||
@@ -73,13 +74,11 @@ export class IndicadorPeriodFilters implements OnChanges {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (this.entry.added.includes(period)) { this.error = 'Este periodo ya está agregado.'; return; }
|
if (this.entry.added.includes(period)) { this.error = 'Este periodo ya está agregado.'; return; }
|
||||||
const selected = this.selectedPeriods;
|
|
||||||
this.entry.added.push(period);
|
this.entry.added.push(period);
|
||||||
this.select([...selected, period]);
|
this.select([period]);
|
||||||
}
|
}
|
||||||
remove(period: string) {
|
remove(period: string) {
|
||||||
this.entry.added = this.entry.added.filter(p => p !== period);
|
this.entry.added = this.entry.added.filter(p => p !== period);
|
||||||
// Removing an unselected option must not change the Todos mode.
|
|
||||||
if (this.entry.draft.mode === 'explicit') this.select(this.selectedPeriods.filter(p => p !== period));
|
if (this.entry.draft.mode === 'explicit') this.select(this.selectedPeriods.filter(p => p !== period));
|
||||||
else this.edited.emit();
|
else this.edited.emit();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import { PlotlyFigure, Tema } from './indicadores.models';
|
||||||
|
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
|
||||||
|
import { CeldaMapa, ComparacionAnalisis, DistribucionAnalisis, MapaAnalisis, TendenciaAnalisis } from './indicadores-analisis.service';
|
||||||
|
|
||||||
|
// The figures of the descriptive analysis. They draw what the answer publishes and nothing else: a suppressed or missing
|
||||||
|
// value is left out of the drawing (a gap, never a zero) and named in the table beside it.
|
||||||
|
const miles = (v: number) => v.toLocaleString('es-MX');
|
||||||
|
const pct = (v: number) => v.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 }) + ' %';
|
||||||
|
const base = (tema: Tema, alto: number, margen: Record<string, number>) => {
|
||||||
|
const t = c2Theme(tema);
|
||||||
|
return { autosize: true, height: alto, paper_bgcolor: t.background, plot_bgcolor: t.background, font: { color: t.text }, margin: margen, showlegend: false };
|
||||||
|
};
|
||||||
|
const config = { displayModeBar: false };
|
||||||
|
|
||||||
|
/** Share of the selection by category, with the Wilson interval of each published share as a horizontal bar. */
|
||||||
|
export function distribucionFigura(d: DistribucionAnalisis, tema: Tema): PlotlyFigure {
|
||||||
|
const t = c2Theme(tema);
|
||||||
|
const items = d.items.filter(i => !i.suprimido && (i.n ?? 0) > 0 && i.porcentaje !== null);
|
||||||
|
return {
|
||||||
|
data: [{
|
||||||
|
type: 'bar', orientation: 'h', y: items.map(i => i.etiqueta), x: items.map(i => i.porcentaje), customdata: items.map(i => i.codigo),
|
||||||
|
marker: { color: C2_PALETTE.series[0] },
|
||||||
|
error_x: { type: 'data', symmetric: false, array: items.map(i => i.ic_alto! - i.porcentaje!), arrayminus: items.map(i => i.porcentaje! - i.ic_bajo!), color: t.text },
|
||||||
|
text: items.map(i => `${miles(i.n!)} (${pct(i.porcentaje!)})`), textposition: 'inside', insidetextanchor: 'start', textfont: { color: '#081839' }, cliponaxis: false,
|
||||||
|
hovertemplate: items.map(i => `<b>${i.etiqueta}</b><br>${miles(i.n!)} pacientes<br>${pct(i.porcentaje!)} (IC 95 %: ${pct(i.ic_bajo!)} a ${pct(i.ic_alto!)})<extra></extra>`),
|
||||||
|
}],
|
||||||
|
layout: { ...base(tema, Math.max(220, 60 + 44 * items.length), { t: 24, l: 150, r: 90, b: 52 }),
|
||||||
|
xaxis: { title: { text: 'Porcentaje de la selección' }, range: [0, 100], ticksuffix: ' %', gridcolor: t.grid, fixedrange: true },
|
||||||
|
yaxis: { autorange: 'reversed', automargin: true, fixedrange: true } },
|
||||||
|
config,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The share of cases per group as a point with its interval: groups that aren't published have no point. */
|
||||||
|
export function comparacionFigura(c: ComparacionAnalisis, tema: Tema, medida: string): PlotlyFigure {
|
||||||
|
const t = c2Theme(tema);
|
||||||
|
const grupos = c.grupos.filter(g => g.estado === 'disponible');
|
||||||
|
return {
|
||||||
|
data: [{
|
||||||
|
type: 'scatter', mode: 'markers', y: grupos.map(g => g.etiqueta), x: grupos.map(g => g.valor), customdata: grupos.map(g => g.codigo),
|
||||||
|
marker: { color: C2_PALETTE.series[1], size: 11 },
|
||||||
|
error_x: { type: 'data', symmetric: false, array: grupos.map(g => g.ic_alto! - g.valor!), arrayminus: grupos.map(g => g.valor! - g.ic_bajo!), color: t.text, thickness: 2, width: 6 },
|
||||||
|
hovertemplate: grupos.map(g => `<b>${g.etiqueta}</b><br>${g.casos} de ${g.total} pacientes con resultado<br>${pct(g.valor!)} (IC 95 %: ${pct(g.ic_bajo!)} a ${pct(g.ic_alto!)})<extra></extra>`),
|
||||||
|
}],
|
||||||
|
layout: { ...base(tema, Math.max(220, 80 + 46 * grupos.length), { t: 24, l: 150, r: 28, b: 56 }),
|
||||||
|
xaxis: { title: { text: `${medida} entre pacientes con resultado de biopsia` }, range: [0, 100], ticksuffix: ' %', gridcolor: t.grid, fixedrange: true },
|
||||||
|
yaxis: { autorange: 'reversed', type: 'category', automargin: true, fixedrange: true } },
|
||||||
|
config,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const textoCelda = (c: CeldaMapa, medida: string) => c.suprimido ? 'No publicado'
|
||||||
|
: medida === 'pacientes' ? `${miles(c.n!)} pacientes` : c.resultado.estado === 'disponible' ? `${pct(c.resultado.valor!)}<br>${c.resultado.casos} de ${c.resultado.total}` : c.resultado.estado === 'suprimido' ? 'No publicado' : 'Sin pacientes con resultado';
|
||||||
|
|
||||||
|
/** BI-RADS by age group: the number of patients or the share of cases in each cell; hidden cells are blank. */
|
||||||
|
export function mapaFigura(m: MapaAnalisis, tema: Tema, medida: 'pacientes' | 'resultado'): PlotlyFigure {
|
||||||
|
const t = c2Theme(tema);
|
||||||
|
const celdas = new Map(m.celdas.map(c => [c.fila + '\u0000' + c.columna, c]));
|
||||||
|
const valor = (c: CeldaMapa | undefined) => !c || c.suprimido ? null : medida === 'pacientes' ? c.n : c.resultado.estado === 'disponible' ? c.resultado.valor : null;
|
||||||
|
const z = m.filas.categorias.map(f => m.columnas.categorias.map(c => valor(celdas.get(f.codigo + '\u0000' + c.codigo))));
|
||||||
|
return {
|
||||||
|
data: [{
|
||||||
|
type: 'heatmap', x: m.columnas.categorias.map(c => c.etiqueta), y: m.filas.categorias.map(f => f.etiqueta), z,
|
||||||
|
customdata: m.filas.categorias.map(f => m.columnas.categorias.map(c => [f.codigo, c.codigo])),
|
||||||
|
text: m.filas.categorias.map(f => m.columnas.categorias.map(c => textoCelda(celdas.get(f.codigo + '\u0000' + c.codigo)!, medida === 'pacientes' ? 'pacientes' : 'resultado'))),
|
||||||
|
hovertemplate: '%{y}, %{x}<br>%{text}<extra></extra>', hoverongaps: false, xgap: 2, ygap: 2,
|
||||||
|
colorscale: [[0, '#E4EEC0'], [1, '#6A8000']], zmin: 0, zmax: medida === 'resultado' ? 100 : undefined,
|
||||||
|
colorbar: { title: { text: medida === 'resultado' ? '% de casos' : 'Pacientes' } },
|
||||||
|
}],
|
||||||
|
layout: { ...base(tema, Math.max(280, 90 + 40 * m.filas.categorias.length), { t: 24, l: 130, r: 28, b: 60 }),
|
||||||
|
xaxis: { automargin: true, fixedrange: true, type: 'category' }, yaxis: { autorange: 'reversed', automargin: true, fixedrange: true, type: 'category' },
|
||||||
|
plot_bgcolor: t.grid },
|
||||||
|
config,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FigurasTendencia { actividad: PlotlyFigure; proporcion: PlotlyFigure; }
|
||||||
|
|
||||||
|
/** Reports per period (bars; a hidden total is a gap) and the share of malignant results with its interval. */
|
||||||
|
export function tendenciaFiguras(r: TendenciaAnalisis, tema: Tema, medida: string): FigurasTendencia {
|
||||||
|
const t = c2Theme(tema);
|
||||||
|
const x = r.periodos.map(p => p.periodo + (p.incompleto ? ' (en curso)' : ''));
|
||||||
|
const disponibles = r.periodos.map((p, i) => ({ p, x: x[i] })).filter(({ p }) => p.maligno.estado === 'disponible');
|
||||||
|
return {
|
||||||
|
actividad: {
|
||||||
|
data: [
|
||||||
|
{ type: 'bar', name: 'Reportes de mastografía', x, y: r.periodos.map(p => p.reportes_mastografia.total), marker: { color: C2_PALETTE.series[2] },
|
||||||
|
hovertemplate: '%{x}<br>%{y} reportes de mastografía<extra></extra>' },
|
||||||
|
{ type: 'bar', name: 'Reportes de biopsia', x, y: r.periodos.map(p => p.reportes_biopsia.total), marker: { color: C2_PALETTE.series[3] },
|
||||||
|
hovertemplate: '%{x}<br>%{y} reportes de biopsia<extra></extra>' },
|
||||||
|
],
|
||||||
|
layout: { ...base(tema, 340, { t: 24, l: 56, r: 16, b: 80 }), showlegend: true, legend: { orientation: 'h', y: -0.28 }, barmode: 'group',
|
||||||
|
xaxis: { type: 'category', automargin: true, fixedrange: true }, yaxis: { title: { text: 'Reportes' }, gridcolor: t.grid, rangemode: 'tozero', fixedrange: true } },
|
||||||
|
config,
|
||||||
|
},
|
||||||
|
proporcion: {
|
||||||
|
data: [{
|
||||||
|
type: 'scatter', mode: 'lines+markers', x: disponibles.map(d => d.x), y: disponibles.map(d => d.p.maligno.valor), connectgaps: false,
|
||||||
|
line: { color: C2_PALETTE.series[1] }, marker: { color: C2_PALETTE.series[1], size: 9 },
|
||||||
|
error_y: { type: 'data', symmetric: false, array: disponibles.map(d => d.p.maligno.ic_alto! - d.p.maligno.valor!), arrayminus: disponibles.map(d => d.p.maligno.valor! - d.p.maligno.ic_bajo!), color: t.text },
|
||||||
|
hovertemplate: disponibles.map(d => `${d.x}<br>${d.p.maligno.casos} de ${d.p.maligno.total} reportes de biopsia con resultado<br>${pct(d.p.maligno.valor!)} (IC 95 %: ${pct(d.p.maligno.ic_bajo!)} a ${pct(d.p.maligno.ic_alto!)})<extra></extra>`),
|
||||||
|
}],
|
||||||
|
layout: { ...base(tema, 340, { t: 24, l: 64, r: 16, b: 64 }),
|
||||||
|
xaxis: { type: 'category', categoryorder: 'array', categoryarray: x, automargin: true, fixedrange: true },
|
||||||
|
yaxis: { title: { text: medida }, range: [0, 100], ticksuffix: ' %', gridcolor: t.grid, fixedrange: true } },
|
||||||
|
config,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user