Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4ffd3797b6 | |||
| b42428b068 | |||
| d9009a2e1e | |||
| c509cb7f87 | |||
| 5807f218b1 | |||
| 62cdb252ca | |||
| 8f2906fe6f | |||
| e8628508d8 | |||
| f4d2a3e85f |
+2
-5
@@ -1,10 +1,7 @@
|
||||
# Production image: build the Angular app, serve the static bundle with
|
||||
# nginx, and reverse-proxy the API paths to the `webapi` compose service —
|
||||
# the same routing `proxy.conf.json` gives `ng serve` in development, so the
|
||||
# app's relative `/imports`, `/data`, ... calls work unchanged.
|
||||
# Production image: the Angular build served by nginx, which proxies the API paths to `webapi`.
|
||||
FROM node:22-slim AS build
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json* ./
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY . .
|
||||
RUN npx ng build --configuration production
|
||||
|
||||
@@ -1,59 +1,16 @@
|
||||
# WebApp
|
||||
|
||||
This project was generated using [Angular CLI](https://github.com/angular/angular-cli) version 22.1.8.
|
||||
|
||||
## Development server
|
||||
|
||||
To start a local development server, run:
|
||||
Interfaz de ISSSTELEON en Angular y Angular Material: conexión e importación de
|
||||
datos (`/conectar`), bitácora de cargas (`/bitacora`), gobernanza y tablero de
|
||||
indicadores (`/indicadores`).
|
||||
|
||||
```bash
|
||||
ng serve
|
||||
npm ci
|
||||
npx ng serve # http://localhost:4200
|
||||
npx ng test --watch=false # pruebas unitarias (Vitest)
|
||||
npx ng build # compilación de producción en dist/WebApp
|
||||
```
|
||||
|
||||
Once the server is running, open your browser and navigate to `http://localhost:4200/`. The application will automatically reload whenever you modify any of the source files.
|
||||
|
||||
## Code scaffolding
|
||||
|
||||
Angular CLI includes powerful code scaffolding tools. To generate a new component, run:
|
||||
|
||||
```bash
|
||||
ng generate component component-name
|
||||
```
|
||||
|
||||
For a complete list of available schematics (such as `components`, `directives`, or `pipes`), run:
|
||||
|
||||
```bash
|
||||
ng generate --help
|
||||
```
|
||||
|
||||
## Building
|
||||
|
||||
To build the project run:
|
||||
|
||||
```bash
|
||||
ng build
|
||||
```
|
||||
|
||||
This will compile your project and store the build artifacts in the `dist/` directory. By default, the production build optimizes your application for performance and speed.
|
||||
|
||||
## Running unit tests
|
||||
|
||||
To execute unit tests with the [Vitest](https://vitest.dev/) test runner, use the following command:
|
||||
|
||||
```bash
|
||||
ng test
|
||||
```
|
||||
|
||||
## Running end-to-end tests
|
||||
|
||||
For end-to-end (e2e) testing, run:
|
||||
|
||||
```bash
|
||||
ng e2e
|
||||
```
|
||||
|
||||
Angular CLI does not come with an end-to-end testing framework by default. You can choose one that suits your needs.
|
||||
|
||||
## Additional Resources
|
||||
|
||||
For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.
|
||||
`ng serve` envía las rutas de la API a WebApi en `localhost:5050`
|
||||
(`proxy.conf.json`). La imagen de Docker (`Dockerfile`) sirve la compilación con
|
||||
nginx (`nginx.conf`), que reenvía esas mismas rutas al servicio `webapi`.
|
||||
|
||||
@@ -8,6 +8,10 @@ server {
|
||||
# the ~33% base64 overhead.
|
||||
client_max_body_size 270m;
|
||||
|
||||
gzip on;
|
||||
gzip_types text/css application/javascript application/json image/svg+xml;
|
||||
gzip_min_length 1024;
|
||||
|
||||
location ~ ^/(api|imports|data|cacu|cama|tea|governance|reportes|health)(/|$) {
|
||||
proxy_pass http://webapi:5000;
|
||||
proxy_set_header Host $host;
|
||||
|
||||
@@ -2,11 +2,21 @@ import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideRouter } from '@angular/router';
|
||||
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 = {
|
||||
providers: [
|
||||
provideBrowserGlobalErrorListeners(),
|
||||
provideRouter(routes),
|
||||
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 },
|
||||
]
|
||||
};
|
||||
|
||||
+6
-19
@@ -4,25 +4,12 @@
|
||||
<a class="brand" routerLink="/" aria-label="ISSSTELEON, inicio">
|
||||
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
|
||||
</a>
|
||||
@if (activeDomain(); as domain) {
|
||||
<span class="platform-title">{{ title }}</span>
|
||||
<button class="domain-selector" mat-button [matMenuTriggerFor]="domainMenu"
|
||||
[attr.aria-label]="'Dominio actual: ' + domainLabels[domain] + '. Cambiar dominio'">
|
||||
{{ domainLabels[domain] }} <span aria-hidden="true">▾</span>
|
||||
</button>
|
||||
<mat-menu #domainMenu="matMenu" aria-label="Cambiar dominio de indicadores">
|
||||
@for (option of otherDomains(); track option) {
|
||||
<a mat-menu-item [routerLink]="['/indicadores', option]">{{ domainLabels[option] }}</a>
|
||||
}
|
||||
</mat-menu>
|
||||
} @else {
|
||||
<nav class="site-header__nav" aria-label="Secciones">
|
||||
<a class="site-header__section" routerLink="/">Análisis de información</a>
|
||||
@if (breadcrumb(); as crumb) {
|
||||
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
|
||||
}
|
||||
</nav>
|
||||
}
|
||||
<nav class="site-header__nav" aria-label="Secciones">
|
||||
<a class="site-header__section" routerLink="/">Análisis de información</a>
|
||||
@if (breadcrumb(); as crumb) {
|
||||
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
|
||||
}
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
|
||||
+13
-1
@@ -6,6 +6,12 @@ const loadIndicadores = () => import('./features/indicadores/indicadores-page').
|
||||
|
||||
export const routes: Routes = [
|
||||
{ path: '', component: Home, title: 'Análisis de información | ISSSTELEON' },
|
||||
{
|
||||
path: 'indicadores/tea-estatus',
|
||||
title: 'Casos por estatus | ISSSTELEON',
|
||||
loadComponent: () => import('./features/indicadores/tea-status-page').then(m => m.TeaStatusPage),
|
||||
data: { workspace: true, breadcrumb: 'Casos por estatus' },
|
||||
},
|
||||
{
|
||||
path: 'conectar',
|
||||
title: 'Conectar datos | ISSSTELEON',
|
||||
@@ -23,9 +29,15 @@ export const routes: Routes = [
|
||||
{
|
||||
path: 'bitacora',
|
||||
title: 'Bitácora de cargas | ISSSTELEON',
|
||||
loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportesPage),
|
||||
loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportsPage),
|
||||
data: { workspace: true, breadcrumb: 'Bitácora de cargas' },
|
||||
},
|
||||
{
|
||||
path: 'kpis',
|
||||
title: 'Indicadores | ISSSTELEON',
|
||||
loadComponent: () => import('./features/indicadores/kpis-page').then(m => m.KpisPage),
|
||||
data: { workspace: true, breadcrumb: 'Indicadores' },
|
||||
},
|
||||
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
|
||||
...DOMINIOS.map(dominio => ({
|
||||
path: `indicadores/${dominio}`,
|
||||
|
||||
@@ -29,31 +29,6 @@
|
||||
width: clamp(180px, 16vw, 200px);
|
||||
}
|
||||
|
||||
.platform-title {
|
||||
color: var(--color-text);
|
||||
font-family: var(--issste-font-heading);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
line-height: 1.15;
|
||||
margin-inline-start: var(--issste-space-4);
|
||||
margin-inline-end: auto;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.domain-selector {
|
||||
flex: 0 0 auto;
|
||||
background-color: var(--issste-accent);
|
||||
color: var(--issste-text);
|
||||
font-weight: 700;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.domain-selector:hover { background-color: var(--issste-accent); filter: brightness(.94); }
|
||||
.domain-selector:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||
|
||||
@media (max-width: 599px) {
|
||||
.platform-title { font-size: 1.125rem; min-width: 0; }
|
||||
}
|
||||
|
||||
.site-header__nav {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
|
||||
@@ -30,17 +30,6 @@ describe('App', () => {
|
||||
expect(page.querySelector('.site-footer')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('an indicators page shows the platform title and a menu named after its domain', async () => {
|
||||
// Fails if the header stops naming the domain or offers the current one among the others.
|
||||
const page = await render('/indicadores/cama');
|
||||
expect(page.querySelector('.platform-title')?.textContent).toContain('Plataforma de Indicadores');
|
||||
expect(page.querySelector('.domain-selector')?.textContent).toContain('Cáncer de mama');
|
||||
(page.querySelector('.domain-selector') as HTMLButtonElement).click();
|
||||
const options = Array.from(document.querySelectorAll('.mat-mdc-menu-panel a')).map(a => a.textContent?.trim());
|
||||
expect(options).toEqual(['TEA', 'CaCu']);
|
||||
expect(page.querySelector('.site-header__crumb')).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();
|
||||
|
||||
+1
-13
@@ -1,13 +1,10 @@
|
||||
import { Component, computed, inject } from '@angular/core';
|
||||
import { toSignal } from '@angular/core/rxjs-interop';
|
||||
import { ActivatedRoute, NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatMenuModule } from '@angular/material/menu';
|
||||
import { filter, map } from 'rxjs';
|
||||
import { Dominio, DOMINIOS } from './features/indicadores/indicadores.models';
|
||||
|
||||
@Component({
|
||||
imports: [RouterLink, RouterOutlet, MatButtonModule, MatMenuModule],
|
||||
imports: [RouterLink, RouterOutlet],
|
||||
selector: 'app-root',
|
||||
styleUrl: './app.scss',
|
||||
templateUrl: './app.html',
|
||||
@@ -16,15 +13,6 @@ export class App {
|
||||
private readonly router = inject(Router);
|
||||
private readonly route = inject(ActivatedRoute);
|
||||
|
||||
protected readonly title = 'Plataforma de Indicadores';
|
||||
protected readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'Cáncer de mama' };
|
||||
private readonly url = toSignal(this.router.events.pipe(
|
||||
filter((event) => event instanceof NavigationEnd), map(event => event.urlAfterRedirects)), { initialValue: this.router.url });
|
||||
// On an indicators page the header names its domain and switches to the others.
|
||||
protected readonly activeDomain = computed(() =>
|
||||
DOMINIOS.find(domain => new RegExp(`^/indicadores/${domain}(?:[/?#]|$)`).test(this.url())));
|
||||
protected readonly otherDomains = computed(() => DOMINIOS.filter(domain => domain !== this.activeDomain()));
|
||||
|
||||
private readonly leafRouteData = toSignal(
|
||||
this.router.events.pipe(
|
||||
filter((event) => event instanceof NavigationEnd),
|
||||
|
||||
@@ -136,7 +136,7 @@ export interface ImportSourcePayload extends SourceLocator {
|
||||
defaults?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// -- documents -----------------------------------------------------------------
|
||||
// Clinical documents
|
||||
|
||||
export type OcrMode = 'auto' | 'always' | 'never';
|
||||
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
/** Base64 of a File's bytes, for JSON endpoints that carry a file. */
|
||||
export async function fileToBase64(file: Blob): Promise<string> {
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
const chunk = 0x8000;
|
||||
let binary = '';
|
||||
for (let i = 0; i < bytes.length; i += chunk) {
|
||||
binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
|
||||
}
|
||||
return btoa(binary);
|
||||
export function fileToBase64(file: Blob): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
const dataUrl = reader.result as string;
|
||||
resolve(dataUrl.slice(dataUrl.indexOf(',') + 1));
|
||||
};
|
||||
reader.onerror = () => reject(reader.error);
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
@if (store.connections().length === 0) {
|
||||
<div class="pane__empty">
|
||||
<app-file-dropzone [accept]="store.acceptedExtensions()" [multiple]="true" (filesChange)="onFilesDropped($event)"></app-file-dropzone>
|
||||
<app-file-dropzone [accept]="store.acceptedExtensions()" [keepSelection]="false" (filesChange)="onFilesDropped($event)"></app-file-dropzone>
|
||||
<button mat-stroked-button type="button" class="pane__db-button" (click)="addConnection.emit()">
|
||||
<mat-icon aria-hidden="true">storage</mat-icon>Conectar una base de datos
|
||||
</button>
|
||||
|
||||
@@ -69,7 +69,7 @@
|
||||
}
|
||||
}
|
||||
</p>
|
||||
<app-file-dropzone [accept]="entry()?.connector?.extensions ?? []" [multiple]="true" (filesChange)="files.set($event)"></app-file-dropzone>
|
||||
<app-file-dropzone [accept]="entry()?.connector?.extensions ?? []" (filesChange)="files.set($event)"></app-file-dropzone>
|
||||
}
|
||||
|
||||
@case ('database') {
|
||||
|
||||
@@ -83,10 +83,8 @@ export class ConnectorGalleryDialog {
|
||||
this.categories.filter((c) => c.id === 'all' || this.entries().some((entry) => entry.category === c.id)),
|
||||
);
|
||||
|
||||
// -- files --
|
||||
readonly files = signal<File[]>([]);
|
||||
|
||||
// -- database --
|
||||
readonly serverForm = this.formBuilder.nonNullable.group({
|
||||
host: ['', Validators.required],
|
||||
port: [null as number | null],
|
||||
|
||||
@@ -101,8 +101,6 @@ export class DocumentReviewDialog {
|
||||
});
|
||||
}
|
||||
|
||||
// -- settings ------------------------------------------------------------
|
||||
|
||||
updateSettings(patch: Partial<DocumentSettings>): void {
|
||||
this.settings.update((settings) => ({ ...settings, ...patch }));
|
||||
}
|
||||
@@ -128,8 +126,6 @@ export class DocumentReviewDialog {
|
||||
});
|
||||
}
|
||||
|
||||
// -- records and values ------------------------------------------------------
|
||||
|
||||
select(index: number): void {
|
||||
this.selectedIndex.set(index);
|
||||
this.page.set(null);
|
||||
@@ -171,8 +167,6 @@ export class DocumentReviewDialog {
|
||||
return record.conflicts.find((conflict) => conflict.field === field) ?? null;
|
||||
}
|
||||
|
||||
// -- pages and images ----------------------------------------------------------
|
||||
|
||||
thumbnailKey(image: DocumentImage): string {
|
||||
return `${image.document}|${image.page_number}|${image.bbox.join(',')}`;
|
||||
}
|
||||
@@ -199,8 +193,6 @@ export class DocumentReviewDialog {
|
||||
});
|
||||
}
|
||||
|
||||
// -- close -------------------------------------------------------------------------
|
||||
|
||||
apply(): void {
|
||||
this.table.configure(this.settings(), { [this.target.key]: this.overrides() });
|
||||
this.dialogRef.close(true);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<mat-icon class="dropzone__icon" aria-hidden="true">cloud_upload</mat-icon>
|
||||
<p class="dropzone__title">Arrastra tus archivos aquí</p>
|
||||
<p class="dropzone__formats">{{ formatsLabel }}</p>
|
||||
<input #fileInput class="visually-hidden" type="file" [multiple]="multiple" [attr.accept]="acceptAttribute" aria-label="Seleccionar archivos" (change)="onFileSelection($event)" />
|
||||
<input #fileInput class="visually-hidden" type="file" [multiple]="multiple()" [attr.accept]="acceptAttribute" aria-label="Seleccionar archivos" (change)="onFileSelection($event)" />
|
||||
<button class="upload-action upload-action--outlined select-files-button" mat-stroked-button type="button" (click)="fileInput.click()">
|
||||
<mat-icon aria-hidden="true">upload_file</mat-icon>
|
||||
<span>Seleccionar archivos</span>
|
||||
|
||||
@@ -2,8 +2,10 @@ import { TestBed } from '@angular/core/testing';
|
||||
import { FileDropzone } from './file-dropzone';
|
||||
|
||||
describe('FileDropzone', () => {
|
||||
function createFixture() {
|
||||
function createFixture(keepSelection = true) {
|
||||
const fixture = TestBed.createComponent(FileDropzone);
|
||||
fixture.componentRef.setInput('accept', ['xlsx', 'csv', 'json', 'pdf']);
|
||||
fixture.componentRef.setInput('keepSelection', keepSelection);
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
@@ -81,7 +83,27 @@ describe('FileDropzone', () => {
|
||||
expect(emitted.at(-1)).toEqual([]);
|
||||
});
|
||||
|
||||
it('honors a custom accept input, keeping pdf available by default', () => {
|
||||
it('without keepSelection emits only each new batch and lists nothing', () => {
|
||||
const fixture = createFixture(false);
|
||||
const compiled = fixture.nativeElement as HTMLElement;
|
||||
const component = fixture.componentInstance;
|
||||
const emitted: File[][] = [];
|
||||
component.filesChange.subscribe((files) => emitted.push(files));
|
||||
const drop = (files: File[]) =>
|
||||
component.onDrop({ preventDefault: () => undefined, dataTransfer: { files } } as unknown as DragEvent);
|
||||
|
||||
const first = new File(['a'], 'uno.csv');
|
||||
const second = new File(['b'], 'dos.csv');
|
||||
drop([first]);
|
||||
drop([second]);
|
||||
drop([new File(['x'], 'malo.docx')]);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(emitted).toEqual([[first], [second]]);
|
||||
expect(compiled.querySelectorAll('.file-row')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('honors a custom accept input', () => {
|
||||
const fixture = createFixture();
|
||||
expect(fixture.componentInstance.allowedExtensions.has('pdf')).toBe(true);
|
||||
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { Component, EventEmitter, Input, Output, signal } from '@angular/core';
|
||||
import { Component, input, output, signal } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
|
||||
/** Drag-and-drop and file-picker area that collects a validated list of files. */
|
||||
/**
|
||||
* Drag-and-drop and file-picker area that validates files by extension and size.
|
||||
* With `keepSelection` it keeps and emits the whole selected list; without it,
|
||||
* it emits only each batch of newly accepted files and keeps nothing.
|
||||
*/
|
||||
@Component({
|
||||
imports: [MatButtonModule, MatIconModule],
|
||||
selector: 'app-file-dropzone',
|
||||
@@ -10,9 +14,10 @@ import { MatIconModule } from '@angular/material/icon';
|
||||
templateUrl: './file-dropzone.html',
|
||||
})
|
||||
export class FileDropzone {
|
||||
@Input() accept: string[] = ['xlsx', 'csv', 'json', 'pdf'];
|
||||
@Input() multiple = true;
|
||||
@Output() readonly filesChange = new EventEmitter<File[]>();
|
||||
readonly accept = input.required<string[]>();
|
||||
readonly multiple = input(true);
|
||||
readonly keepSelection = input(true);
|
||||
readonly filesChange = output<File[]>();
|
||||
|
||||
readonly files = signal<File[]>([]);
|
||||
readonly fileMessages = signal<string[]>([]);
|
||||
@@ -21,15 +26,15 @@ export class FileDropzone {
|
||||
private dragDepth = 0;
|
||||
|
||||
get allowedExtensions(): Set<string> {
|
||||
return new Set(this.accept.map((extension) => extension.toLowerCase()));
|
||||
return new Set(this.accept().map((extension) => extension.toLowerCase()));
|
||||
}
|
||||
|
||||
get acceptAttribute(): string {
|
||||
return this.accept.map((extension) => `.${extension}`).join(',');
|
||||
return this.accept().map((extension) => `.${extension}`).join(',');
|
||||
}
|
||||
|
||||
get formatsLabel(): string {
|
||||
return this.accept.map((extension) => extension.toUpperCase()).join(' · ');
|
||||
return this.accept().map((extension) => extension.toUpperCase()).join(' · ');
|
||||
}
|
||||
|
||||
onFileSelection(event: Event): void {
|
||||
@@ -88,7 +93,8 @@ export class FileDropzone {
|
||||
|
||||
private addFiles(incomingFiles: File[]): void {
|
||||
const messages: string[] = [];
|
||||
const accepted = this.multiple ? [...this.files()] : [];
|
||||
const kept = this.keepSelection() && this.multiple() ? [...this.files()] : [];
|
||||
const accepted = [...kept];
|
||||
|
||||
for (const file of incomingFiles) {
|
||||
const extension = this.extensionOf(file.name);
|
||||
@@ -104,16 +110,20 @@ export class FileDropzone {
|
||||
messages.push(`${file.name} ya se encuentra seleccionado.`);
|
||||
continue;
|
||||
}
|
||||
if (!this.multiple) {
|
||||
if (!this.multiple()) {
|
||||
accepted.length = 0;
|
||||
}
|
||||
accepted.push(file);
|
||||
if (!this.multiple) break;
|
||||
if (!this.multiple()) break;
|
||||
}
|
||||
|
||||
this.files.set(accepted);
|
||||
this.fileMessages.set(messages);
|
||||
this.filesChange.emit(accepted);
|
||||
if (this.keepSelection()) {
|
||||
this.files.set(accepted);
|
||||
this.filesChange.emit(accepted);
|
||||
} else if (accepted.length > kept.length) {
|
||||
this.filesChange.emit(accepted.slice(kept.length));
|
||||
}
|
||||
}
|
||||
|
||||
private extensionOf(fileName: string): string {
|
||||
|
||||
@@ -52,7 +52,7 @@
|
||||
<ng-container matColumnDef="outcome">
|
||||
<th mat-header-cell *matHeaderCellDef>Resultado</th>
|
||||
<td mat-cell *matCellDef="let flow">
|
||||
@if (resultOf(flow); as result) {
|
||||
@if (flow.result(); as result) {
|
||||
+{{ result.created }} · ↻{{ result.updated }} · ✕{{ result.rejected }}@if (result.merged) { · ⧉{{ result.merged }} }
|
||||
} @else {
|
||||
—
|
||||
|
||||
@@ -37,12 +37,7 @@ export class LoadDialog implements OnInit {
|
||||
/** With merging, rows incomplete on their own may be completed by another source. */
|
||||
readonly canLoad = computed(() => this.totals().valid > 0 || (this.store.mergeDuplicates() && this.totals().rows > 0));
|
||||
|
||||
/**
|
||||
* The flows the next batch would write. Reactive to the merge checkbox
|
||||
* while nothing has loaded yet, so ticking it reveals the flow it
|
||||
* completes; frozen the moment a batch starts, so the results table
|
||||
* keeps listing exactly what was sent.
|
||||
*/
|
||||
/** The flows the next batch writes; frozen once it starts so the results match what was sent. */
|
||||
private readonly _frozenFlows = signal<ImportFlow[] | null>(null);
|
||||
readonly flows = computed(() => this._frozenFlows() ?? this.store.submittableFlows());
|
||||
readonly skipped = computed(() => this.store.flows().filter((flow) => !this.flows().includes(flow) && !flow.canSubmit));
|
||||
@@ -85,7 +80,7 @@ export class LoadDialog implements OnInit {
|
||||
this.store.setOnConflict(strategy);
|
||||
}
|
||||
|
||||
/** Toggling may bring an until-now-skipped flow into `flows()`; preview its rows too. */
|
||||
/** Merging can add flows to the batch; validate them so their rows show up in the preview. */
|
||||
toggleMerge(merge: boolean): void {
|
||||
this.store.setMergeDuplicates(merge);
|
||||
Promise.all(this.flows().filter((flow) => !flow.validation()).map((flow) => this.store.validate(flow)));
|
||||
@@ -99,8 +94,4 @@ export class LoadDialog implements OnInit {
|
||||
explore(): void {
|
||||
this.dialogRef.close('explore');
|
||||
}
|
||||
|
||||
resultOf(flow: ImportFlow) {
|
||||
return flow.result();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,9 @@ import { FileConnection } from './file-source';
|
||||
import { PdfConnection } from './pdf-source';
|
||||
|
||||
/** Turns the files chosen for one source kind into workspace connections. */
|
||||
export type ConnectionFactory = (files: File[]) => DataConnection[];
|
||||
type ConnectionFactory = (files: File[]) => DataConnection[];
|
||||
|
||||
// Adding a file source on the client is one `DataConnection` subclass and one entry here.
|
||||
const FACTORIES = new Map<SourceType, ConnectionFactory>([
|
||||
['csv', (files) => files.map((file) => new FileConnection(file, 'csv'))],
|
||||
['excel', (files) => files.map((file) => new FileConnection(file, 'excel'))],
|
||||
@@ -18,11 +19,6 @@ const FACTORIES = new Map<SourceType, ConnectionFactory>([
|
||||
['document', (files) => [new DocumentConnection(files)]],
|
||||
]);
|
||||
|
||||
/** Adding a file source on the client is one `DataConnection` subclass and one call here. */
|
||||
export function registerConnectionFactory(kind: SourceType, factory: ConnectionFactory): void {
|
||||
FACTORIES.set(kind, factory);
|
||||
}
|
||||
|
||||
export function connectionsFor(kind: SourceType, files: File[]): DataConnection[] {
|
||||
const factory = FACTORIES.get(kind);
|
||||
return factory && files.length ? factory(files) : [];
|
||||
|
||||
@@ -134,12 +134,7 @@ export class ImportFlow {
|
||||
return !['loading', 'error', 'incomplete'].includes(this.status());
|
||||
}
|
||||
|
||||
/**
|
||||
* Belongs in the next load: complete and not already written. A loaded
|
||||
* flow stays out of later batches (re-sending it would duplicate rows in
|
||||
* tables without a natural key) until it's edited, since any edit clears
|
||||
* its result.
|
||||
*/
|
||||
/** Complete and not yet written; editing a loaded flow clears its result and makes it pending again. */
|
||||
get pendingLoad(): boolean {
|
||||
return this.canSubmit && this.status() !== 'loaded';
|
||||
}
|
||||
@@ -162,7 +157,7 @@ export class ImportFlow {
|
||||
);
|
||||
}
|
||||
|
||||
// -- mapping edits (every one invalidates the last validation) -----------
|
||||
// Every mapping edit invalidates the last validation.
|
||||
|
||||
map(source: string, field: string): void {
|
||||
this.mapping.assign(source, field);
|
||||
@@ -210,7 +205,6 @@ export class ImportFlow {
|
||||
return Object.fromEntries(Object.entries(this._defaults()).filter(([, value]) => value.trim() !== ''));
|
||||
}
|
||||
|
||||
// -- backend round trips ---------------------------------------------------
|
||||
|
||||
async toPayload(): Promise<ImportSourcePayload> {
|
||||
const locator = await this.table.locator(this.target.key);
|
||||
|
||||
@@ -52,7 +52,6 @@ const SQL_DIALECT_LABELS: Record<string, string> = {
|
||||
mariadb: 'MariaDB',
|
||||
postgresql: 'PostgreSQL',
|
||||
mssql: 'SQL Server',
|
||||
oracle: 'Oracle',
|
||||
sqlite: 'SQLite',
|
||||
};
|
||||
|
||||
|
||||
@@ -75,12 +75,7 @@ export class ConnectWorkspaceStore {
|
||||
/** A batch writes to one domain's database, so the domain can only change while there are no flows. */
|
||||
readonly domainLocked = computed(() => this._flows().length > 0);
|
||||
|
||||
/**
|
||||
* Flows with a known target and a natural key, not still loading/erroring
|
||||
* and not already written — candidates to combine by `mergeDuplicates`,
|
||||
* complete or not (a source missing a required field may still supply
|
||||
* others a sibling source lacks).
|
||||
*/
|
||||
/** Unwritten flows into a keyed target: what `mergeDuplicates` may combine, complete or not. */
|
||||
private readonly mergeCandidateFlows = computed(() =>
|
||||
this._flows().filter((flow) => !!flow.target.conflict_fields && !['loading', 'error', 'loaded'].includes(flow.status())),
|
||||
);
|
||||
@@ -97,13 +92,7 @@ export class ConnectWorkspaceStore {
|
||||
return new Set([...counts].filter(([, count]) => count > 1).map(([key]) => key));
|
||||
});
|
||||
|
||||
/**
|
||||
* Flows the next batch will write. Normally just the complete ones; with
|
||||
* `mergeDuplicates` on, a flow missing a required field joins them too
|
||||
* when another flow targets the same keyed entity — the gap may be
|
||||
* exactly what that other source supplies, so the batch combines them
|
||||
* before validating instead of dropping the incomplete one silently.
|
||||
*/
|
||||
/** Flows the next batch writes: the complete ones, plus incomplete ones another flow may complete when merging. */
|
||||
readonly submittableFlows = computed(() => {
|
||||
const complete = this._flows().filter((flow) => flow.pendingLoad);
|
||||
if (!this._mergeDuplicates()) return complete;
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
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;
|
||||
// Filters a list announces in `filtros_disponibles`, by key.
|
||||
filtros?: Record<string, string>; }
|
||||
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 SeguimientoPaciente {
|
||||
id_seudonimo: string;
|
||||
|
||||
@@ -91,6 +91,13 @@ 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();
|
||||
open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull();
|
||||
});
|
||||
it.each(['cama'])('%s conserva su estado pendiente sin consultas de pacientes', dominio => {
|
||||
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', () => {
|
||||
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();
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -15,18 +15,15 @@ import { filterCompatibility } from './indicadores-memory';
|
||||
import { DonutSelection } from './indicadores-donut-drilldown';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
|
||||
import { vistaEscenario } from './indicadores-eu7-escenario';
|
||||
import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
|
||||
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
|
||||
import { vistaConfirmacion } from './indicadores-confirmacion-citologia';
|
||||
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
|
||||
import { parTiempos } from './indicadores-tiempos-pareados';
|
||||
import { parConteos } from './indicadores-conteos-pareados';
|
||||
import { IndicadorConteosPareados } from './indicador-conteos-pareados';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-catalog-card',
|
||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || !!tiempos || !!conteos' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorConteosPareados],
|
||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || !!tiempos' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia],
|
||||
template: `
|
||||
<mat-card>
|
||||
<header>
|
||||
@@ -49,10 +46,6 @@ import { IndicadorConteosPareados } from './indicador-conteos-pareados';
|
||||
<div #visibilityRegion class="confirmacion-region">
|
||||
<app-indicador-confirmacion-citologia [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
</div>
|
||||
} @else if (conteos; as par) {
|
||||
<div #visibilityRegion class="conteos-region">
|
||||
<app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
</div>
|
||||
} @else if (tiempos; as par) {
|
||||
<div #visibilityRegion class="tiempos-region">
|
||||
<app-indicador-tiempos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
@@ -98,7 +91,7 @@ import { IndicadorConteosPareados } from './indicador-conteos-pareados';
|
||||
}
|
||||
.card-identity { min-width: 0; }
|
||||
h2, p { overflow-wrap: anywhere; }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 700; font-size: 1.5rem; line-height: 1.25; }
|
||||
.pin-toggle { align-self: start; margin-top: var(--issste-space-1); max-width: 100%; height: auto;
|
||||
min-width: 48px; min-height: 48px; color: var(--issste-text); }
|
||||
.pin-toggle mat-icon { flex-shrink: 0; }
|
||||
@@ -127,12 +120,10 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
});
|
||||
}
|
||||
get pair() { return dualFigures(this.indicador); }
|
||||
get isEu7() { return !!vistaEscenario(this.dominio, this.indicador); }
|
||||
get isConfirmacion() { return !!vistaConfirmacion(this.dominio, this.indicador); }
|
||||
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
|
||||
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
|
||||
// Connected time pairs replace the diagnosis card with one coordinated box plot.
|
||||
get tiempos() { return parTiempos(this.dominio, this.indicador.id); }
|
||||
// Exams and patients of the same finding, drawn together on the exams' card.
|
||||
get conteos() { return parConteos(this.dominio, this.indicador.id); }
|
||||
get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
|
||||
get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; }
|
||||
private updateNumeric() {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<section class="confirmacion" [attr.aria-label]="'Confirmación histopatológica, ' + vista.textos.filas.toLowerCase()">
|
||||
<section class="confirmacion" aria-label="Confirmación histopatológica por resultado de la citología">
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||
@if (helpOpen) {
|
||||
@@ -16,7 +16,7 @@
|
||||
}
|
||||
@switch (status()) {
|
||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando citologías y biopsias" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
|
||||
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@@ -30,13 +30,9 @@
|
||||
}
|
||||
@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">{{ vista.textos.vacio }}</p> }
|
||||
@if (status() === 'empty') { <p role="status">No hay citologías de alto grado publicadas para este periodo.</p> }
|
||||
@else {
|
||||
@if (!vista.botones) {
|
||||
<p class="hint">Haz clic en un anillo de la dona para elegir un grupo o un resultado; el centro regresa un paso, hasta el total.</p>
|
||||
}
|
||||
<!-- Without visible buttons they stay for the keyboard, shown while one has the focus. -->
|
||||
<div class="legend" [class.solo-teclado]="!vista.botones" role="group" aria-label="Seleccionar resultado de biopsia">
|
||||
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
|
||||
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista base de la confirmación">Volver</button>
|
||||
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
||||
@for (g of m.grupos; track g.id; let i = $index) {
|
||||
@@ -50,9 +46,9 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="figures">
|
||||
<section class="figure rates"><h3>{{ vista.textos.filas }}, {{ m.periodo }}</h3>
|
||||
<section class="figure rates"><h3>Por resultado de la citología, {{ m.periodo }}</h3>
|
||||
@if (ratesFigure) {
|
||||
<app-plotly-chart [figure]="ratesFigure" [animated]="!vista.botones" [showNotes]="false" [label]="'Confirmación, tasas ' + vista.textos.filas.toLowerCase() + ', ' + m.periodo + ', ' + selectionLabel" />
|
||||
<app-plotly-chart [figure]="ratesFigure" [showNotes]="false" [label]="'Confirmación, tasas por citología, ' + 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> } }
|
||||
@@ -60,16 +56,16 @@
|
||||
</section>
|
||||
<section class="figure donut"><h3>Resultado de la biopsia, {{ m.periodo }}</h3>
|
||||
@if (m.conBiopsia !== null && m.conBiopsia > 0 && donutFigure) {
|
||||
<app-plotly-chart [figure]="donutFigure" [animated]="!vista.botones" [showNotes]="false" [label]="'Confirmación, dona de grados de biopsia, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
||||
} @else { <p role="status">{{ m.conBiopsia === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin ' + vista.textos.sujetos + ' con biopsia en el periodo.' }}</p> }
|
||||
<app-plotly-chart [figure]="donutFigure" [showNotes]="false" [label]="'Confirmación, dona de grados de biopsia, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
||||
} @else { <p role="status">{{ m.conBiopsia === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin mujeres con biopsia en el periodo.' }}</p> }
|
||||
</section>
|
||||
</div>
|
||||
}
|
||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de contingencia, ' + indicador.titulo" tabindex="0">
|
||||
<table><caption>Tabla de contingencia de {{ vista.textos.sujetos }}, {{ m.periodo }}</caption>
|
||||
<thead><tr><th scope="col">{{ vista.textos.encabezado }}</th>@for (g of m.grados; track g.id) { <th scope="col">{{ g.etiqueta }}</th> }<th scope="col">Con biopsia</th>@for (a of m.aparte; track a.id) { <th scope="col">{{ a.etiqueta }}</th> }</tr></thead>
|
||||
<div class="table-scroll" role="region" aria-label="Tabla de contingencia de citología y biopsia" tabindex="0">
|
||||
<table><caption>Tabla de contingencia de mujeres, {{ m.periodo }}</caption>
|
||||
<thead><tr><th scope="col">Citología</th>@for (g of m.grados; track g.id) { <th scope="col">{{ g.etiqueta }}</th> }<th scope="col">Con biopsia</th>@for (a of m.aparte; track a.id) { <th scope="col">{{ a.etiqueta }}</th> }</tr></thead>
|
||||
<tbody>@for (fila of m.filas; track fila.id) {
|
||||
<tr><th scope="row">{{ fila.etiqueta }}</th>@for (g of m.grados; track g.id) { <td>{{ cellText(fila.celdas[g.id]) }}</td> }<td>{{ denText(fila.den, fila.estado) }}</td>@for (a of m.aparte; track a.id) { <td>{{ cellText(fila.aparte[a.id]) }}</td> }</tr>
|
||||
}</tbody>
|
||||
|
||||
@@ -7,12 +7,8 @@ p, h3, summary { overflow-wrap: anywhere; }
|
||||
.legend { display: grid; gap: .6rem; margin-block: 1rem; }
|
||||
.keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
.legend > button { justify-self: start; }
|
||||
.hint { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
.legend.solo-teclado:not(:focus-within) { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||
// The donut is the control: its slices and centre answer to the pointer.
|
||||
.donut app-plotly-chart { cursor: pointer; }
|
||||
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
|
||||
border-radius: var(--issste-radius); color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
|
||||
border-radius: 999px; color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
|
||||
.keys button { display: inline-flex; align-items: center; gap: .4rem; text-align: start; overflow-wrap: anywhere; }
|
||||
button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
|
||||
button:disabled { opacity: .5; cursor: default; }
|
||||
|
||||
@@ -8,9 +8,12 @@ import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './in
|
||||
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { clicConfirmacion, clicDona, ConfirmacionIncompatible, CONFIRMACION_CACU, donaConfirmacion, donaExpandible, estadoTasa, figuraTasas,
|
||||
import { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, ESTRATO_CITOLOGIA, estadoTasa, figuraTasas, ID_CONFIRMACION,
|
||||
lectura, ModeloConfirmacion, modeloConfirmacion, periodosConfirmacion, SeleccionConfirmacion, seleccionBase, seleccionEtiqueta,
|
||||
Celda, Tasa, tasas, vistaConfirmacion } from './indicadores-confirmacion-citologia';
|
||||
Celda, tasas } from './indicadores-confirmacion-citologia';
|
||||
|
||||
// Figures of the kit whose "Cómo leer" describes this coordinated view.
|
||||
const FIGURAS = [['fig_c2_donas', 'Dona de grados de biopsia'], ['fig_c2_barras', 'Tasas por resultado de la citología']] as const;
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-confirmacion-citologia',
|
||||
@@ -45,18 +48,14 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
||||
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
||||
get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; }
|
||||
get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; }
|
||||
get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === (this.vista.botones ? this.model.base : undefined); }
|
||||
get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; }
|
||||
get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; }
|
||||
// CaCu's words when the catalog doesn't name this indicator, so the messages still read.
|
||||
get vista() { return vistaConfirmacion(this.dominio, this.indicador) ?? CONFIRMACION_CACU; }
|
||||
estadoTasa(t: Tasa) { return estadoTasa(t, this.vista.textos.sujetos); }
|
||||
readonly estadoTasa = estadoTasa;
|
||||
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
|
||||
denText(den: number | null, estado: string) { return den === null ? estado : den.toLocaleString('es-MX'); }
|
||||
get readingGuide() {
|
||||
const details = this.metadata?.figuras_detalle ?? [];
|
||||
// Figures of the kit whose "Cómo leer" describes this coordinated view.
|
||||
const figuras = [['fig_c2_donas', 'Dona de resultados de biopsia'], ['fig_c2_barras', 'Tasas ' + this.vista.textos.filas.toLowerCase()]] as const;
|
||||
return figuras.flatMap(([figura, nombre]) => {
|
||||
return FIGURAS.flatMap(([figura, nombre]) => {
|
||||
const detail = details.find(item => item.figura === figura);
|
||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||
@@ -66,7 +65,7 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
||||
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: this.vista.estrato })
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_CITOLOGIA })
|
||||
+ JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras]);
|
||||
if (key !== this.key) {
|
||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
|
||||
@@ -85,8 +84,7 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
||||
this.subscription?.unsubscribe();
|
||||
this.loaded = true; this.clear();
|
||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||
const vista = vistaConfirmacion(this.dominio, this.indicador);
|
||||
if (!vista || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
|
||||
if (this.dominio !== 'cacu' || this.indicador.id !== ID_CONFIRMACION || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
|
||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.';
|
||||
this.status.set('incompatible'); return;
|
||||
}
|
||||
@@ -94,12 +92,12 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
||||
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
|
||||
this.status.set('loading');
|
||||
this.subscription = this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version,
|
||||
{ estrato: vista.estrato }).pipe(timeout({ first: 40000 })).subscribe({
|
||||
{ estrato: ESTRATO_CITOLOGIA }).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: datos => {
|
||||
if (key !== this.key) return;
|
||||
try {
|
||||
this.periods = periodosConfirmacion(datos, this.applied.tipo, periods, vista);
|
||||
this.pages = this.periods.map(p => modeloConfirmacion(datos, p, vista));
|
||||
this.periods = periodosConfirmacion(datos, this.applied.tipo, periods);
|
||||
this.pages = this.periods.map(p => modeloConfirmacion(datos, p));
|
||||
// The most recent period first, as the prototype; navigation goes back.
|
||||
this.periodIndex = Math.max(0, this.periods.length - 1); this.activatePeriod();
|
||||
} catch (error) { this.failure(error); }
|
||||
@@ -117,8 +115,7 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
||||
}
|
||||
private activatePeriod() {
|
||||
this.model = this.pages[this.periodIndex];
|
||||
// With buttons the view opens on the base group; without, on the total, as CaCu's interactive donut.
|
||||
this.selection = this.model ? (this.vista.botones ? seleccionBase(this.model) : {}) : undefined;
|
||||
this.selection = this.model ? seleccionBase(this.model) : undefined;
|
||||
this.draw(); this.status.set(this.model && !this.model.vacio ? 'ready' : 'empty');
|
||||
}
|
||||
changePeriod(step: number) {
|
||||
@@ -127,7 +124,7 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
||||
}
|
||||
select(trace: string, index = 0) {
|
||||
if (!this.model || !this.selection || this.status() !== 'ready') return;
|
||||
this.selection = (this.vista.botones ? clicConfirmacion : clicDona)(this.model, this.selection, trace, index); this.draw();
|
||||
this.selection = clicConfirmacion(this.model, this.selection, trace, index); this.draw();
|
||||
}
|
||||
plotClicked(event: unknown) {
|
||||
const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0];
|
||||
@@ -135,7 +132,7 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
||||
}
|
||||
private draw() {
|
||||
if (!this.model || !this.selection) return;
|
||||
this.donutFigure = (this.vista.botones ? donaConfirmacion : donaExpandible)(this.model, this.selection, this.tema);
|
||||
this.donutFigure = donaConfirmacion(this.model, this.selection, this.tema);
|
||||
this.ratesFigure = figuraTasas(this.model, this.selection, this.tema);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
<section class="conteos" [attr.aria-label]="indicador.titulo + ', por ' + par.unidades.pacientes.slice(0, -1) + ' y por ' + par.unidades.examenes.slice(0, -1)">
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||
@if (helpOpen) {
|
||||
<div class="methodology">
|
||||
@if (metadata) {
|
||||
@for (guide of readingGuide; track guide.figura) {
|
||||
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
|
||||
<h3>{{ guide.nombre }}</h3>
|
||||
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
|
||||
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
|
||||
</section>
|
||||
} @empty { <p>El servicio no publica instrucciones de lectura para estas figuras.</p> }
|
||||
} @else { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
|
||||
</div>
|
||||
}
|
||||
@switch (status()) {
|
||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando {{ par.unidades.examenes }} y {{ par.unidades.pacientes }} del mismo periodo…</p> }
|
||||
@case ('empty') { <p role="status">No hay periodos publicados por los dos conteos.</p> }
|
||||
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@if (status() === 'ready' && model; as m) {
|
||||
@if (pages.length > 1) {
|
||||
<nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo">
|
||||
<button type="button" aria-label="Periodo anterior" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||
<span role="status">{{ m.periodo }}, {{ periodIndex + 1 }} de {{ pages.length }}</span>
|
||||
<button type="button" aria-label="Periodo siguiente" [disabled]="periodIndex === pages.length - 1" (click)="changePeriod(1)">›</button>
|
||||
</nav>
|
||||
}
|
||||
<div class="figures">
|
||||
<section class="figure"><h3>{{ par.unidades.examenes | titlecase }} por categoría, {{ m.periodo }}</h3>
|
||||
@if (total) {
|
||||
<app-plotly-chart [figure]="donutFigure!" [showNotes]="false" [label]="indicador.titulo + ', dona, ' + m.periodo" />
|
||||
} @else { <p role="status">{{ total === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.examenes + ' en el periodo.' }}</p> }
|
||||
@if (m.sinDato) { <p class="note">Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.</p> }
|
||||
</section>
|
||||
<section class="figure"><h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}, {{ m.periodo }}</h3>
|
||||
<app-plotly-chart [figure]="barsFigure!" [showNotes]="false" [label]="indicador.titulo + ', barras por ' + par.unidades.pacientes.slice(0, -1) + ', ' + m.periodo" />
|
||||
</section>
|
||||
</div>
|
||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0">
|
||||
<table><caption>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}, {{ m.periodo }}</caption>
|
||||
<thead><tr><th scope="col">Categoría</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>{{ texto(f.pacientes) }}</td><td>{{ texto(f.examenes) }}</td></tr> }</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
</section>
|
||||
@@ -1,22 +0,0 @@
|
||||
:host { display: block; min-width: 0; }
|
||||
.conteos { min-width: 0; padding-top: var(--issste-space-3); }
|
||||
p, h3, summary { overflow-wrap: anywhere; }
|
||||
.applied-summary, .note { color: var(--issste-text-secondary); }
|
||||
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.reading-guide h3 { margin: 0 0 .25rem; }
|
||||
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
|
||||
h3 { font-size: 1rem; font-weight: 500; line-height: 1.5; }
|
||||
.periods { display: flex; align-items: center; gap: var(--issste-space-3); }
|
||||
.periods button { min-width: 44px; min-height: 44px; font-size: 1.25rem; color: var(--issste-text); background: var(--issste-surface);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); cursor: pointer; }
|
||||
.periods button:disabled { opacity: .5; cursor: default; }
|
||||
// The two figures share the card in equal halves; one above the other on a narrow card.
|
||||
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||
@media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
app-plotly-chart { --plot-height: 400px; }
|
||||
summary { cursor: pointer; padding-block: .75rem; }
|
||||
summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.table-scroll { overflow: auto; }
|
||||
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||
caption { text-align: start; font-weight: 600; }
|
||||
@@ -1,117 +0,0 @@
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { TitleCasePipe } from '@angular/common';
|
||||
import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { barrasConteos, ConteosIncompatibles, donaConteos, ModeloConteos, modelosConteos, ParConteos, totalExamenes } from './indicadores-conteos-pareados';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-conteos-pareados',
|
||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart, TitleCasePipe],
|
||||
templateUrl: './indicador-conteos-pareados.html',
|
||||
styleUrl: './indicador-conteos-pareados.scss',
|
||||
})
|
||||
export class IndicadorConteosPareados implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) par!: ParConteos;
|
||||
// The card's indicator (the exams); its partner (the patients) has no card and is requested by id.
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() visible = true;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
readonly metadataRequested = output<void>();
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
message = '';
|
||||
periodIndex = 0;
|
||||
pages: ModeloConteos[] = [];
|
||||
donutFigure?: PlotlyFigure;
|
||||
barsFigure?: PlotlyFigure;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private subscription?: Subscription;
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
|
||||
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
||||
get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; }
|
||||
get total() { return this.model ? totalExamenes(this.model) : null; }
|
||||
texto(n: number | null) { return n === null ? 'Sin dato' : n.toLocaleString('es-MX'); }
|
||||
helpOpen = false;
|
||||
// "Cómo leer": what the kit publishes for the exams' two figures.
|
||||
get readingGuide() {
|
||||
const figuras = [['fig_c2_donas', 'Dona por categoría'], ['fig_c2_barras', 'Pacientes y ' + this.par.unidades.examenes]] as const;
|
||||
return figuras.flatMap(([figura, nombre]) => {
|
||||
const detail = this.metadata?.figuras_detalle?.find(item => item.figura === figura);
|
||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
|
||||
});
|
||||
}
|
||||
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([this.par.examenes, this.par.pacientes, this.indicador.tipos_periodo]);
|
||||
if (key !== this.key) {
|
||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false; this.clear();
|
||||
if (!this.visible) { this.status.set('deferred'); return; }
|
||||
this.load();
|
||||
} else if (this.visible && !this.loaded) this.load();
|
||||
else if (this.model && changes['tema']) this.draw();
|
||||
}
|
||||
retry() { if (this.visible) this.load(); }
|
||||
private clear() { this.pages = []; this.periodIndex = 0; this.donutFigure = undefined; this.barsFigure = undefined; }
|
||||
private load() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.loaded = true; this.clear();
|
||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||
if (this.indicador.id !== this.par.examenes || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
|
||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica el conteo necesario para esta vista.';
|
||||
this.status.set('incompatible'); return;
|
||||
}
|
||||
const key = this.key;
|
||||
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
|
||||
this.status.set('loading');
|
||||
this.subscription = combineLatest([
|
||||
this.snapshots.datos(this.dominio, this.par.examenes, this.applied.tipo, periods, this.indicador.version),
|
||||
this.snapshots.datos(this.dominio, this.par.pacientes, this.applied.tipo, periods),
|
||||
]).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: ([examenes, pacientes]) => {
|
||||
if (key !== this.key) return;
|
||||
try {
|
||||
this.pages = modelosConteos(this.par, examenes, pacientes, this.applied.tipo);
|
||||
// The most recent period first; navigation goes back.
|
||||
this.periodIndex = Math.max(0, this.pages.length - 1);
|
||||
this.draw(); this.status.set(this.model ? 'ready' : 'empty');
|
||||
} catch (error) { this.failure(error); }
|
||||
},
|
||||
error: error => { if (key === this.key) this.failure(error); },
|
||||
});
|
||||
}
|
||||
private failure(error: unknown) {
|
||||
this.clear();
|
||||
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
||||
: error instanceof ConteosIncompatibles ? error.message : httpMessage(error);
|
||||
this.status.set(error instanceof ConteosIncompatibles || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
|
||||
? 'incompatible' : 'error');
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
changePeriod(step: number) {
|
||||
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
|
||||
this.periodIndex += step; this.draw();
|
||||
}
|
||||
private draw() {
|
||||
const m = this.model;
|
||||
if (!m) return;
|
||||
this.donutFigure = donaConteos(m, this.par, this.tema);
|
||||
this.barsFigure = barrasConteos(m, this.par, this.tema);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
<section class="eu7" [attr.aria-label]="indicador.titulo + ' por ' + etiquetaEstrato">
|
||||
<section class="eu7" aria-label="Resultados citológicos por escenario clínico">
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||
@if (helpOpen) {
|
||||
@@ -16,24 +16,24 @@
|
||||
}
|
||||
@switch (status()) {
|
||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando el mismo periodo para dona y barras…</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando resultados citológicos y escenarios" /><p role="status">Cargando el mismo periodo para dona y barras…</p> }
|
||||
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@if (status() === 'ready' || status() === 'empty') {
|
||||
@if (periods.length > 1) {
|
||||
<nav class="periods" [attr.aria-label]="'Periodos de dona y barras, ' + indicador.titulo">
|
||||
<button type="button" aria-label="Periodo anterior" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||
<nav class="periods" aria-label="Periodos de dona y barras EU7">
|
||||
<button type="button" aria-label="Periodo anterior de EU7" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||
<span role="status">{{ periods[periodIndex] }}, {{ periodIndex + 1 }} de {{ periods.length }}</span>
|
||||
<button type="button" aria-label="Periodo siguiente" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
|
||||
<button type="button" aria-label="Periodo siguiente de EU7" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
|
||||
</nav>
|
||||
}
|
||||
@if (model; as m) {
|
||||
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}</p>
|
||||
@if (status() === 'empty') { <p role="status">No hay pacientes publicados para este periodo.</p> }
|
||||
@else {
|
||||
<div class="legend" role="group" [attr.aria-label]="'Explorar grupos y categorías, ' + indicador.titulo">
|
||||
<button type="button" (click)="select('centro')" [disabled]="!selection.grupo && !selection.categoria" aria-label="Volver en la selección">Volver</button>
|
||||
<div class="legend" role="group" aria-label="Explorar grupos y categorías de EU7">
|
||||
<button type="button" (click)="select('centro')" [disabled]="!selection.grupo && !selection.categoria" aria-label="Volver en la selección de EU7">Volver</button>
|
||||
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
||||
@for (g of m.grupos; track g.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="selection.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||
@@ -48,27 +48,27 @@
|
||||
<div class="figures">
|
||||
<section class="figure"><h3>Distribución de resultados, {{ m.periodo }}</h3>
|
||||
@if (m.total !== null && m.total > 0 && donutFigure) {
|
||||
<app-plotly-chart [figure]="donutFigure" [animated]="true" [showNotes]="false" [label]="indicador.titulo + ', dona de dos anillos, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
||||
<app-plotly-chart [figure]="donutFigure" [animated]="true" [showNotes]="false" [label]="'EU7, dona de dos anillos, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
||||
} @else { <p role="status">{{ m.total === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado disponible para la dona.' }}</p> }
|
||||
<p>{{ sinDatoNote }}</p>
|
||||
</section>
|
||||
<section class="figure"><h3>{{ selectionLabel }} por {{ etiquetaEstrato }}, {{ m.periodo }}</h3>
|
||||
<p>Porcentaje del total válido de cada {{ etiquetaEstrato }}; excluye «{{ m.sinDatoEtiqueta }}».</p>
|
||||
<section class="figure"><h3>{{ selectionLabel }} por escenario clínico, {{ m.periodo }}</h3>
|
||||
<p>Porcentaje del total válido de cada escenario; excluye «Sin dato».</p>
|
||||
@if (m.escenarios.length && barsFigure) {
|
||||
<app-plotly-chart [figure]="barsFigure" [animated]="true" [showNotes]="false" [style.--plot-min-width]="'440px'" [label]="indicador.titulo + ', barras por ' + etiquetaEstrato + ', ' + m.periodo + ', ' + selectionLabel" />
|
||||
<app-plotly-chart [figure]="barsFigure" [animated]="true" [showNotes]="false" [style.--plot-min-width]="'440px'" [label]="'EU7, barras por escenario clínico, ' + m.periodo + ', ' + selectionLabel" />
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
}
|
||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0">
|
||||
<div class="table-scroll" role="region" aria-label="Tabla de valores EU7" tabindex="0">
|
||||
<table><caption>Datos generales, {{ m.periodo }}</caption>
|
||||
<thead><tr><th scope="col">Categoría</th><th scope="col">Conteo</th></tr></thead>
|
||||
<tbody>@for (row of generalCells; track $index) { <tr><th scope="row">{{ row.etiqueta }}</th><td>{{ cellText(row.celda) }}</td></tr> }</tbody>
|
||||
</table>
|
||||
<table><caption>Por {{ etiquetaEstrato }}, {{ m.periodo }}, porcentajes sin «{{ m.sinDatoEtiqueta }}»</caption>
|
||||
<thead><tr><th scope="col">{{ etiquetaEstrato.charAt(0).toUpperCase() + etiquetaEstrato.slice(1) }}</th><th scope="col">Categoría</th><th scope="col">Conteo</th><th scope="col">Denominador válido</th><th scope="col">Porcentaje</th></tr></thead>
|
||||
<table><caption>Escenarios clínicos, {{ m.periodo }}, porcentajes sin «Sin dato»</caption>
|
||||
<thead><tr><th scope="col">Escenario</th><th scope="col">Categoría</th><th scope="col">Conteo</th><th scope="col">Denominador válido</th><th scope="col">Porcentaje</th></tr></thead>
|
||||
<tbody>@for (row of scenarioCells; track $index) { <tr><th scope="row">{{ row.escenario }}</th><td>{{ row.categoria }}</td><td>{{ cellText(row.celda) }}</td><td>{{ row.den === null ? 'No disponible / no aplica' : row.den }}</td><td>{{ percentText(row.pct) }}</td></tr> }</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
@@ -8,7 +8,7 @@ p, h3, summary { overflow-wrap: anywhere; }
|
||||
.keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
.legend > button { justify-self: start; }
|
||||
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
|
||||
border-radius: var(--issste-radius); color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
|
||||
border-radius: 999px; color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
|
||||
.keys button { display: inline-flex; align-items: center; gap: .4rem; text-align: start; overflow-wrap: anywhere; }
|
||||
button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
|
||||
button:disabled { opacity: .5; cursor: default; }
|
||||
|
||||
@@ -126,7 +126,7 @@ describe('EU7 integración Angular y caché compartida', () => {
|
||||
f.detectChanges(); flush(); expect(f.nativeElement.textContent).toContain('Suprimido');
|
||||
expect(f.nativeElement.textContent).not.toContain('987654');
|
||||
expect(f.nativeElement.querySelector('table caption')).not.toBeNull();
|
||||
expect(f.nativeElement.querySelector('[aria-label="Tabla de valores, Distribución de resultados citológicos"]').tabIndex).toBe(0);
|
||||
expect(f.nativeElement.querySelector('[aria-label="Tabla de valores EU7"]').tabIndex).toBe(0);
|
||||
});
|
||||
it('catálogo sin capacidad temporal o clínica no inicia GET', () => {
|
||||
f.componentRef.setInput('indicador', { ...indicador, filtros: [] }); f.detectChanges();
|
||||
|
||||
@@ -4,14 +4,16 @@ import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema, VistaEscenario } from './indicadores.models';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { percentText } from './indicadores-format';
|
||||
import { stratifiedCapabilities } from './indicadores-stratified';
|
||||
import { barras, Celda, clic, dona, esEu7, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
|
||||
periodosCompatibles, Seleccion, seleccionEtiqueta, vistaEscenario } from './indicadores-eu7-escenario';
|
||||
import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
|
||||
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario';
|
||||
|
||||
const EU7_FIGURES = [['fig_c2_donas', 'Dona de dos anillos'], ['fig_c2_barras', 'Barras por escenario clínico']] as const;
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-eu7-escenario',
|
||||
@@ -42,8 +44,6 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
private pages: Modelo[] = [];
|
||||
get vista(): VistaEscenario | undefined { return vistaEscenario(this.dominio, this.indicador); }
|
||||
get etiquetaEstrato() { return this.vista?.etiqueta ?? 'escenario clínico'; }
|
||||
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
||||
get selectionLabel() { return this.model ? seleccionEtiqueta(this.model, this.selection) : 'TOTAL'; }
|
||||
get sinDatoNote() {
|
||||
@@ -51,8 +51,6 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
if (!m) return '';
|
||||
if (m.vacio) return 'No hay registros publicados en este periodo.';
|
||||
const n = m.sinDato.n;
|
||||
if (this.vista && !esEu7(this.vista)) return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la dona.`
|
||||
: `Fuera de la dona: ${n} pacientes con «${m.sinDatoEtiqueta}»${m.total === null ? '' : ` de ${m.total + n}`}.`;
|
||||
return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la dona.`
|
||||
: m.total === null ? `Fuera de la dona: ${n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte. Total de la dona no disponible.`
|
||||
: `Fuera de la dona: ${n} de ${m.total + n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte.`;
|
||||
@@ -71,8 +69,7 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
// "Cómo leer" shows only what the kit publishes for the two figures of this view.
|
||||
get readingGuide() {
|
||||
const details = this.metadata?.figuras_detalle ?? [];
|
||||
const figuras = [['fig_c2_donas', 'Dona de dos anillos'], ['fig_c2_barras', 'Barras por ' + this.etiquetaEstrato]] as const;
|
||||
return figuras.flatMap(([figura, nombre]) => {
|
||||
return EU7_FIGURES.flatMap(([figura, nombre]) => {
|
||||
const detail = details.find(item => item.figura === figura);
|
||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||
@@ -102,11 +99,10 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
this.loaded = true; this.model = undefined; this.pages = []; this.periods = [];
|
||||
this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined;
|
||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||
const vista = this.vista;
|
||||
if (!vista || this.indicador.contrato !== 'C2'
|
||||
if (this.dominio !== 'cacu' || this.indicador.id !== 'cacu_eu7' || this.indicador.contrato !== 'C2'
|
||||
|| !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras')
|
||||
|| !stratifiedCapabilities(this.indicador).includes(vista.estrato) || !compatibility.compatible) {
|
||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.';
|
||||
|| !stratifiedCapabilities(this.indicador).includes(ESTRATO) || !compatibility.compatible) {
|
||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista EU7.';
|
||||
this.status.set('incompatible'); return;
|
||||
}
|
||||
const key = this.key;
|
||||
@@ -114,13 +110,13 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
this.status.set('loading');
|
||||
this.subscription = combineLatest([
|
||||
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version),
|
||||
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version, { estrato: vista.estrato }),
|
||||
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version, { estrato: ESTRATO }),
|
||||
]).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: ([general, escenarios]) => {
|
||||
if (key !== this.key) return;
|
||||
try {
|
||||
this.periods = periodosCompatibles(general, escenarios, this.applied.tipo, periods);
|
||||
this.pages = this.periods.map(p => modelo(general, escenarios, p, vista.estrato));
|
||||
this.pages = this.periods.map(p => modelo(general, escenarios, p));
|
||||
this.periodIndex = 0; this.activatePeriod();
|
||||
} catch (error) { this.failure(error); }
|
||||
},
|
||||
@@ -155,7 +151,7 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
private draw() {
|
||||
if (!this.model) return;
|
||||
this.donutFigure = dona(this.model, this.selection, this.tema);
|
||||
this.barsFigure = barras(this.model, this.selection, this.tema, `% de pacientes de cada ${this.etiquetaEstrato}`);
|
||||
this.barsFigure = barras(this.model, this.selection, this.tema);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||
|
||||
@@ -120,7 +120,7 @@
|
||||
.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: var(--issste-radius); font: inherit; cursor: pointer; }
|
||||
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; }
|
||||
|
||||
@@ -15,6 +15,7 @@ import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
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 { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
|
||||
import { c2GeneralSelection } from './indicadores-c2-general-selection';
|
||||
@@ -104,7 +105,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
.distribution-toggle, .distribution-dimensions { display: flex; flex-wrap: wrap; gap: .5rem; margin-top: .5rem; }
|
||||
.distribution-dimensions { margin-top: .75rem; }
|
||||
.distribution-toggle button, .distribution-dimensions button { min-height: 44px; max-width: 100%; padding: .65rem .9rem;
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); color: var(--issste-text);
|
||||
border: 1px solid var(--issste-border); border-radius: 999px; background: var(--issste-surface); color: var(--issste-text);
|
||||
font: inherit; text-align: start; overflow-wrap: anywhere; cursor: pointer; }
|
||||
.distribution-toggle button.active, .distribution-dimensions button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; }
|
||||
.distribution-toggle button:disabled, .distribution-dimensions button:disabled { opacity: .5; cursor: not-allowed; }
|
||||
@@ -258,6 +259,15 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
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) {
|
||||
// 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.
|
||||
|
||||
@@ -13,21 +13,20 @@ import { MatCardModule } from '@angular/material/card';
|
||||
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
|
||||
}
|
||||
@if (temporalReference) { <p>{{ temporalReference }}</p> }
|
||||
<!-- A card with its value says nothing more about its state; any other state is the message. -->
|
||||
@if (state !== 'Disponible') { <p class="kpi-state" role="status">{{ state }}</p> }
|
||||
<p class="kpi-state" role="status">{{ state }}</p>
|
||||
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
|
||||
</mat-card>
|
||||
`,
|
||||
styles: `
|
||||
:host { display: flex; flex-direction: column; min-width: 0; }
|
||||
mat-card { box-sizing: border-box; flex: 1 1 auto; padding: var(--issste-space-6);
|
||||
:host { display: block; min-width: 0; }
|
||||
mat-card { box-sizing: border-box; height: 100%; padding: var(--issste-space-6);
|
||||
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border);
|
||||
border-radius: var(--issste-radius); box-shadow: none; }
|
||||
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: 1.25rem; line-height: 1.3; }
|
||||
h3, p { overflow-wrap: anywhere; }
|
||||
p { margin: var(--issste-space-3) 0 0; }
|
||||
.kpi-state, .additional-info { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
.value { font-size: 1.75rem; font-weight: 500; line-height: 1.2; }
|
||||
.value { font: var(--mat-sys-headline-medium); }
|
||||
.value span { margin-inline-start: .3em; }
|
||||
`,
|
||||
})
|
||||
|
||||
@@ -52,18 +52,6 @@ describe('KPI integración con autoridad global', () => {
|
||||
const d = KPI_BY_DOMAIN[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period], categorias: { A: {} }, filas: [
|
||||
{ periodo: period, grupo: d.contrato === 'C1' && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: 5, valor: 40, numerador: 2, denominador: 5, mediana: 7, q1: 3, q3: 9, unidad: 'dias', suprimido: 0 }] };
|
||||
}
|
||||
// Answers every card by its URL until none is waiting: a domain with more cards than the concurrent
|
||||
// requests gets them in batches.
|
||||
function flushAll(domain: Dominio, extra: Partial<IndicadorDatos> = {}) {
|
||||
for (let reqs = requests(); reqs.length; reqs = requests()) {
|
||||
// A flushed answer can cancel its siblings (a new anchor period); those are not answered.
|
||||
for (const r of reqs.filter(r => !r.cancelled)) {
|
||||
const index = KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.includes('/' + d.id + '/'));
|
||||
r.flush({ ...response(index, domain, r.request.params.get('periodos') ?? '2025-S1'), ...extra });
|
||||
}
|
||||
fixture.detectChanges();
|
||||
}
|
||||
}
|
||||
function apply(periods: string[], tipo: 'mes' | 'semestre' = 'semestre') {
|
||||
const state = fixture.componentInstance.filters!; state.tipo = tipo; state.editors[tipo]!.draft = { mode: 'explicit', periodos: periods as [string, ...string[]] };
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
||||
@@ -83,8 +71,8 @@ describe('KPI integración con autoridad global', () => {
|
||||
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], ['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()[3].result().info).toBe('2 de 5 pacientes con TEA positivo tienen un EEG ligado.');
|
||||
expect(panels()[4].result().info).toBe('2 de 5 pacientes con TEA positivo no tienen ningún EEG ligado.');
|
||||
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', () => {
|
||||
load('cacu'); const req = requests(); expect(req).toHaveLength(2); expect(panels().every(p => p.result().loading)).toBe(true);
|
||||
@@ -116,9 +104,8 @@ describe('KPI integración con autoridad global', () => {
|
||||
it('dominio cancela solicitudes salientes y restaura aplicado independiente del borrador', () => {
|
||||
load('cacu'); const outgoing = requests(); apply(['2025-S1']); const applied = requests(); expect(outgoing.every(r => r.cancelled)).toBe(true);
|
||||
fixture.componentInstance.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S2'] };
|
||||
load('cama'); expect(applied.every(r => r.cancelled)).toBe(true); expect(requests().every(r => r.request.url.startsWith('/cama/'))).toBe(true); flushAll('cama');
|
||||
// CaMa's last cards start after its first batch and are cancelled by the change of domain.
|
||||
load('cacu'); const restored = requests().filter(r => !r.cancelled); expect(restored.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
||||
load('cama'); expect(applied.every(r => r.cancelled)).toBe(true); const cama = requests(); expect(cama.every(r => r.request.url.startsWith('/cama/'))).toBe(true); cama.forEach((r,i) => r.flush(response(i, 'cama')));
|
||||
load('cacu'); const restored = requests(); expect(restored.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
||||
expect(fixture.componentInstance.filters!.editors.semestre!.draft).toEqual({ mode: 'explicit', periodos: ['2025-S2'] }); restored.forEach((r,i) => r.flush(response(i)));
|
||||
});
|
||||
it('el catálogo vigente retira los KPI que dejaron de publicarse', () => {
|
||||
@@ -188,23 +175,24 @@ describe('KPI integración con autoridad global', () => {
|
||||
expect(panels()).toHaveLength(2); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true);
|
||||
http.expectNone(r => r.url.endsWith('/datos'));
|
||||
});
|
||||
it('las tarjetas conservan valores, unidades, periodo e información sin etiqueta estadística frontend', () => {
|
||||
it('las seis tarjetas conservan valores, unidades, periodo e información sin etiqueta estadística frontend', () => {
|
||||
for (const domain of ['cacu', 'cama'] as const) {
|
||||
load(domain);
|
||||
flushAll(domain, { notas: ['Nota del pie de la figura.'] });
|
||||
const req = requests(); expect(req).toHaveLength(KPI_BY_DOMAIN[domain].length);
|
||||
req.forEach((r, i) => r.flush({ ...response(i, domain), notas: ['Nota del pie de la figura.'] }));
|
||||
fixture.detectChanges();
|
||||
const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')];
|
||||
expect(cards).toHaveLength(domain === 'cacu' ? 5 : 4);
|
||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', '40.0', '7', '7']);
|
||||
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined]
|
||||
: ['pacientes', '%', 'días (mediana)', 'días (mediana)']);
|
||||
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? [undefined, 'Selección no consolidable', undefined, 'Indicador no disponible', 'Indicador no disponible'] : Array(4).fill(undefined));
|
||||
expect(cards).toHaveLength(domain === 'cacu' ? 5 : 3);
|
||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', '40.0', '7']);
|
||||
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined] : ['pacientes', '%', 'días (mediana)']);
|
||||
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', 'Disponible', 'Disponible']);
|
||||
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining('2025-S1'),
|
||||
expect.stringContaining(domain === 'cacu' ? '5 citologías; primer cuartil: 3 días; tercer cuartil: 9 días.' : '5 mastografías; Q1 a Q3: 3 a 9 días.'),
|
||||
]));
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
|
||||
// CaCu and CaMa cards say only their own line; the kit notes are the figure footer.
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Nota del pie de la figura.');
|
||||
// CaCu cards say only their own line; the kit notes are the figure footer.
|
||||
expect(fixture.nativeElement.textContent.includes('Nota del pie de la figura.')).toBe(domain !== 'cacu');
|
||||
}
|
||||
});
|
||||
it('Aplicar Todos después del periodo compartido conserva supresión del último sin retroceder', () => {
|
||||
@@ -224,7 +212,7 @@ describe('KPI integración con autoridad global', () => {
|
||||
it('primera entrada independiente y regreso inicial reutilizan datos, sin reiniciar filtros', () => {
|
||||
for (const domain of ['cacu', 'cama'] as const) {
|
||||
load(domain, false, ['2025-S1'], true); requests()[0].flush(response(0, domain)); fixture.detectChanges();
|
||||
flushAll(domain);
|
||||
requests().forEach((r, i) => r.flush(response(i + 1, domain))); fixture.detectChanges();
|
||||
expect(TestBed.inject(IndicadoresMemory).initialKpiPresentation(domain)).toBe(false);
|
||||
}
|
||||
load('cacu', false, ['2025-S1'], true);
|
||||
@@ -236,7 +224,7 @@ describe('KPI integración con autoridad global', () => {
|
||||
const data = response(0, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; requests()[0].flush(data);
|
||||
const old = requests(); expect(old).toHaveLength(1);
|
||||
load('cama'); expect(old.every(r => r.cancelled)).toBe(true);
|
||||
flushAll('cama');
|
||||
requests().forEach((r, i) => r.flush(response(i, 'cama')));
|
||||
load('cacu', false, ['2025-S2', '2025-S1'], true); const resumed = requests(); expect(resumed).toHaveLength(1);
|
||||
resumed[0].flush(response(0)); fixture.detectChanges();
|
||||
requests().forEach((r, i) => { expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush(response(i + 1)); });
|
||||
|
||||
@@ -19,12 +19,11 @@ interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; ver
|
||||
imports: [IndicadorKpiCard, MatButtonModule],
|
||||
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
|
||||
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
|
||||
[loading]="result().loading ?? false" [notes]="dominio !== 'tea' ? [] : result().notes ?? []" />
|
||||
[loading]="result().loading ?? false" [notes]="dominio === 'cacu' ? [] : result().notes ?? []" />
|
||||
@if (result().state === 'Error de consulta') {
|
||||
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
|
||||
}`,
|
||||
// The card fills the panel, so cards in one grid row are as tall as the row.
|
||||
styles: ':host { display: flex; flex-direction: column; min-width: 0; } app-indicador-kpi-card { flex: 1 1 auto; }',
|
||||
styles: ':host { display: block; min-width: 0; }',
|
||||
})
|
||||
export class IndicadorKpiPanel implements OnChanges {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
|
||||
@@ -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'); },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -14,11 +14,9 @@
|
||||
@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>
|
||||
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply || (!hasPending && !initialPresentation)" (click)="apply.emit()">Aplicar</button>
|
||||
@if (hasPending) { <span class="pending" role="status">Hay cambios sin aplicar.</span> }
|
||||
</div>
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}. {{ availability ? 'Existe reporte en al menos un indicador del dominio.' : 'Disponibilidad desconocida hasta consultar.' }}</p>
|
||||
@if (availability) {
|
||||
@if (availability.status === 'loading') { <p role="status">Consultando periodos disponibles…</p> }
|
||||
@else if (availability.status === 'error') {
|
||||
@@ -45,5 +43,10 @@
|
||||
</div>
|
||||
}
|
||||
@if (error) { <p class="error" role="alert">{{ error }}</p> }
|
||||
<p class="draft-summary">Selección en edición: {{ summary }}</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" 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>
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
</section>
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
@use '@angular/material' as mat;
|
||||
|
||||
// One compact row, like the Seguimiento form: the two selectors, Aplicar and the pending notice.
|
||||
:host { display: block; min-width: 0; @include mat.theme((density: -4)); }
|
||||
:host { display: block; min-width: 0; margin: var(--issste-space-4) 0; }
|
||||
section { min-width: 0; }
|
||||
.fields { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); }
|
||||
mat-form-field { flex: 0 1 14rem; min-width: 0; }
|
||||
.period-builder mat-form-field { flex: 0 1 9rem; }
|
||||
.period-builder button { min-height: 40px; }
|
||||
p { overflow-wrap: anywhere; line-height: 1.4; margin: var(--issste-space-2) 0 0; font: var(--mat-sys-body-small); }
|
||||
.select-value { white-space: normal; overflow-wrap: anywhere; line-height: 1.4; }
|
||||
.filter-help, .applied-summary { color: var(--issste-text-secondary); }
|
||||
.pending { color: var(--issste-text); font: var(--mat-sys-body-small); border-left: 3px solid var(--issste-accent); padding-left: var(--issste-space-2); }
|
||||
.fields { display: flex; flex-wrap: wrap; align-items: start; gap: var(--issste-space-3); }
|
||||
mat-form-field { flex: 1 1 14rem; min-width: 0; max-width: 24rem; }
|
||||
.period-builder mat-form-field { flex: 0 1 10rem; }
|
||||
.period-builder button { margin-top: var(--issste-space-2); min-height: 44px; }
|
||||
p { overflow-wrap: anywhere; line-height: 1.5; margin: var(--issste-space-3) 0; }
|
||||
.select-value { white-space: normal; overflow-wrap: anywhere; line-height: 1.5; }
|
||||
.filter-help, .applied-summary { color: var(--issste-text-secondary); font: var(--mat-sys-body-small); }
|
||||
.draft-summary { font-weight: 500; }
|
||||
.pending { border-left: 3px solid var(--issste-text); padding-left: var(--issste-space-3); }
|
||||
.error { color: var(--mat-sys-error); }
|
||||
.remove { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); }
|
||||
.apply-button { min-height: 40px; }
|
||||
.remove button { min-height: 44px; }
|
||||
.apply-button { min-height: 44px; margin-top: var(--issste-space-2); }
|
||||
@media (max-width: 550px) {
|
||||
mat-form-field, .period-builder mat-form-field { flex: 1 1 100%; }
|
||||
mat-form-field, .period-builder mat-form-field { flex: 1 1 100%; max-width: none; }
|
||||
.period-builder button { margin-top: 0; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones';
|
||||
import { FigureSelection, IndicadorDatos } from './indicadores.models';
|
||||
|
||||
const fila = (grupo: string, numerador: number, denominador: number, extra: object = {}) => ({
|
||||
periodo: '2025-S2', grupo, estrato: null, suprimido: 0, numerador, denominador, valor: 0, ic_bajo: null, ic_alto: null,
|
||||
n_sin_evento: denominador - numerador, n_excluido: 0, ...extra,
|
||||
});
|
||||
const datos = (filas: Record<string, unknown>[] = [fila('TOTAL', 11, 20), fila('ritmo_posterior', 5, 20), fila('picos_paroxisticos', 0, 20)]): IndicadorDatos => ({
|
||||
id: 'M30_resultado_eeg', titulo: 'Porcentaje de EEG normal y anormal', contrato: 'C1', unidad: 'paciente',
|
||||
tipo_periodo: 'semestre', periodos: ['2025-S2'], estrato: null, valores_estrato: [],
|
||||
grupos: { TOTAL: 'Total', ritmo_posterior: 'Ritmo posterior', picos_paroxisticos: 'Picos paroxísticos' },
|
||||
grupos_de_categoria: {}, notas: ['Datos ficticios.'], filas,
|
||||
});
|
||||
const selection: FigureSelection = { dominio: 'tea', indicador: 'M30_resultado_eeg', figura: 'fig_c1_barras_alteracion', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] };
|
||||
|
||||
describe('Barras por alteración para C1', () => {
|
||||
it('solo aplica a C1 con la figura por alteración', () => {
|
||||
expect(c1AlterationCapability('C1', 'fig_c1_barras_alteracion')).toBe(true);
|
||||
expect(c1AlterationCapability('C2', 'fig_c1_barras_alteracion')).toBe(false);
|
||||
expect(c1AlterationCapability('C1', 'fig_c1_barras_edad')).toBe(false);
|
||||
});
|
||||
it('una barra por alteración tras la de alguna alteración, con su porcentaje y sus conteos', () => {
|
||||
const result = c1AlterationFigure(datos(), selection);
|
||||
if (result.status !== 'supported') throw new Error(result.reason);
|
||||
const [trace] = result.figure.data as Record<string, unknown>[];
|
||||
expect(result.figure.data.length).toBe(1);
|
||||
expect(trace['x']).toEqual(['Alguna alteración', 'Ritmo posterior', 'Picos paroxísticos']);
|
||||
expect(trace['y']).toEqual([55, 25, 0]);
|
||||
expect(trace['text']).toEqual(['55.0 %', '25.0 %', '0.0 %']);
|
||||
expect(trace['customdata']).toEqual([[11, 20], [5, 20], [0, 20]]);
|
||||
expect(result.total).toBe(20);
|
||||
expect(result.notes).toEqual(['Datos ficticios.']);
|
||||
expect(result.highlight.items.map(i => i.id)).toEqual(['TOTAL', 'ritmo_posterior', 'picos_paroxisticos']);
|
||||
expect((result.figure.layout['title'] as { text: string }).text).toBe('Porcentaje de EEG normal y anormal, 2025-S2');
|
||||
});
|
||||
it('varios periodos se dibujan lado a lado, uno por serie', () => {
|
||||
const otro = (grupo: string, n: number, d: number) => fila(grupo, n, d, { periodo: '2025-S1' });
|
||||
const data = { ...datos([otro('TOTAL', 2, 8), otro('ritmo_posterior', 1, 8), otro('picos_paroxisticos', 1, 8), ...datos().filas]), periodos: ['2025-S1', '2025-S2'] };
|
||||
const result = c1AlterationFigure(data, { ...selection, periodos: ['2025-S1', '2025-S2'] });
|
||||
if (result.status !== 'supported') throw new Error(result.reason);
|
||||
const traces = result.figure.data as Record<string, unknown>[];
|
||||
expect(traces.map(t => t['name'])).toEqual(['2025-S1', '2025-S2']);
|
||||
expect(traces[0]['y']).toEqual([25, 12.5, 12.5]);
|
||||
expect(result.figure.layout['showlegend']).toBe(true);
|
||||
expect(result.total).toBe(28);
|
||||
expect(result.highlight.items[1].points).toEqual([{ trace: 0, index: 1 }, { trace: 1, index: 1 }]);
|
||||
});
|
||||
it('un periodo sin niños con EEG bueno no dibuja ceros', () => {
|
||||
const result = c1AlterationFigure(datos([fila('TOTAL', 0, 0), fila('ritmo_posterior', 0, 0), fila('picos_paroxisticos', 0, 0)]), selection);
|
||||
if (result.status !== 'supported') throw new Error(result.reason);
|
||||
expect((result.figure.data[0] as Record<string, unknown>)['y']).toEqual([null, null, null]);
|
||||
expect(result.total).toBe(0);
|
||||
});
|
||||
it('rechaza datos que no son los grupos por alteración de la selección', () => {
|
||||
expect(c1AlterationFigure({ ...datos(), grupos: { TOTAL: 'Total' } }, selection).status).toBe('unsupported');
|
||||
expect(c1AlterationFigure({ ...datos(), estrato: 'grupo_edad' }, selection).status).toBe('unsupported');
|
||||
expect(c1AlterationFigure(datos([fila('TOTAL', 11, 20), fila('ritmo_posterior', 5, 20)]), selection).status).toBe('unsupported');
|
||||
expect(c1AlterationFigure(datos([fila('TOTAL', 11, 20), fila('ritmo_posterior', 25, 20), fila('picos_paroxisticos', 0, 20)]), selection).status).toBe('unsupported');
|
||||
expect(c1AlterationFigure(datos([fila('TOTAL', 11, 20), fila('ritmo_posterior', 5, 20, { suprimido: 1 }), fila('picos_paroxisticos', 0, 20)]), selection).status).toBe('unsupported');
|
||||
expect(c1AlterationFigure(datos(), { ...selection, periodos: ['2025-S1'] }).status).toBe('unsupported');
|
||||
expect(c1AlterationFigure(datos(), { ...selection, figura: 'fig_c1_barras_edad' }).status).toBe('unsupported');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { percentNumber } from './indicadores-format';
|
||||
import { FigureHighlight } from './indicadores-highlight';
|
||||
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
|
||||
import { FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models';
|
||||
|
||||
// fig_c1_barras_alteracion: a C1 proportion whose groups are the alterations of the EEG. One bar per alteration with
|
||||
// the share of the period's children that have it, after a first bar for the children with any of them (the TOTAL
|
||||
// group). A child counts in every alteration it has, so the bars don't add up. Several periods draw side by side.
|
||||
export const C1_ALTERATION_BARS = 'fig_c1_barras_alteracion';
|
||||
const TOTAL = 'TOTAL';
|
||||
const ANY_LABEL = 'Alguna alteración';
|
||||
|
||||
export type C1AlterationResult = { status: 'unsupported'; reason: string }
|
||||
| { status: 'supported'; figure: PlotlyFigure; highlight: FigureHighlight; total: number; notes: string[] };
|
||||
export function c1AlterationCapability(contract: string, representation: string): boolean {
|
||||
return contract === 'C1' && representation === C1_ALTERATION_BARS;
|
||||
}
|
||||
|
||||
const count = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
|
||||
const escape = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
// The any-alteration bar keeps the red of the event; each alteration takes its own colour.
|
||||
const COLORS = [C2_PALETTE.series[1], ...C2_PALETTE.edades, C2_PALETTE.series[2], C2_PALETTE.series[3], C2_PALETTE.series[0]];
|
||||
const color = (i: number) => COLORS[i % COLORS.length];
|
||||
|
||||
export function c1AlterationFigure(data: IndicadorDatos, selection: FigureSelection): C1AlterationResult {
|
||||
const unsupported = (reason: string): C1AlterationResult => ({ status: 'unsupported', reason });
|
||||
if (!c1AlterationCapability(data.contrato, selection.figura)) return unsupported('Representación no soportada');
|
||||
if (data['estrato'] != null) return unsupported('Esta figura no admite una dimensión');
|
||||
const periods = selection.periodos ? data.periodos.filter(p => selection.periodos!.includes(p)) : data.periodos;
|
||||
if (!periods.length) return unsupported('No hay periodos publicados para esta selección');
|
||||
const published = data['grupos'];
|
||||
const groups = Object.entries(published && typeof published === 'object' ? published : {}).filter(([id]) => id !== TOTAL);
|
||||
if (!groups.length) return unsupported('El indicador no publica grupos por alteración');
|
||||
const bars = [{ id: TOTAL, label: ANY_LABEL }, ...groups.map(([id, label]) => ({ id, label: String(label) }))];
|
||||
|
||||
const cells = periods.map(period => bars.map(bar =>
|
||||
data.filas.filter(r => r['periodo'] === period && r['grupo'] === bar.id && r['estrato'] == null)));
|
||||
if (cells.some(row => row.some(found => found.length !== 1))) return unsupported('Grupos por alteración incompletos');
|
||||
const rows = cells.map(row => row.map(([r]) => r));
|
||||
if (rows.some(row => row.some(r => (r['suprimido'] !== 0 && r['suprimido'] !== false)
|
||||
|| !count(r['numerador']) || !count(r['denominador']) || r['numerador'] > r['denominador'])))
|
||||
return unsupported('Conteos por alteración suprimidos o no verificables');
|
||||
|
||||
const theme = c2Theme(selection.tema);
|
||||
const x = bars.map(b => escape(b.label));
|
||||
const single = periods.length === 1;
|
||||
const traces = rows.map((row, p) => {
|
||||
const y = row.map(r => (r['denominador'] as number) ? 100 * (r['numerador'] as number) / (r['denominador'] as number) : null);
|
||||
return { type: 'bar', name: periods[p], x, y,
|
||||
marker: { color: single ? bars.map((_, i) => color(i)) : color(p), line: { color: theme.background, width: 1 } },
|
||||
text: y.map(v => v === null ? '' : percentNumber(v) + ' %'), textposition: 'outside', cliponaxis: false,
|
||||
customdata: row.map(r => [r['numerador'], r['denominador']]),
|
||||
hovertemplate: '%{x}' + (single ? '' : ', %{fullData.name}') + '<br>%{y:.1f} % (%{customdata[0]} de %{customdata[1]} niños)<extra></extra>' };
|
||||
});
|
||||
const figure: PlotlyFigure = {
|
||||
data: traces,
|
||||
layout: { autosize: true, height: 400, barmode: 'group', margin: { t: 56, l: 72, r: 24, b: single ? 64 : 96 }, showlegend: !single,
|
||||
legend: { orientation: 'h', y: -0.3, itemclick: false, itemdoubleclick: false },
|
||||
title: { text: escape(String(data['titulo'] ?? data.id)) + (single ? ', ' + periods[0] : '') },
|
||||
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text },
|
||||
xaxis: { type: 'category', title: { text: 'Alteración del EEG' }, automargin: true },
|
||||
yaxis: { title: { text: '% de niños con EEG de buena calidad' }, range: [0, 100], ticksuffix: ' %', gridcolor: theme.grid, zeroline: false } },
|
||||
config: { displayModeBar: false },
|
||||
};
|
||||
const highlight: FigureHighlight = { groups: [], traces: traces.map((_, t) => t), allLabel: 'Todas las alteraciones',
|
||||
items: bars.map((b, i) => ({ id: b.id, label: b.label, color: single ? color(i) : theme.line,
|
||||
points: traces.map((_, t) => ({ trace: t, index: i })) })) };
|
||||
// Children with a first good EEG over the periods drawn: zero means there is nothing to draw a share of.
|
||||
const total = rows.reduce((sum, row) => sum + (row[0]['denominador'] as number), 0);
|
||||
return { status: 'supported', figure, highlight, total, notes: Array.isArray(data.notas) ? [...data.notas] : [] };
|
||||
}
|
||||
@@ -9,11 +9,11 @@ import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { Indicador, IndicadorDatos } from './indicadores.models';
|
||||
import { clicConfirmacion, clicDona, ConfirmacionIncompatible, CONFIRMACION_CACU, CONFIRMACION_CAMA, donaConfirmacion, donaExpandible, estadoTasa, figuraTasas, lectura, modeloConfirmacion,
|
||||
periodosConfirmacion, rangoTasas, seleccionBase, seleccionEtiqueta, tasas, vistaConfirmacion, wilson } from './indicadores-confirmacion-citologia';
|
||||
import { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, estadoTasa, figuraTasas, lectura, modeloConfirmacion,
|
||||
periodosConfirmacion, rangoTasas, seleccionBase, tasas, wilson } from './indicadores-confirmacion-citologia';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); animated = input<boolean>(); plotClick = output<unknown>(); }
|
||||
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); plotClick = output<unknown>(); }
|
||||
|
||||
const GRADOS = ['NORMAL', 'LIEBG', 'LIEAG', 'CIS', 'CARCINOMA'];
|
||||
// Real kit shape: both apart keys, an off-catalogue grade (CIN2, colour null) and
|
||||
@@ -62,7 +62,7 @@ describe('Confirmación histopatológica: modelo', () => {
|
||||
const d = respuesta(['2026-S2'], { LIEAG: CONTEOS['LIEAG'] });
|
||||
const m = modeloConfirmacion(d, '2026-S2');
|
||||
expect(m.filas.map(f => f.den)).toEqual([0, 58, 0]);
|
||||
expect(tasas(m, seleccionBase(m)).map(t => estadoTasa(t))).toEqual(['Sin mujeres con biopsia', '', 'Sin mujeres con biopsia']);
|
||||
expect(tasas(m, seleccionBase(m)).map(estadoTasa)).toEqual(['Sin mujeres con biopsia', '', 'Sin mujeres con biopsia']);
|
||||
expect(m.filas[0].etiqueta).toBe('Carcinoma in situ');
|
||||
(d['totales_estrato'] as Record<string, unknown>[])[0]['suprimido'] = 1;
|
||||
const s = modeloConfirmacion(d, '2026-S2');
|
||||
@@ -223,65 +223,3 @@ describe('Confirmación histopatológica: componente', () => {
|
||||
card.destroy(); http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
|
||||
// Cáncer de mama's configuration of the same view. Fixture: a one-period answer of cama_histopatologia_birads
|
||||
// built below, with two BI-RADS categories published and biopsies without a result kept apart.
|
||||
describe('Confirmación histopatológica de cáncer de mama', () => {
|
||||
const categorias = {
|
||||
BENIGNO: { etiqueta: 'Benigno', color: '#9DBFE3', grupo: 'NO_MALIGNO' }, RIESGO_B3: { etiqueta: 'Lesión de riesgo (B3)', color: '#2F6DB3', grupo: 'NO_MALIGNO' },
|
||||
IN_SITU: { etiqueta: 'Carcinoma in situ', color: '#D9822B', grupo: 'MALIGNO' }, INVASOR: { etiqueta: 'Carcinoma invasor', color: '#B5482E', grupo: 'MALIGNO' },
|
||||
SIN_DATO: { etiqueta: 'Sin resultado histopatológico', color: '#BDBDBD', grupo: 'SIN_DATO' },
|
||||
};
|
||||
const n: Record<string, Record<string, number>> = {
|
||||
BIRADS_5: { BENIGNO: 3, RIESGO_B3: 0, IN_SITU: 11, INVASOR: 38, SIN_DATO: 3 },
|
||||
BIRADS_4A: { BENIGNO: 91, RIESGO_B3: 15, IN_SITU: 1, INVASOR: 7, SIN_DATO: 9 },
|
||||
};
|
||||
const datos = () => ({ id: 'cama_histopatologia_birads', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S2'], estrato: 'birads',
|
||||
valores_estrato: Object.keys(n), categorias, grupos_de_categoria: { NO_MALIGNO: 'No maligno', MALIGNO: 'Maligno', SIN_DATO: 'Sin dato' },
|
||||
filas: Object.entries(n).flatMap(([estrato, c]) => Object.entries(c).map(([categoria, v]) =>
|
||||
({ periodo: '2025-S2', grupo: 'TOTAL', estrato, categoria, n: v, suprimido: 0 }))) }) as IndicadorDatos;
|
||||
|
||||
it('la elige el dominio y el indicador', () => {
|
||||
// Fails if the view stops being found for cáncer de mama, or leaks to another indicator.
|
||||
expect(vistaConfirmacion('cama', { id: 'cama_histopatologia_birads' })).toBe(CONFIRMACION_CAMA);
|
||||
expect(vistaConfirmacion('cama', { id: 'cacu_confirmacion_citologia' })).toBeUndefined();
|
||||
});
|
||||
it('filas BI-RADS de la más grave a la menor, base maligna y sin resultado aparte', () => {
|
||||
// Fails if the rows don't follow the configuration, the base isn't malignancy or «Sin dato» enters the rate.
|
||||
const m = modeloConfirmacion(datos(), '2025-S2', CONFIRMACION_CAMA), base = seleccionBase(m);
|
||||
expect(m.filas.map(f => f.id)).toEqual(['BIRADS_6', 'BIRADS_5', 'BIRADS_4C', 'BIRADS_4B', 'BIRADS_4A']);
|
||||
expect(base).toEqual({ grupo: 'MALIGNO' });
|
||||
expect(lectura(m, base)).toBe('Detección de cáncer (valor predictivo positivo)');
|
||||
const t = tasas(m, base);
|
||||
expect(t[1].k).toBe(49); expect(t[1].fila.den).toBe(52);
|
||||
expect(t[4].k).toBe(8); expect(t[4].fila.den).toBe(114);
|
||||
expect(estadoTasa(t[0], m.vista.textos.sujetos)).toBe('Sin pacientes con biopsia');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Dona interactiva como la de CaCu (sin botones)', () => {
|
||||
const vista = { ...CONFIRMACION_CAMA, id: 'cacu_confirmacion_citologia', estrato: 'citologia_alto_grado' as const, filas: CONFIRMACION_CACU.filas, base: 'LIEAG' };
|
||||
const modelo = () => modeloConfirmacion(respuesta(), '2026-S2', vista);
|
||||
it('total → grupo → resultado y el centro regresa un paso hasta el total', () => {
|
||||
// Fails if the centre stops returning to the total, or a group click no longer narrows to it.
|
||||
const m = modelo(), g = m.grupos.findIndex(x => x.id === m.base), c = m.grados.findIndex(x => x.grupo === m.base);
|
||||
let s = clicDona(m, {}, 'grupos', g); expect(s).toEqual({ grupo: m.base });
|
||||
s = clicDona(m, s, 'categorias', c); expect(s).toEqual({ grupo: m.base, categoria: m.grados[c].id });
|
||||
s = clicDona(m, s, 'centro', 0); expect(s).toEqual({ grupo: m.base });
|
||||
s = clicDona(m, s, 'centro', 0); expect(s).toEqual({});
|
||||
expect(clicDona(m, { grupo: m.base }, 'grupos', g)).toEqual({});
|
||||
const otra = m.grados.findIndex(x => x.grupo !== m.base);
|
||||
expect(clicDona(m, { grupo: m.base }, 'categorias', otra)).toEqual({ grupo: m.base });
|
||||
});
|
||||
it('el grupo elegido llena los dos anillos y el total cuenta el grupo base en las tasas', () => {
|
||||
// Fails if the other group's slices stay (no expansion), or the total stops reading as the base rate.
|
||||
const m = modelo(), base = m.grupos.find(x => x.id === m.base)!;
|
||||
const d = donaExpandible(m, { grupo: m.base }, 'claro');
|
||||
const exterior = d.data[2]['values'] as number[];
|
||||
m.grados.forEach((g, i) => expect(exterior[i] === 0).toBe(g.grupo !== m.base));
|
||||
expect((d.data[1]['values'] as number[]).filter(v => v > 0)).toHaveLength(1);
|
||||
expect(d.data[0]['text']).toEqual([`<b>${base.grados.reduce((s, c) => s + m.totales[c]!, 0)}</b><br>${base.etiqueta}`]);
|
||||
expect(tasas(m, {}).map(t => t.k)).toEqual(tasas(m, seleccionBase(m)).map(t => t.k));
|
||||
expect(lectura(m, {})).toBe(vista.textos.base);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { DimensionEstrato, Dominio, Indicador, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Theme } from './indicadores-c2-palette';
|
||||
import { percentNumber, shareText } from './indicadores-format';
|
||||
|
||||
@@ -24,36 +24,6 @@ export const FILAS_CITOLOGIA = [
|
||||
] as const;
|
||||
export const Z95 = 1.959963984540054;
|
||||
|
||||
// One confirmation view: which indicator and stratum, its fixed rows (most severe on top), the grade whose group is
|
||||
// the base view (the true positives), the grade read as a false positive, and the words the view uses.
|
||||
export interface VistaConfirmacion {
|
||||
id: string; estrato: DimensionEstrato; filas: readonly { id: string; etiqueta: string }[];
|
||||
base: string; falsoPositivo: string;
|
||||
// With buttons, the choice is made on them; without, on the donut (donaExpandible), whose centre names it.
|
||||
botones: boolean;
|
||||
textos: { base: string; falsoPositivo: string; sinConfirmacion: string; filas: string; encabezado: string; sujetos: string; vacio: string };
|
||||
}
|
||||
export const CONFIRMACION_CACU: VistaConfirmacion = {
|
||||
id: ID_CONFIRMACION, estrato: ESTRATO_CITOLOGIA, filas: FILAS_CITOLOGIA, base: 'LIEAG', falsoPositivo: 'NORMAL', botones: true,
|
||||
textos: { base: 'Verdaderos positivos (valor predictivo positivo)', falsoPositivo: 'Falsos positivos: la biopsia no confirmó lesión',
|
||||
sinConfirmacion: 'Sin confirmación de alto grado', filas: 'Por resultado de la citología', encabezado: 'Citología', sujetos: 'mujeres',
|
||||
vacio: 'No hay citologías de alto grado publicadas para este periodo.' },
|
||||
};
|
||||
// Cáncer de mama: the biopsies by the BI-RADS of the mammogram that led to them; the base is malignancy.
|
||||
export const CONFIRMACION_CAMA: VistaConfirmacion = {
|
||||
id: 'cama_histopatologia_birads', estrato: 'birads', base: 'INVASOR', falsoPositivo: 'BENIGNO', botones: false,
|
||||
filas: [{ id: 'BIRADS_6', etiqueta: 'BI-RADS 6' }, { id: 'BIRADS_5', etiqueta: 'BI-RADS 5' }, { id: 'BIRADS_4C', etiqueta: 'BI-RADS 4C' },
|
||||
{ id: 'BIRADS_4B', etiqueta: 'BI-RADS 4B' }, { id: 'BIRADS_4A', etiqueta: 'BI-RADS 4A' }],
|
||||
textos: { base: 'Detección de cáncer (valor predictivo positivo)', falsoPositivo: 'Falsos positivos: la biopsia resultó benigna',
|
||||
sinConfirmacion: 'Sin malignidad', filas: 'Por categoría BI-RADS', encabezado: 'BI-RADS', sujetos: 'pacientes',
|
||||
vacio: 'No hay biopsias publicadas para este periodo.' },
|
||||
};
|
||||
const VISTAS_CONFIRMACION: Readonly<Partial<Record<Dominio, VistaConfirmacion>>> = { cacu: CONFIRMACION_CACU, cama: CONFIRMACION_CAMA };
|
||||
export function vistaConfirmacion(dominio: Dominio, indicador: Pick<Indicador, 'id'>): VistaConfirmacion | undefined {
|
||||
const vista = VISTAS_CONFIRMACION[dominio];
|
||||
return vista?.id === indicador.id ? vista : undefined;
|
||||
}
|
||||
|
||||
export interface Celda { n: number | null; estado: 'Publicado' | 'Suprimido' | 'No disponible'; }
|
||||
export interface Grado { id: string; etiqueta: string; color: string; grupo: string; }
|
||||
export interface GrupoGrados { id: string; etiqueta: string; color: string; grados: string[]; }
|
||||
@@ -67,10 +37,9 @@ export interface FilaCitologia {
|
||||
export interface ModeloConfirmacion {
|
||||
periodo: string; grados: Grado[]; grupos: GrupoGrados[]; base: string;
|
||||
filas: FilaCitologia[]; totales: Record<string, number | null>; conBiopsia: number | null;
|
||||
aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[]; vista: VistaConfirmacion;
|
||||
aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[];
|
||||
}
|
||||
// Without a group, the total: every result is shown and the rates count the base group.
|
||||
export interface SeleccionConfirmacion { grupo?: string; categoria?: string; }
|
||||
export interface SeleccionConfirmacion { grupo: string; categoria?: string; }
|
||||
export interface Tasa { fila: FilaCitologia; k: number | null; valor: number | null; bajo: number | null; alto: number | null; }
|
||||
export class ConfirmacionIncompatible extends Error {}
|
||||
|
||||
@@ -112,8 +81,8 @@ function rgba(hex: string, alfa: number): string {
|
||||
const etiquetaGrupo = (v: unknown) => texto(v) ? v : registro(v) && texto(v['etiqueta']) ? v['etiqueta'] : undefined;
|
||||
|
||||
/** Validated periods of one stratified response, in request order or sorted. */
|
||||
export function periodosConfirmacion(datos: IndicadorDatos, tipo: string, solicitados?: readonly string[], vista = CONFIRMACION_CACU): string[] {
|
||||
if (datos.id !== vista.id || datos.contrato !== 'C2' || datos.tipo_periodo !== tipo || datos['estrato'] !== vista.estrato
|
||||
export function periodosConfirmacion(datos: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] {
|
||||
if (datos.id !== ID_CONFIRMACION || datos.contrato !== 'C2' || datos.tipo_periodo !== tipo || datos['estrato'] !== ESTRATO_CITOLOGIA
|
||||
|| !Array.isArray(datos.periodos) || new Set(datos.periodos).size !== datos.periodos.length
|
||||
|| datos.periodos.some(p => typeof p !== 'string' || !(tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(p))
|
||||
|| (solicitados && datos.periodos.some(p => !solicitados.includes(p)))
|
||||
@@ -124,8 +93,8 @@ export function periodosConfirmacion(datos: IndicadorDatos, tipo: string, solici
|
||||
}
|
||||
|
||||
/** One /datos payload -> the contingency table of a single period. */
|
||||
export function modeloConfirmacion(datos: IndicadorDatos, periodo: string, vista = CONFIRMACION_CACU): ModeloConfirmacion {
|
||||
periodosConfirmacion(datos, datos.tipo_periodo, undefined, vista);
|
||||
export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): ModeloConfirmacion {
|
||||
periodosConfirmacion(datos, datos.tipo_periodo);
|
||||
const cats = datos['categorias'], nombres = datos['grupos_de_categoria'];
|
||||
if (!registro(cats) || !registro(nombres)) return fail('Catálogo de grados incompleto.');
|
||||
const aparte = APARTE.filter(a => Object.hasOwn(cats, a.id)).map(a => {
|
||||
@@ -143,8 +112,8 @@ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string, vista
|
||||
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: promedio((publicados.length ? publicados : propios).map(g => g.color)),
|
||||
grados: propios.map(g => g.id) };
|
||||
});
|
||||
// The base view is the group of the view's base grade (CaCu: "LIEAG o más"): the true positives.
|
||||
const base = grados.find(g => g.id === vista.base)?.grupo ?? fail(`El catálogo no publica el grado ${vista.base}.`);
|
||||
// The base view is the group of LIEAG ("LIEAG o más"): the true positives.
|
||||
const base = grados.find(g => g.id === 'LIEAG')?.grupo ?? fail('El catálogo no publica el grado LIEAG.');
|
||||
if (grupos.length !== 2) fail('Se esperaban dos grupos de grados.');
|
||||
const index = new Map<string, Record<string, unknown>>();
|
||||
for (const row of datos.filas.filter(f => f['periodo'] === periodo)) {
|
||||
@@ -159,11 +128,11 @@ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string, vista
|
||||
}
|
||||
// valores_estrato may list only the strata with data; a fixed row absent from it has no women.
|
||||
const publicados = Array.isArray(datos['valores_estrato']) ? (datos['valores_estrato'] as unknown[]) : undefined;
|
||||
if (publicados && !publicados.every(v => typeof v === 'string')) fail('Estratos inválidos.');
|
||||
if (publicados && !publicados.every(v => typeof v === 'string')) fail('Estratos de citología inválidos.');
|
||||
const etiquetas = registro(datos['etiquetas_estrato']) ? datos['etiquetas_estrato'] : {};
|
||||
const totales = Array.isArray(datos['totales_estrato']) ? (datos['totales_estrato'] as unknown[]) : [];
|
||||
if (!totales.every(registro)) fail('Totales por estrato inválidos.');
|
||||
const filas = vista.filas.map(({ id, etiqueta }) => {
|
||||
if (!totales.every(registro)) fail('Totales de citología inválidos.');
|
||||
const filas = FILAS_CITOLOGIA.map(({ id, etiqueta }) => {
|
||||
const rotulo = texto(etiquetas[id]) ? etiquetas[id] : registro(cats[id]) && texto(cats[id]['etiqueta']) ? cats[id]['etiqueta'] : etiqueta;
|
||||
const tieneFilas = [...index.keys()].some(k => JSON.parse(k)[0] === id);
|
||||
const ausente = !tieneFilas && (!publicados || !publicados.includes(id));
|
||||
@@ -179,26 +148,15 @@ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string, vista
|
||||
const porGrado = Object.fromEntries(grados.map(g => [g.id, filas.some(f => f.den === null) ? null : suma(filas.map(f => f.celdas[g.id]))]));
|
||||
return { periodo, grados, grupos, base, filas, totales: porGrado,
|
||||
conBiopsia: suma(grados.map(g => ({ n: porGrado[g.id], estado: 'Publicado' as const }))),
|
||||
aparte, vacio: index.size === 0, notas: [...new Set(datos.notas ?? [])], vista };
|
||||
aparte, vacio: index.size === 0, notas: [...new Set(datos.notas ?? [])] };
|
||||
}
|
||||
|
||||
export function seleccionBase(m: ModeloConfirmacion): SeleccionConfirmacion { return { grupo: m.base }; }
|
||||
export function seleccionados(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string[] {
|
||||
return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === (sel.grupo ?? m.base))?.grados ?? [];
|
||||
return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === sel.grupo)?.grados ?? [];
|
||||
}
|
||||
export function seleccionEtiqueta(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string {
|
||||
return sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.etiqueta
|
||||
: sel.grupo ? m.grupos.find(g => g.id === sel.grupo)!.etiqueta : 'Todos los resultados';
|
||||
}
|
||||
/** CaCu's interactive donut: a group narrows to it, a result is chosen inside its group, the centre steps back
|
||||
* (result -> its group -> the total), and choosing the chosen entry again also steps back. */
|
||||
export function clicDona(m: ModeloConfirmacion, sel: SeleccionConfirmacion, traza: string, indice: number): SeleccionConfirmacion {
|
||||
if (traza === 'centro') return sel.categoria && sel.grupo ? { grupo: sel.grupo } : {};
|
||||
if (traza === 'grupos') { const g = m.grupos[indice]?.id; return !g ? sel : sel.grupo === g && !sel.categoria ? {} : { grupo: g }; }
|
||||
if (traza !== 'categorias') return sel;
|
||||
const c = m.grados[indice];
|
||||
if (!c || (sel.grupo && c.grupo !== sel.grupo)) return sel;
|
||||
return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id };
|
||||
return sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.etiqueta : m.grupos.find(g => g.id === sel.grupo)!.etiqueta;
|
||||
}
|
||||
/** Group selects the group; a grade selects it and a second click returns to its group; the centre returns to the base. */
|
||||
export function clicConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmacion, traza: string, indice: number): SeleccionConfirmacion {
|
||||
@@ -211,9 +169,9 @@ export function clicConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmaci
|
||||
}
|
||||
/** The axis title says what the rate reads. */
|
||||
export function lectura(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string {
|
||||
if (!sel.categoria && (sel.grupo ?? m.base) === m.base) return m.vista.textos.base;
|
||||
if (sel.categoria === m.vista.falsoPositivo) return m.vista.textos.falsoPositivo;
|
||||
if (!sel.categoria) return m.vista.textos.sinConfirmacion;
|
||||
if (!sel.categoria && sel.grupo === m.base) return 'Verdaderos positivos (valor predictivo positivo)';
|
||||
if (sel.categoria === 'NORMAL') return 'Falsos positivos: la biopsia no confirmó lesión';
|
||||
if (!sel.categoria) return 'Sin confirmación de alto grado';
|
||||
return 'Proporción con biopsia ' + seleccionEtiqueta(m, sel);
|
||||
}
|
||||
/** Per cytology: selected grades over women with a biopsy. "No biopsy yet" never enters. */
|
||||
@@ -226,8 +184,8 @@ export function tasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion): Tasa[]
|
||||
return { fila, k, valor: 100 * k / fila.den, bajo, alto };
|
||||
});
|
||||
}
|
||||
export function estadoTasa(t: Tasa, sujetos = 'mujeres'): string {
|
||||
return t.fila.den === 0 ? `Sin ${sujetos} con biopsia` : t.fila.estado === 'Publicado' ? '' : t.fila.estado;
|
||||
export function estadoTasa(t: Tasa): string {
|
||||
return t.fila.den === 0 ? 'Sin mujeres con biopsia' : t.fila.estado === 'Publicado' ? '' : t.fila.estado;
|
||||
}
|
||||
/** Axis bounded to what is shown: 5-point margin, multiples of 5, within 0-100. */
|
||||
export function rangoTasas(valores: Tasa[]): [number, number] {
|
||||
@@ -241,14 +199,14 @@ export function rangoTasas(valores: Tasa[]): [number, number] {
|
||||
export function figuraTasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema);
|
||||
const valores = tasas(m, sel);
|
||||
const color = sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.color : m.grupos.find(g => g.id === (sel.grupo ?? m.base))!.color;
|
||||
const color = sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.color : m.grupos.find(g => g.id === sel.grupo)!.color;
|
||||
const y = valores.map(t => t.fila.etiqueta);
|
||||
return { data: [{
|
||||
type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor),
|
||||
marker: { size: 12, color }, cliponaxis: false,
|
||||
error_x: { type: 'data', symmetric: false, color, thickness: 2, width: 6,
|
||||
array: valores.map(t => t.valor === null ? 0 : t.alto! - t.valor), arrayminus: valores.map(t => t.valor === null ? 0 : t.valor - t.bajo!) },
|
||||
customdata: valores.map(t => t.k === null ? [estadoTasa(t, m.vista.textos.sujetos), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]),
|
||||
customdata: valores.map(t => t.k === null ? [estadoTasa(t), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]),
|
||||
hovertemplate: '%{y}<br><b>%{customdata[0]}</b> (%{customdata[1]}/%{customdata[2]})<br>IC 95 %: %{customdata[3]}–%{customdata[4]} %<extra></extra>',
|
||||
}], layout: {
|
||||
autosize: true, height: 360, showlegend: false, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||
@@ -257,7 +215,7 @@ export function figuraTasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion, t
|
||||
xaxis: { range: rangoTasas(valores), ticksuffix: ' %', gridcolor: p.grid, zeroline: false, fixedrange: true, title: { text: lectura(m, sel) } },
|
||||
annotations: valores.map(t => ({ x: 1, xref: 'paper', xanchor: 'left', xshift: 8, y: t.fila.etiqueta, yref: 'y', showarrow: false, align: 'left',
|
||||
font: { size: 12, color: p.text },
|
||||
text: t.k === null ? estadoTasa(t, m.vista.textos.sujetos) : `<b>${shareText(t.k, t.fila.den!)}</b><br>${t.k}/${t.fila.den}` })),
|
||||
text: t.k === null ? estadoTasa(t) : `<b>${shareText(t.k, t.fila.den!)}</b><br>${t.k}/${t.fila.den}` })),
|
||||
}, config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
@@ -269,7 +227,7 @@ export function donaConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmaci
|
||||
const interior = m.grupos.map(g => g.grados.reduce((s, c) => s + m.totales[c]!, 0));
|
||||
const exterior = m.grados.map(g => m.totales[g.id]!);
|
||||
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' };
|
||||
const hover = { hovertemplate: `%{label}<br>%{customdata[0]} ${m.vista.textos.sujetos} con biopsia, %{customdata[1]}<extra></extra>` };
|
||||
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} mujeres con biopsia, %{customdata[1]}<extra></extra>' };
|
||||
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
|
||||
return { data: [
|
||||
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, textinfo: 'text', textposition: 'inside',
|
||||
@@ -284,41 +242,3 @@ export function donaConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmaci
|
||||
], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
|
||||
config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
/** Donut without buttons, drawn like CaCu's interactive one: the chosen group fills both rings (the other's
|
||||
* slices are zero, so its results expand), a chosen result keeps its colour and its siblings fade, and the
|
||||
* centre names the choice. The traces keep their names and counts, so a choice animates. */
|
||||
export function donaExpandible(m: ModeloConfirmacion, sel: SeleccionConfirmacion, tema: Tema): PlotlyFigure {
|
||||
if (m.conBiopsia === null || m.conBiopsia === 0) return { data: [], layout: {} };
|
||||
const p = c2Theme(tema), total = m.conBiopsia;
|
||||
const nGrupo = (g: GrupoGrados) => g.grados.reduce((s, c) => s + m.totales[c]!, 0);
|
||||
const interior = m.grupos.map(g => !sel.grupo || sel.grupo === g.id ? nGrupo(g) : 0);
|
||||
const exterior = m.grados.map(g => !sel.grupo || sel.grupo === g.grupo ? m.totales[g.id]! : 0);
|
||||
const centro = sel.categoria ? m.totales[sel.categoria]! : sel.grupo ? nGrupo(m.grupos.find(g => g.id === sel.grupo)!) : total;
|
||||
const rotulos = (values: number[], labels: string[], pct: boolean) => {
|
||||
const suma = values.reduce((s, n) => s + n, 0);
|
||||
return values.map((v, i) => !suma || v / suma < .05 ? '' : escapar(labels[i]) + (pct ? '<br>' + shareText(v, suma) : ''));
|
||||
};
|
||||
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'text', textposition: 'inside',
|
||||
insidetextorientation: 'horizontal' };
|
||||
const hover = { hovertemplate: `%{label}<br>%{customdata[0]} ${m.vista.textos.sujetos} con biopsia, %{customdata[1]}<extra></extra>` };
|
||||
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
|
||||
return { data: [
|
||||
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] },
|
||||
text: [`<b>${miles(centro)}</b><br>${escapar(sel.grupo || sel.categoria ? seleccionEtiqueta(m, sel) : 'Con biopsia')}`],
|
||||
textfont: { size: 16, color: p.text }, marker: { colors: [p.background] },
|
||||
hovertemplate: (sel.grupo || sel.categoria ? 'Volver' : 'Todos los resultados') + '<extra></extra>' },
|
||||
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
|
||||
labels: m.grupos.map(g => escapar(g.etiqueta)), text: rotulos(interior, m.grupos.map(g => g.etiqueta), false),
|
||||
textfont: { color: '#FFFFFF' }, customdata: custom(interior),
|
||||
marker: { colors: m.grupos.map(g => rgba(g.color, sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
|
||||
// Outer labels go outside the ring with a leader line, at full size; automargin makes room for them and
|
||||
// shrinks the three rings together, so they stay concentric.
|
||||
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
|
||||
labels: m.grados.map(g => escapar(g.etiqueta)), textposition: 'outside', automargin: true,
|
||||
text: exterior.map((v, i) => v ? escapar(m.grados[i].etiqueta) + '<br>' + shareText(v, exterior.reduce((s, n) => s + n, 0)) : ''),
|
||||
textfont: { size: 12, color: p.text }, customdata: custom(exterior),
|
||||
marker: { colors: m.grados.map(g => rgba(g.color, sel.categoria && g.id !== sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
|
||||
], layout: { autosize: true, height: 440, margin: { t: 30, l: 30, r: 30, b: 30 }, paper_bgcolor: p.background, font: { color: p.text } },
|
||||
config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import { barrasConteos, ConteosIncompatibles, donaConteos, esSocioConteos, modelosConteos, PARES_CONTEOS, parConteos, razon, totalExamenes } from './indicadores-conteos-pareados';
|
||||
|
||||
// Covers the paired counts of cáncer de mama: mammograms by BI-RADS (donut) and each patient BI-RADS next to its
|
||||
// mammograms (bars). Fixtures: two one-period answers built below, with the categories the API publishes.
|
||||
const par = PARES_CONTEOS[0];
|
||||
const filas = (n: Record<string, number | null>) => Object.entries(n).map(([categoria, v]) =>
|
||||
({ periodo: '2025-S2', grupo: 'TOTAL', estrato: null, categoria, n: v, suprimido: v === null ? 1 : 0 }));
|
||||
const examenes = (n: Record<string, number | null> = { B4A: 30, B4B: 18, B4C: 12, B5: 1016, B6: 972, SIN_DATO: 20 }) => ({
|
||||
id: 'cama_birads_456_mastografia', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S2'],
|
||||
categorias: Object.fromEntries(Object.keys(n).map(k => [k, { etiqueta: k === 'SIN_DATO' ? 'Sin dato' : 'BI-RADS ' + k.slice(1), color: '#C26A2B' }])),
|
||||
filas: filas(n) }) as unknown as IndicadorDatos;
|
||||
const pacientes = () => ({ id: 'cama_birads_456_paciente', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S2'],
|
||||
categorias: { BIRADS_4: { etiqueta: 'BI-RADS 4' }, BIRADS_5: { etiqueta: 'BI-RADS 5' }, BIRADS_6: { etiqueta: 'BI-RADS 6' } },
|
||||
filas: filas({ BIRADS_4: 15, BIRADS_5: 254, BIRADS_6: 243 }) }) as unknown as IndicadorDatos;
|
||||
|
||||
describe('Conteos por mastografía y por paciente', () => {
|
||||
it('la tarjeta de mastografías los dibuja y la de pacientes no tiene tarjeta propia', () => {
|
||||
// Fails if the pair is found on the wrong card, or the patients still get a card of their own.
|
||||
expect(parConteos('cama', 'cama_birads_456_mastografia')).toBe(par);
|
||||
expect(parConteos('cama', 'cama_birads_456_paciente')).toBeUndefined();
|
||||
expect(esSocioConteos('cama', 'cama_birads_456_paciente', ['cama_birads_456_mastografia', 'cama_birads_456_paciente'])).toBe(true);
|
||||
expect(esSocioConteos('cama', 'cama_birads_456_paciente', ['cama_birads_456_paciente'])).toBe(false);
|
||||
});
|
||||
it('suma 4A, 4B y 4C en el BI-RADS 4 de la paciente y deja «Sin dato» fuera de la dona', () => {
|
||||
// Fails if subcategories don't add up to their patient category, or uncategorised exams enter the donut.
|
||||
const [m] = modelosConteos(par, examenes(), pacientes(), 'semestre');
|
||||
expect(m.filas.map(f => [f.id, f.pacientes, f.examenes])).toEqual([['BIRADS_4', 15, 60], ['BIRADS_5', 254, 1016], ['BIRADS_6', 243, 972]]);
|
||||
expect(razon(m.filas[0])).toBe(4);
|
||||
expect(totalExamenes(m)).toBe(2048); expect(m.sinDato).toBe(20);
|
||||
expect(donaConteos(m, par, 'claro').data[0]['values']).toEqual([30, 18, 12, 1016, 972]);
|
||||
expect(barrasConteos(m, par, 'claro').data.map(t => t['x'])).toEqual([[15, 254, 243], [60, 1016, 972]]);
|
||||
});
|
||||
it('una celda suprimida no se vuelve cero', () => {
|
||||
// Fails if a suppressed exam count is drawn as zero or its category's sum and ratio are still computed.
|
||||
const [m] = modelosConteos(par, examenes({ B4A: null, B4B: 18, B4C: 12, B5: 1016, B6: 972 }), pacientes(), 'semestre');
|
||||
expect(totalExamenes(m)).toBeNull(); expect(m.filas[0].examenes).toBeNull(); expect(razon(m.filas[0])).toBeNull();
|
||||
expect(donaConteos(m, par, 'claro').data).toEqual([]);
|
||||
});
|
||||
it('rechaza respuestas de otro indicador o intervalo', () => {
|
||||
// Fails if the view accepts data that isn't the pair it draws.
|
||||
expect(() => modelosConteos(par, pacientes(), pacientes(), 'semestre')).toThrow(ConteosIncompatibles);
|
||||
expect(() => modelosConteos(par, examenes(), pacientes(), 'mes')).toThrow(ConteosIncompatibles);
|
||||
});
|
||||
});
|
||||
@@ -1,102 +0,0 @@
|
||||
import { Dominio, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Theme } from './indicadores-c2-palette';
|
||||
import { percentNumber } from './indicadores-format';
|
||||
|
||||
// Two C2 counts of the same finding, one per exam and one per patient: the exams' composition as a donut, and
|
||||
// each patient category next to its exams, so the bars say how many exams each patient has.
|
||||
export interface ParConteos {
|
||||
dominio: Dominio;
|
||||
examenes: string;
|
||||
pacientes: string;
|
||||
// Exam category -> patient category it adds to (BI-RADS 4A, 4B and 4C are a patient's BI-RADS 4).
|
||||
grupoDe: Readonly<Record<string, string>>;
|
||||
unidades: { examenes: string; pacientes: string; porPaciente: string };
|
||||
}
|
||||
export const PARES_CONTEOS: readonly ParConteos[] = [
|
||||
{ dominio: 'cama', examenes: 'cama_birads_456_mastografia', pacientes: 'cama_birads_456_paciente',
|
||||
grupoDe: { B4A: 'BIRADS_4', B4B: 'BIRADS_4', B4C: 'BIRADS_4', B5: 'BIRADS_5', B6: 'BIRADS_6' },
|
||||
unidades: { examenes: 'mastografías', pacientes: 'pacientes', porPaciente: 'por paciente' } },
|
||||
];
|
||||
// The card of the exams draws the pair; the patients' indicator is its partner and has no card of its own.
|
||||
export const parConteos = (dominio: Dominio, id: string) => PARES_CONTEOS.find(p => p.dominio === dominio && p.examenes === id);
|
||||
export const esSocioConteos = (dominio: Dominio, id: string, ids: readonly string[]) =>
|
||||
PARES_CONTEOS.some(p => p.dominio === dominio && p.pacientes === id && ids.includes(p.examenes));
|
||||
|
||||
export interface CategoriaConteo { id: string; etiqueta: string; color: string; n: number | null; }
|
||||
export interface FilaConteo { id: string; etiqueta: string; pacientes: number | null; examenes: number | null; }
|
||||
export interface ModeloConteos { periodo: string; examenes: CategoriaConteo[]; sinDato: number | null; filas: FilaConteo[]; notas: string[]; }
|
||||
export class ConteosIncompatibles extends Error {}
|
||||
|
||||
const registro = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const fail = (message: string): never => { throw new ConteosIncompatibles(message); };
|
||||
const escapar = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
const miles = (v: number) => v.toLocaleString('es-MX');
|
||||
// A suppressed or unpublished cell is unknown, never zero.
|
||||
function cuenta(filas: Record<string, unknown>[], periodo: string, categoria: string): number | null {
|
||||
const fila = filas.find(f => f['periodo'] === periodo && f['categoria'] === categoria);
|
||||
return fila && fila['suprimido'] === 0 && typeof fila['n'] === 'number' && Number.isSafeInteger(fila['n']) && fila['n'] >= 0 ? fila['n'] : null;
|
||||
}
|
||||
const sumar = (valores: (number | null)[]) => valores.some(v => v === null) ? null : valores.reduce<number>((s, v) => s + v!, 0);
|
||||
|
||||
/** One model per period both responses publish, in chronological order. */
|
||||
export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacientes: IndicadorDatos, tipo: string): ModeloConteos[] {
|
||||
for (const [d, id] of [[examenes, par.examenes], [pacientes, par.pacientes]] as const) {
|
||||
if (d.id !== id || d.contrato !== 'C2' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos) || !Array.isArray(d.filas) || !registro(d['categorias'])) {
|
||||
fail('Los datos no corresponden a los conteos por mastografía y por paciente.');
|
||||
}
|
||||
}
|
||||
const catExamenes = examenes['categorias'] as Record<string, unknown>, catPacientes = pacientes['categorias'] as Record<string, unknown>;
|
||||
const etiqueta = (cat: Record<string, unknown>, id: string) => registro(cat[id]) && typeof cat[id]['etiqueta'] === 'string' ? cat[id]['etiqueta'] as string : id;
|
||||
const color = (id: string) => registro(catExamenes[id]) && typeof catExamenes[id]['color'] === 'string' ? catExamenes[id]['color'] as string : '#8A9199';
|
||||
const ids = Object.keys(par.grupoDe).filter(id => Object.hasOwn(catExamenes, id));
|
||||
const filasIds = [...new Set(Object.values(par.grupoDe))];
|
||||
if (!ids.length || filasIds.some(id => !Object.hasOwn(catPacientes, id))) fail('Las categorías de mastografías y pacientes no coinciden.');
|
||||
const periodos = [...examenes.periodos].filter(p => pacientes.periodos.includes(p)).sort();
|
||||
const filasE = examenes.filas as Record<string, unknown>[], filasP = pacientes.filas as Record<string, unknown>[];
|
||||
return periodos.map(periodo => {
|
||||
const cats = ids.map(id => ({ id, etiqueta: etiqueta(catExamenes, id), color: color(id), n: cuenta(filasE, periodo, id) }));
|
||||
return {
|
||||
periodo, examenes: cats, sinDato: Object.hasOwn(catExamenes, 'SIN_DATO') ? cuenta(filasE, periodo, 'SIN_DATO') : 0,
|
||||
filas: filasIds.map(id => ({ id, etiqueta: etiqueta(catPacientes, id), pacientes: cuenta(filasP, periodo, id),
|
||||
examenes: sumar(cats.filter(c => par.grupoDe[c.id] === id).map(c => c.n)) })),
|
||||
notas: [...new Set([...(examenes.notas ?? []), ...(pacientes.notas ?? [])])],
|
||||
};
|
||||
});
|
||||
}
|
||||
export const totalExamenes = (m: ModeloConteos) => sumar(m.examenes.map(c => c.n));
|
||||
export const razon = (f: FilaConteo) => f.pacientes && f.examenes !== null ? f.examenes / f.pacientes : null;
|
||||
|
||||
/** Exams by category around their total; nothing is drawn when a cell is unknown. */
|
||||
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure {
|
||||
const total = totalExamenes(m);
|
||||
if (!total) return { data: [], layout: {} };
|
||||
const p = c2Theme(tema), n = m.examenes.map(c => c.n!);
|
||||
return { data: [{ type: 'pie', hole: .6, sort: false, direction: 'clockwise', values: n, labels: m.examenes.map(c => escapar(c.etiqueta)),
|
||||
marker: { colors: m.examenes.map(c => c.color), line: { color: p.background, width: 2 } }, textinfo: 'text', textposition: 'inside',
|
||||
text: n.map((v, i) => v / total < .05 ? '' : escapar(m.examenes[i].etiqueta) + '<br>' + percentNumber(100 * v / total) + ' %'),
|
||||
customdata: n.map(v => [miles(v), percentNumber(100 * v / total)]),
|
||||
hovertemplate: `%{label}<br>%{customdata[0]} ${par.unidades.examenes}, %{customdata[1]} %<extra></extra>` }],
|
||||
layout: { autosize: true, height: 400, showlegend: false, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text },
|
||||
annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false, font: { size: 18, color: p.text },
|
||||
text: `<b>${miles(total)}</b><br>${par.unidades.examenes}` }] }, config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
/** Per patient category: patients next to their exams, and how many exams each patient has. */
|
||||
export function barrasConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema), y = m.filas.map(f => escapar(f.etiqueta));
|
||||
const traza = (clave: 'pacientes' | 'examenes', nombre: string, color: string) => ({
|
||||
type: 'bar', orientation: 'h', name: nombre, y, x: m.filas.map(f => f[clave]), marker: { color },
|
||||
text: m.filas.map(f => f[clave] === null ? 'Sin dato' : miles(f[clave]!)), textposition: 'outside', cliponaxis: false,
|
||||
hovertemplate: `%{y}: %{x} ${nombre}<extra></extra>` });
|
||||
const maximo = Math.max(1, ...m.filas.map(f => f.examenes ?? 0), ...m.filas.map(f => f.pacientes ?? 0));
|
||||
return { data: [traza('pacientes', par.unidades.pacientes, '#7A8794'), traza('examenes', par.unidades.examenes, '#C26A2B')],
|
||||
layout: { autosize: true, height: 400, barmode: 'group', bargap: .3, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { t: 16, l: 96, r: 150, b: 56 }, legend: { orientation: 'h', y: -0.14, itemclick: false, itemdoubleclick: false },
|
||||
yaxis: { type: 'category', autorange: 'reversed', automargin: true, fixedrange: true },
|
||||
xaxis: { range: [0, maximo * 1.18], gridcolor: p.grid, zeroline: false, fixedrange: true },
|
||||
annotations: m.filas.map((f, i) => {
|
||||
const r = razon(f);
|
||||
return { x: 1, xref: 'paper', xanchor: 'left', xshift: 8, y: y[i], yref: 'y', showarrow: false, align: 'left', font: { size: 12, color: p.text },
|
||||
text: r === null ? 'Sin razón' : `<b>≈ ${r.toLocaleString('es-MX', { maximumFractionDigits: 1 })}</b> ${par.unidades.porPaciente}` };
|
||||
}) }, config: { displayModeBar: false } };
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
:host { display: block; min-width: 0; padding: var(--issste-space-4); overflow-wrap: anywhere;
|
||||
background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
h2 { font-size: 1.25rem; font-weight: 500; margin-top: 0; }
|
||||
h2 { font-size: 1.5rem; margin-top: 0; }
|
||||
h3 { font-size: 1.25rem; }
|
||||
h4 { font-size: 1rem; margin-bottom: .5rem; }
|
||||
section + section { border-top: 1px solid var(--issste-border); margin-top: var(--issste-space-6); padding-top: var(--issste-space-4); }
|
||||
|
||||
@@ -19,7 +19,7 @@ export class IndicadoresDefinitions {
|
||||
@Input() loading = false;
|
||||
@Input() error = '';
|
||||
readonly retry = output<void>();
|
||||
readonly domainNames: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama' };
|
||||
readonly domainNames: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'CaMa' };
|
||||
readonly periodNames: Record<TipoPeriodo, string> = { semestre: 'Semestral', mes: 'Mensual' };
|
||||
readonly figureDisplayName = figureDisplayName;
|
||||
readonly periodInterpretation = PERIOD_INTERPRETATION;
|
||||
|
||||
@@ -1,18 +1,11 @@
|
||||
import { DimensionEstrato, Dominio, Indicador, IndicadorDatos, PlotlyFigure, Tema, VistaEscenario } from './indicadores.models';
|
||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Theme } from './indicadores-c2-palette';
|
||||
import { percentNumber, shareText } from './indicadores-format';
|
||||
|
||||
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
|
||||
// A C2 distribution with category groups, next to the same categories by one stratum. Unknown cells never become zero.
|
||||
// This boundary is intentionally specific to EU7. Unknown cells never become zero.
|
||||
export const ESTRATO = 'estatus_seguimiento';
|
||||
const SIN_DATO = 'SIN_DATO';
|
||||
// CaCu's EU7 predates the catalog's `escenario` field.
|
||||
const EU7: VistaEscenario = { estrato: ESTRATO, etiqueta: 'escenario clínico' };
|
||||
export function vistaEscenario(dominio: Dominio, indicador: Indicador): VistaEscenario | undefined {
|
||||
if (indicador.escenario) return indicador.escenario;
|
||||
return dominio === 'cacu' && indicador.id === 'cacu_eu7' ? EU7 : undefined;
|
||||
}
|
||||
export const esEu7 = (vista: VistaEscenario) => vista === EU7;
|
||||
export interface Seleccion { grupo?: string; categoria?: string; }
|
||||
export interface Categoria { id: string; etiqueta: string; color: string; grupo: string; }
|
||||
export interface Grupo { id: string; etiqueta: string; color: string; }
|
||||
@@ -71,7 +64,7 @@ function catalogo(data: IndicadorDatos): Categoria[] {
|
||||
/** Validate the common temporal scope before exposing any period's figures. */
|
||||
export function periodosCompatibles(general: IndicadorDatos, escenarios: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] {
|
||||
for (const d of [general, escenarios]) {
|
||||
if (d.id !== general.id || d.contrato !== 'C2' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos)
|
||||
if (d.id !== 'cacu_eu7' || d.contrato !== 'C2' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos)
|
||||
|| new Set(d.periodos).size !== d.periodos.length || d.periodos.some(p => typeof p !== 'string'
|
||||
|| !(tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(p))
|
||||
|| !Array.isArray(d.filas) || d.filas.some(f => !registro(f) || !d.periodos.includes(f['periodo'] as string))) {
|
||||
@@ -87,10 +80,10 @@ export function periodosCompatibles(general: IndicadorDatos, escenarios: Indicad
|
||||
}
|
||||
|
||||
/** Two immutable /datos payloads -> one safe presentation model for a single period. */
|
||||
export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, periodo: string, estrato: DimensionEstrato = ESTRATO): Modelo {
|
||||
export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, periodo: string): Modelo {
|
||||
periodosCompatibles(general, porEscenario, general.tipo_periodo);
|
||||
const valores = porEscenario['valores_estrato'], etiquetas = porEscenario['etiquetas_estrato'];
|
||||
if ((general['estrato'] ?? null) !== null || porEscenario['estrato'] !== estrato || !general.periodos.includes(periodo)
|
||||
if ((general['estrato'] ?? null) !== null || porEscenario['estrato'] !== ESTRATO || !general.periodos.includes(periodo)
|
||||
|| !Array.isArray(valores) || !valores.every(v => typeof v === 'string') || new Set(valores).size !== valores.length
|
||||
|| !registro(etiquetas) || valores.some(v => typeof etiquetas[v] !== 'string')
|
||||
|| [general, porEscenario].some(d => registro(d['filtros']) ? Object.keys(d['filtros']).length > 0 : d['filtros'] != null)) {
|
||||
@@ -219,7 +212,7 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
|
||||
config: { displayModeBar: false } };
|
||||
}
|
||||
/** Selection never changes the original denominator or renormalizes a subset. */
|
||||
export function barras(m: Modelo, sel: Seleccion, tema: Tema, eje = '% de pacientes del escenario con resultado'): PlotlyFigure {
|
||||
export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema);
|
||||
const visibles = sel.categoria ? [sel.categoria] : sel.grupo ? hijas(m, sel.grupo).map(c => c.id) : m.categorias.map(c => c.id);
|
||||
const y = m.escenarios.map(s => escapar(s.etiqueta));
|
||||
@@ -242,7 +235,7 @@ export function barras(m: Modelo, sel: Seleccion, tema: Tema, eje = '% de pacien
|
||||
paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { t: 24, l: 150, r: 72, b: 64 }, showlegend: false,
|
||||
yaxis: { type: 'category', autorange: 'reversed', categoryorder: 'array', categoryarray: y, automargin: true },
|
||||
xaxis: { title: { text: eje }, ticksuffix: ' %', gridcolor: p.grid,
|
||||
xaxis: { title: { text: '% de pacientes del escenario con resultado' }, ticksuffix: ' %', gridcolor: p.grid,
|
||||
range: sel.grupo || sel.categoria ? [0, Math.max(...sumas.filter((v): v is number => v !== null), 1) * 1.35] : [0, 112],
|
||||
tickvals: sel.grupo || sel.categoria ? undefined : [0, 20, 40, 60, 80, 100] },
|
||||
annotations: m.escenarios.map((s, i) => ({ y: y[i], x: sumas[i] ?? 0, xanchor: 'left', xshift: 6, showarrow: false,
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,208 @@
|
||||
// What this module covers: the indicator page and TEA's follow-up over the WebApi's FHIR endpoint. The catalog and
|
||||
// technical sheet from `Measure`, the data rows from `MeasureReport`, the periods from two one-report searches, the
|
||||
// C3r box plot, and the follow-up list and patient summary from `EpisodeOfCare` and `$resumen-tea`; each mapped into
|
||||
// the shapes the page reads and passed through the same checks.
|
||||
// Fixtures: `indicadores-fhir.fixtures.ts`, real responses of the WebApi over its TEA fixture database.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { Bundle, resources } from './fhir';
|
||||
import {
|
||||
cajaDeDatos, datosDeReportes, FhirIndicadoresPeriodos, FhirIndicadoresService, indicadorDeMeasure, Measure, periodoIniciado,
|
||||
periodosDesde, Report,
|
||||
} from './indicadores-fhir';
|
||||
import * as fx from './indicadores-fhir.fixtures';
|
||||
import { c1AlterationFigure } from './indicadores-c1-alteraciones';
|
||||
import { c2Figure } from './indicadores-c2-adapter';
|
||||
import { datosValidos } from './indicadores.service';
|
||||
import { FhirTeaSeguimientoService, mapaDeElectrodos } from './tea-seguimiento-fhir';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
|
||||
const measure = (id: string) => resources(fx.measures).find(m => m.id === id) as Measure;
|
||||
const reports = (bundle: Bundle) => resources(bundle, 'MeasureReport') as Report[];
|
||||
|
||||
describe('Indicadores sobre FHIR', () => {
|
||||
it('el catálogo sale de cada Measure con los ids, contratos, figuras y estratos de la página', () => {
|
||||
// Pins down: ids with underscores, the contract and figures from the extensions, the age stratum of a C1 and none
|
||||
// for a C2 (its stratifier holds the categories). Fails if the catalog stops matching the page's TEA ids.
|
||||
const catalog = resources(fx.measures).map(m => indicadorDeMeasure(m as Measure));
|
||||
const m21 = catalog.find(i => i.id === 'M21_diagnosticados_con_eeg')!;
|
||||
expect(m21).toMatchObject({ contrato: 'C1', figuras: ['fig_c1_barras_edad'], tipos_periodo: ['semestre', 'mes'], estratos: ['grupo_edad'], sentido: 'mayor_mejor' });
|
||||
expect(catalog.find(i => i.id === 'M28_casos_por_estado')).toMatchObject({ contrato: 'C2', estratos: [] });
|
||||
expect(catalog.find(i => i.id === 'M25_dias_mchat_diagnostico')).toMatchObject({ contrato: 'C3r', sentido: 'menor_mejor' });
|
||||
});
|
||||
|
||||
it('los grupos de M30 llegan como filas por alteración y dibujan sus barras', () => {
|
||||
// Pins down: a report's extra groups become one row each under the group's code, labelled by the Measure, and
|
||||
// that is what `fig_c1_barras_alteracion` draws. The report is written here in the WebApi's shape (the fixtures
|
||||
// hold none for M30). Fails if the groups are dropped or renamed on the way, or the figure stops reading them.
|
||||
const m30 = measure('M30-resultado-eeg');
|
||||
const pop = (code: string, count: number) => ({ code: { coding: [{ code }] }, count });
|
||||
const group = (code: string, n: number) => ({ code: { coding: [{ code }] }, population: [pop('denominator', 8), pop('numerator', n)],
|
||||
measureScore: { value: n / 8 } });
|
||||
const codes = (m30.group ?? []).map(g => g.code?.coding?.[0]?.code as string);
|
||||
const report = { resourceType: 'MeasureReport', id: 'M30-resultado-eeg-1', period: { start: '2025-07-01', end: '2025-12-31' },
|
||||
group: codes.map((c, i) => group(c, c === 'TOTAL' ? 4 : i % 3)) } as unknown as Report;
|
||||
const datos = datosValidos(datosDeReportes(m30, [report], 'semestre'), 'M30_resultado_eeg', 'semestre', ['2025-S2']);
|
||||
expect(datos.filas.map(f => f['grupo'])).toEqual(codes);
|
||||
expect(codes).toContain('ritmo_posterior');
|
||||
const result = c1AlterationFigure(datos, { dominio: 'tea', indicador: 'M30_resultado_eeg', figura: 'fig_c1_barras_alteracion',
|
||||
tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] });
|
||||
if (result.status !== 'supported') throw new Error(result.reason);
|
||||
const [trace] = result.figure.data as Record<string, unknown>[];
|
||||
expect(trace['x']).toEqual(['Alguna alteración', 'Ritmo posterior', 'Husos de sueño N2', 'Husos de sueño N3', 'Picos paroxísticos',
|
||||
'Gradiente anteroposterior']);
|
||||
expect((trace['y'] as number[])[0]).toBe(50);
|
||||
});
|
||||
|
||||
it('una proporción da numerador, denominador y porcentaje, y por grupo de edad los códigos de la página', () => {
|
||||
// Pins down: the score becomes a percentage, the age groups `16-23`..., and an empty «Sin dato» stratum is left
|
||||
// out. Fails if the fraction isn't multiplied, the codes keep FHIR's underscore or the empty stratum becomes a bar.
|
||||
const total = datosValidos(datosDeReportes(measure('M21-diagnosticados-con-eeg'), reports(fx.m21Semestres), 'semestre'),
|
||||
'M21_diagnosticados_con_eeg', 'semestre');
|
||||
expect(total.periodos).toEqual(['2025-S1', '2025-S2']);
|
||||
expect(total.filas[0]).toMatchObject({ periodo: '2025-S1', grupo: 'TOTAL', estrato: null, numerador: 2, denominador: 2, valor: 100, suprimido: 0 });
|
||||
const porEdad = datosDeReportes(measure('M21-diagnosticados-con-eeg'), reports(fx.m21Semestres), 'semestre', { estrato: 'grupo_edad' });
|
||||
expect(porEdad['valores_estrato']).toEqual(['16-23', '24-29', '30-36']);
|
||||
expect((porEdad['etiquetas_estrato'] as Record<string, string>)['16-23']).toBe('16 a 23 meses');
|
||||
});
|
||||
|
||||
it('una exclusión del denominador llega como n_excluido', () => {
|
||||
// Pins down: M24's neuropediatrics notes without F84.0 are counted apart. Fails if the exclusion is dropped.
|
||||
const datos = datosDeReportes(measure('M24-confirmacion-diagnostico'), reports(fx.m24Semestres), 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ numerador: 2, denominador: 5, valor: 40, n_excluido: 1 });
|
||||
});
|
||||
|
||||
it('una composición da todas sus categorías, también las de cero, y la página la dibuja', () => {
|
||||
// Pins down: one row per category of the Measure, in its order, with zeros for the absent ones, so the C2 adapter
|
||||
// accepts the partition. Fails if a category with no patients is left out (the page refuses an incomplete one).
|
||||
const datos = datosDeReportes(measure('M29-calidad-eeg'), reports(fx.m29Semestres), 'semestre');
|
||||
const s1 = datos.filas.filter(f => f['periodo'] === '2025-S1');
|
||||
expect(s1.map(f => [f['categoria'], f['n']])).toEqual([['BUENO', 2], ['MALO', 1], ['SIN_ANALIZAR', 0]]);
|
||||
const m28 = datosDeReportes(measure('M28-casos-por-estado'), [reports(fx.m28Semestres)[0]], 'semestre');
|
||||
const figure = c2Figure(m28, { indicador: 'M28_casos_por_estado', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', dominio: 'tea' });
|
||||
expect(figure.status).toBe('supported');
|
||||
});
|
||||
|
||||
it('una duración da mediana, cuartiles y unidad en días, y su caja por periodo', () => {
|
||||
// Pins down: the median and quartile extensions, `dias` (what the KPI card requires) and the box plot built here
|
||||
// instead of by the server. Fails if the quartiles are lost or the box plot stops having one box per period.
|
||||
const datos = datosDeReportes(measure('M25-dias-mchat-diagnostico'), reports(fx.m25Semestres), 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ mediana: 59.5, q1: 58.75, q3: 60.25, n: 2, n_sin_evento: 4, unidad: 'dias' });
|
||||
const caja = cajaDeDatos(datos as IndicadorDatos);
|
||||
expect(caja.data[0]).toMatchObject({ type: 'box', median: datos.filas.filter(f => f['mediana'] !== null).map(f => f['mediana']) });
|
||||
});
|
||||
|
||||
it('los periodos siguen al primero sin huecos y los que no han empezado se descartan', () => {
|
||||
// Pins down: semesters and months counted on from the first report, and none after today. Fails if a year
|
||||
// boundary is crossed wrongly or a future period is offered.
|
||||
expect(periodosDesde('2024-07-01', 'semestre', 3)).toEqual(['2024-S2', '2025-S1', '2025-S2']);
|
||||
expect(periodosDesde('2024-11-01', 'mes', 3)).toEqual(['2024-11', '2024-12', '2025-01']);
|
||||
const today = new Date(2025, 9, 15);
|
||||
expect(periodoIniciado('2025-S2', today)).toBe(true);
|
||||
expect(periodoIniciado('2025-11', today)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Servicios FHIR de indicadores', () => {
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), FhirIndicadoresService, FhirIndicadoresPeriodos] });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => http.verify());
|
||||
|
||||
it('pide los periodos elegidos de una medida a la búsqueda de MeasureReport', async () => {
|
||||
// Pins down: one `Measure` list per domain, and `/MeasureReport?measure=<canonical>&periodo=...`. Fails if the
|
||||
// request leaves the FHIR endpoint or loses the periods asked for.
|
||||
const service = TestBed.inject(FhirIndicadoresService);
|
||||
const answer = firstValueFrom(service.datos('tea', 'M21_diagnosticados_con_eeg', 'semestre', ['2025-S1', '2025-S2']));
|
||||
http.expectOne('/tea/fhir/Measure').flush(fx.measures);
|
||||
const request = http.expectOne(r => r.url === '/tea/fhir/MeasureReport');
|
||||
expect(request.request.params.get('measure')).toBe('https://isssteleon.org/fhir/Measure/M21-diagnosticados-con-eeg');
|
||||
expect(request.request.params.get('periodo')).toBe('2025-S1,2025-S2');
|
||||
request.flush(fx.m21Semestres);
|
||||
expect((await answer).filas.length).toBe(2);
|
||||
});
|
||||
|
||||
it('el inventario de periodos sale de dos búsquedas de un solo reporte', async () => {
|
||||
// Pins down: one report of each type and the search's total, shared by every measure of the domain. Fails if each
|
||||
// measure computes its own periods or every period is evaluated to list them.
|
||||
const periodos = TestBed.inject(FhirIndicadoresPeriodos);
|
||||
periodos.today = () => new Date(2025, 11, 31);
|
||||
const answer = firstValueFrom(periodos.periodos('tea', 'M28_casos_por_estado'));
|
||||
http.expectOne('/tea/fhir/Measure').flush(fx.measures);
|
||||
const semestres = http.expectOne(r => r.params.get('tipo-periodo') === 'semestre');
|
||||
expect(semestres.request.params.get('_count')).toBe('1');
|
||||
semestres.flush({ ...fx.m28Semestres, entry: fx.m28Semestres.entry!.slice(0, 1) });
|
||||
const first = reports(fx.m28Semestres)[0];
|
||||
http.expectOne(r => r.params.get('tipo-periodo') === 'mes').flush({ resourceType: 'Bundle', total: 12,
|
||||
entry: [{ resource: { ...first, period: { start: '2025-01-01', end: '2025-01-31' } } }] });
|
||||
const found = await answer;
|
||||
expect(found.filter(p => p.tipo === 'semestre').map(p => p.periodo)).toEqual(['2025-S2', '2025-S1']);
|
||||
expect(found.filter(p => p.tipo === 'mes').length).toBe(12);
|
||||
expect(await firstValueFrom(periodos.periodos('tea', 'M21_diagnosticados_con_eeg'))).toEqual(found);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Seguimiento de TEA sobre FHIR', () => {
|
||||
let http: HttpTestingController;
|
||||
let service: FhirTeaSeguimientoService;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), FhirTeaSeguimientoService] });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
service = TestBed.inject(FhirTeaSeguimientoService);
|
||||
});
|
||||
afterEach(() => http.verify());
|
||||
|
||||
it('la lista sale de los episodios con sus recursos incluidos y respeta filtros y página', async () => {
|
||||
// Pins down: the window and cut-off as `date`, the filters as search parameters, paging as `_count`/`_offset`,
|
||||
// and each row's age group, M-CHAT, ADOS-2, study EEG and alterations from the included resources. Fails if a
|
||||
// filter is dropped or a column stops coming from its resource.
|
||||
const answer = firstValueFrom(service.consultar({ corte: '2025-12-31', meses: 12, page: 1, page_size: 5, grupo_edad: '16-23 meses', estado_caso: 'completo' }));
|
||||
const list = http.expectOne(r => r.url === '/tea/fhir/EpisodeOfCare');
|
||||
expect(list.request.params.getAll('date')).toEqual(['ge2025-01-01', 'le2025-12-31']);
|
||||
expect(list.request.params.get('grupo-edad')).toBe('16_23');
|
||||
expect(list.request.params.get('status')).toBe('finished');
|
||||
expect(list.request.params.get('_count')).toBe('5');
|
||||
list.flush(fx.episodios);
|
||||
http.expectOne(r => r.url === '/tea/fhir/EpisodeOfCare/$resumen-eeg').flush(fx.resumenEeg);
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
||||
const response = await answer;
|
||||
expect(response.paginacion).toEqual({ page: 1, page_size: 5, total_items: 6, total_pages: 2 });
|
||||
expect(response.items[0]).toMatchObject({ id_seudonimo: 'P-4A59E9D8B4', grupo_edad: '16-23 meses', ultimo_eeg: '2025-05-20', mchat: 12,
|
||||
css_ados2: 7, modulo_ados2: '1', estado_caso: 'completo', alteraciones_eeg: 'anormal', alteraciones: ['ritmo_posterior'], pendientes: [] });
|
||||
expect(response.resumen_eeg).toMatchObject({ normales: 2, anormales: 1, sin_eeg: 3 });
|
||||
expect(response.tipos_alteracion.map(t => t.codigo)).toContain('ritmo_posterior');
|
||||
});
|
||||
|
||||
it('el resumen del paciente arma el ADOS-2, la calidad, las alteraciones y su mapa', async () => {
|
||||
// Pins down: ADOS-2 domains whose totals add up (the page checks it), quality criteria in channels or dB, each
|
||||
// metric's state and effects from the code system, and one map per evaluable metric from its electrodes. Fails if
|
||||
// the summary stops passing the page's checks or a map appears for a metric without electrodes.
|
||||
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
|
||||
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente);
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
||||
const detalle = await answer;
|
||||
expect(detalle.grupo_edad).toBe('16-23 meses');
|
||||
expect(detalle.ados2).toMatchObject({ modulo: '1', css: 7, clasificacion: 'autismo', nivel_css: 'moderado' });
|
||||
expect(detalle.eeg!.calidad).toBe('bueno');
|
||||
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'linea')).toMatchObject({ valor: 3.5, unidad: 'dB' });
|
||||
const ritmo = detalle.eeg!.alteraciones.find(a => a.codigo === 'ritmo_posterior')!;
|
||||
expect(ritmo).toMatchObject({ estado: 'disminuido', valor_z: -4.08 });
|
||||
expect(ritmo.efectos).toContain('Ritmo más lento de lo esperado para la edad.');
|
||||
expect(detalle.eeg!.mapas.map(m => m.codigo)).toEqual(['ritmo_posterior']);
|
||||
});
|
||||
|
||||
it('el mapa toma el valor de cada electrodo y deja en blanco lo que ninguno alcanza', () => {
|
||||
// Pins down: the electrode's own z at its position, regions averaged from the measured electrodes only, and no
|
||||
// value far from every electrode. Fails if the map paints the whole head from a few occipital electrodes.
|
||||
const mapa = mapaDeElectrodos('ritmo_posterior', 'Ritmo posterior', { O1: -2.8, O2: -2.4, Pz: -1.1 });
|
||||
const eje = Array.from({ length: 41 }, (_, i) => Math.round((-1 + i * .05) * 100) / 100);
|
||||
expect(mapa.z[eje.indexOf(-0.75)][eje.indexOf(-0.25)]).not.toBeNull();
|
||||
expect(mapa.z[eje.indexOf(0.75)][eje.indexOf(0)]).toBeNull();
|
||||
expect(mapa.regiones.map(r => r.codigo)).toEqual(['occipital', 'parietal']);
|
||||
expect(mapa.regiones[0].valor_z).toBe(-2.6);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,325 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map, Observable, shareReplay, switchMap } from 'rxjs';
|
||||
import { Bundle, code, Concept, display, extension, extensions, Extension, Resource, resources } from './fhir';
|
||||
import { periodLabel } from './measure-report';
|
||||
import {
|
||||
DatosScope, Dominio, FigureSelection, Indicador, IndicadorDatos, IndicadorMetadatos, PlotlyFigure, requireDominio, TipoPeriodo,
|
||||
} from './indicadores.models';
|
||||
import { catalogoValido, datosParams, datosValidos, figuraPeriodos, figuraValida, IndicadoresService, metadatosValidos } from './indicadores.service';
|
||||
import { AvailablePeriod, IndicadoresPeriodos, periodOrder } from './indicadores-periodos';
|
||||
import { IndicadoresRequests } from './indicadores-requests';
|
||||
|
||||
// The indicator page over the WebApi's FHIR endpoint (`/<domain>/fhir/`): `Measure` for the catalog and the technical
|
||||
// sheet, `MeasureReport` for the data rows. Everything is mapped into the shapes the page already reads, and checked
|
||||
// by the same rules as before.
|
||||
|
||||
interface Population { code?: Concept; count?: number; description?: string; criteria?: { expression?: string } }
|
||||
interface Score { value?: number; unit?: string; extension?: Extension[] }
|
||||
interface Stratum { value?: Concept; population?: Population[]; measureScore?: Score; component?: { code?: Concept; value?: Concept }[] }
|
||||
interface Stratifier { code?: Concept[] | Concept }
|
||||
interface ReportStratifier { code?: Concept[]; stratum?: Stratum[] }
|
||||
interface Group { code?: Concept; population?: Population[]; measureScore?: Score; stratifier?: (Stratifier & ReportStratifier)[] }
|
||||
export interface Measure extends Resource {
|
||||
url?: string; version?: string; name?: string; title?: string; description?: string;
|
||||
scoring?: Concept; subjectCodeableConcept?: Concept; improvementNotation?: Concept; group?: Group[];
|
||||
}
|
||||
export interface Report extends Resource {
|
||||
measure?: string; date?: string; period?: { start: string; end: string }; group?: Group[];
|
||||
}
|
||||
interface Categoria { etiqueta: string; color: string | null; grupo: null }
|
||||
|
||||
const MAX_COUNT = 200;
|
||||
const POPULATION_GROUP: Record<string, string> = {
|
||||
'initial-population': 'poblacion', denominator: 'denominador', numerator: 'numerador',
|
||||
'denominator-exclusion': 'exclusion', 'measure-population-exclusion': 'exclusion', 'measure-observation': 'observacion',
|
||||
};
|
||||
|
||||
// `M21-diagnosticados-con-eeg` <-> `M21_diagnosticados_con_eeg`, the ids the page and its TEA texts use.
|
||||
export const indicadorId = (measureId: string) => measureId.replace(/-/g, '_');
|
||||
const stratifierCode = (s: Stratifier) => code(Array.isArray(s.code) ? s.code[0] : s.code);
|
||||
// Age groups travel as `16_23`; the page names them `16-23`.
|
||||
export const estratoValor = (value: string) => /^\d+_\d+$/.test(value) ? value.replace('_', '-') : value;
|
||||
|
||||
function count(populations: Population[] | undefined, name: string): number | null {
|
||||
const found = populations?.find(p => code(p.code) === name);
|
||||
return found && Number.isSafeInteger(found.count) ? found.count! : null;
|
||||
}
|
||||
function decimal(score: Score | undefined, name: string): number | null {
|
||||
const value = extension(score, name)?.valueDecimal;
|
||||
return typeof value === 'number' ? value : null;
|
||||
}
|
||||
const round1 = (value: number) => Math.round(value * 10) / 10;
|
||||
|
||||
export function categorias(measure: Measure): Record<string, Categoria> {
|
||||
return Object.fromEntries(extensions(measure, 'categoria').flatMap(e => {
|
||||
const codigo = extension(e, 'codigo')?.valueCode, etiqueta = extension(e, 'etiqueta')?.valueString;
|
||||
return codigo && etiqueta ? [[codigo, { etiqueta, color: extension(e, 'color')?.valueString ?? null, grupo: null }]] : [];
|
||||
}));
|
||||
}
|
||||
function contrato(measure: Measure): string {
|
||||
return extension(measure, 'contrato')?.valueCode ?? '';
|
||||
}
|
||||
// The strata a measure can be broken down by. A C2's first stratifier holds its categories, not a stratum.
|
||||
function estratos(measure: Measure): string[] {
|
||||
const all = (measure.group?.[0]?.stratifier ?? []).map(stratifierCode).filter((c): c is string => !!c);
|
||||
return contrato(measure) === 'C2' ? all.slice(1) : all;
|
||||
}
|
||||
|
||||
export function indicadorDeMeasure(measure: Measure): Indicador & Record<string, unknown> {
|
||||
const notation = code(measure.improvementNotation);
|
||||
const vistas = extensions(measure, 'vistas').map(e => e.valueCode).filter((v): v is string => !!v);
|
||||
return {
|
||||
id: indicadorId(measure.id ?? ''),
|
||||
version: measure.version,
|
||||
titulo: measure.title ?? measure.name ?? measure.id ?? '',
|
||||
contrato: contrato(measure),
|
||||
figuras: extensions(measure, 'figuras').map(e => e.valueString).filter((f): f is string => !!f),
|
||||
tipos_periodo: extensions(measure, 'tipos-periodo').map(e => e.valueCode).filter((t): t is TipoPeriodo => t === 'semestre' || t === 'mes'),
|
||||
unidad: code(measure.subjectCodeableConcept) ?? null,
|
||||
sentido: notation === 'increase' ? 'mayor_mejor' : notation === 'decrease' ? 'menor_mejor' : null,
|
||||
estratos: estratos(measure),
|
||||
filtros: [],
|
||||
...(vistas.length ? { vistas } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function metadatosDeMeasure(measure: Measure): IndicadorMetadatos {
|
||||
const unidad = code(measure.subjectCodeableConcept) ?? null;
|
||||
return {
|
||||
id: indicadorId(measure.id ?? ''),
|
||||
version: measure.version,
|
||||
descripcion: measure.description ?? null,
|
||||
ficha: { codigo: (measure.id ?? '').split('-')[0], unidad, definicion: measure.description ?? null },
|
||||
unidad,
|
||||
referencias: [],
|
||||
poblaciones: (measure.group?.[0]?.population ?? []).map(p => ({
|
||||
grupo: POPULATION_GROUP[code(p.code) ?? ''] ?? code(p.code) ?? '',
|
||||
codigo: p.criteria?.expression ?? code(p.code) ?? '',
|
||||
descripcion: p.description ?? '',
|
||||
})),
|
||||
figuras_detalle: [],
|
||||
categorias: categorias(measure),
|
||||
};
|
||||
}
|
||||
|
||||
// FHIR's period end is inclusive; the page's `periodo_fin`, like `dim_periodo`, is the next day.
|
||||
function nextDay(day: string): string {
|
||||
const date = new Date(day + 'T00:00:00Z');
|
||||
date.setUTCDate(date.getUTCDate() + 1);
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
function reporte(report: Report, periodo: string) {
|
||||
const knowledge = extension(report, 'corte-conocimiento')?.valueDateTime;
|
||||
return {
|
||||
periodo,
|
||||
report_id: extension(report, 'reporte-id')?.valueInteger ?? null,
|
||||
periodo_inicio: report.period?.start ?? null,
|
||||
periodo_fin: report.period ? nextDay(report.period.end) : null,
|
||||
fecha_corte: extension(report, 'corte-evento')?.valueDate ?? knowledge?.slice(0, 10) ?? null,
|
||||
generado_en: report.date ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function proporcion(populations: Population[] | undefined, score: Score | undefined) {
|
||||
const numerador = count(populations, 'numerator'), denominador = count(populations, 'denominator');
|
||||
return {
|
||||
suprimido: 0, numerador, denominador,
|
||||
valor: typeof score?.value === 'number' ? round1(score.value * 100) : null,
|
||||
ic_bajo: decimal(score, 'ic-bajo'), ic_alto: decimal(score, 'ic-alto'),
|
||||
n_sin_evento: numerador !== null && denominador !== null ? denominador - numerador : null,
|
||||
n_excluido: count(populations, 'denominator-exclusion') ?? 0,
|
||||
};
|
||||
}
|
||||
function duracion(populations: Population[] | undefined, score: Score | undefined) {
|
||||
return {
|
||||
suprimido: 0,
|
||||
n: count(populations, 'measure-observation') ?? 0,
|
||||
mediana: typeof score?.value === 'number' ? score.value : null,
|
||||
q1: decimal(score, 'q1'), q3: decimal(score, 'q3'),
|
||||
// The units without a value at the cut-off: FHIR's population exclusion.
|
||||
n_sin_evento: count(populations, 'measure-population-exclusion') ?? 0,
|
||||
n_excluido: 0,
|
||||
unidad: 'dias',
|
||||
};
|
||||
}
|
||||
function stratumValue(stratum: Stratum): string | undefined {
|
||||
const value = code(stratum.value);
|
||||
return value === undefined ? undefined : estratoValor(value);
|
||||
}
|
||||
|
||||
// The `/datos` answer for `measure`, from one report per period.
|
||||
export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoPeriodo, scope: DatosScope = {}): IndicadorDatos {
|
||||
const kind = contrato(measure), cats = categorias(measure), estrato = scope.estrato;
|
||||
const grupos = Object.fromEntries((measure.group ?? []).map(g => {
|
||||
const id = code(g.code) ?? 'TOTAL';
|
||||
return [id, id === 'TOTAL' ? 'Total' : display(g.code) ?? id];
|
||||
}));
|
||||
const valores = new Map<string, string>();
|
||||
const filas: Record<string, unknown>[] = [];
|
||||
const periodos: string[] = [];
|
||||
for (const report of reports) {
|
||||
if (!report.period) continue;
|
||||
const periodo = periodLabel(report.period);
|
||||
periodos.push(periodo);
|
||||
for (const group of report.group ?? []) {
|
||||
const grupo = code(group.code) ?? 'TOTAL';
|
||||
if (kind === 'C2') {
|
||||
const counts = new Map((group.stratifier?.[0]?.stratum ?? []).map(s => [code(s.value), s.population?.[0]?.count ?? 0]));
|
||||
Object.keys(cats).forEach((categoria, orden) =>
|
||||
filas.push({ periodo, grupo, estrato: null, categoria, n: counts.get(categoria) ?? 0, orden, suprimido: 0 }));
|
||||
continue;
|
||||
}
|
||||
const row = (populations: Population[] | undefined, score: Score | undefined) =>
|
||||
kind === 'C3r' ? duracion(populations, score) : proporcion(populations, score);
|
||||
if (!estrato) {
|
||||
filas.push({ periodo, grupo, estrato: null, ...row(group.population, group.measureScore) });
|
||||
continue;
|
||||
}
|
||||
const stratifier = group.stratifier?.find(s => code(s.code?.[0]) === estrato);
|
||||
if (!stratifier) throw new Error('Dimensión no admitida');
|
||||
for (const stratum of stratifier.stratum ?? []) {
|
||||
const valor = stratumValue(stratum);
|
||||
// A stratum nobody falls in, like an empty «Sin dato», isn't a bar of its own.
|
||||
if (!valor || !(stratum.population ?? []).some(p => (p.count ?? 0) > 0) && valor === 'sin_dato') continue;
|
||||
valores.set(valor, display(stratum.value) ?? valor);
|
||||
filas.push({ periodo, grupo, estrato: valor, ...row(stratum.population, stratum.measureScore) });
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
id: indicadorId(measure.id ?? ''),
|
||||
titulo: measure.title ?? measure.name ?? '',
|
||||
version: measure.version,
|
||||
contrato: kind,
|
||||
unidad: code(measure.subjectCodeableConcept) ?? '',
|
||||
tipo_periodo: tipo,
|
||||
periodos,
|
||||
estrato: estrato ?? null,
|
||||
...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: Object.fromEntries(valores) } : { valores_estrato: [] }),
|
||||
grupos,
|
||||
categorias: cats,
|
||||
grupos_de_categoria: {},
|
||||
notas: [],
|
||||
reportes: reports.filter(r => r.period).map(r => reporte(r, periodLabel(r.period!))),
|
||||
filas,
|
||||
};
|
||||
}
|
||||
|
||||
// One box per period, from each period's median and quartiles.
|
||||
export function cajaDeDatos(datos: IndicadorDatos): PlotlyFigure {
|
||||
const filas = datos.filas.filter(f => f['grupo'] === 'TOTAL' && f['estrato'] == null && typeof f['mediana'] === 'number');
|
||||
const values = (field: string) => filas.map(f => f[field]);
|
||||
return {
|
||||
data: filas.length ? [{ type: 'box', name: 'Total', x: values('periodo'), q1: values('q1'), median: values('mediana'), q3: values('q3'),
|
||||
lowerfence: values('q1'), upperfence: values('q3') }] : [],
|
||||
layout: { title: { text: String(datos['titulo'] ?? '') }, autosize: true, margin: { l: 60, r: 24, t: 60, b: 60 },
|
||||
yaxis: { title: { text: 'días' }, rangemode: 'tozero' } },
|
||||
};
|
||||
}
|
||||
|
||||
function tipoDe(periodo: string): TipoPeriodo {
|
||||
return periodo.includes('-S') ? 'semestre' : 'mes';
|
||||
}
|
||||
// The `count` periods of `tipo` from the one starting on `start`, in order.
|
||||
export function periodosDesde(start: string, tipo: TipoPeriodo, total: number): string[] {
|
||||
const [year, month] = start.split('-').map(Number);
|
||||
return Array.from({ length: total }, (_, i) => {
|
||||
if (tipo === 'semestre') {
|
||||
const n = (year * 2 + (month >= 7 ? 1 : 0)) + i;
|
||||
return `${Math.floor(n / 2)}-S${n % 2 + 1}`;
|
||||
}
|
||||
const n = year * 12 + month - 1 + i;
|
||||
return `${Math.floor(n / 12)}-${String(n % 12 + 1).padStart(2, '0')}`;
|
||||
});
|
||||
}
|
||||
// A period that hasn't started by `today` has no data to show.
|
||||
export function periodoIniciado(periodo: string, today: Date): boolean {
|
||||
const current = periodOrder(tipoDe(periodo) === 'semestre'
|
||||
? `${today.getFullYear()}-S${today.getMonth() < 6 ? 1 : 2}`
|
||||
: `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}`);
|
||||
return periodOrder(periodo) <= current;
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class FhirMeasures {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly cache = new Map<Dominio, Observable<Measure[]>>();
|
||||
all(dominio: Dominio): Observable<Measure[]> {
|
||||
const domain = requireDominio(dominio);
|
||||
let request = this.cache.get(domain);
|
||||
if (!request) {
|
||||
request = this.http.get<Bundle>(`/${domain}/fhir/Measure`).pipe(
|
||||
map(bundle => resources(bundle, 'Measure') as Measure[]), shareReplay({ bufferSize: 1, refCount: false }));
|
||||
this.cache.set(domain, request);
|
||||
}
|
||||
return request;
|
||||
}
|
||||
one(dominio: Dominio, indicador: string): Observable<Measure> {
|
||||
return this.all(dominio).pipe(map(measures => {
|
||||
const found = measures.find(m => indicadorId(m.id ?? '') === indicador);
|
||||
if (!found) throw new Error('Indicador no publicado');
|
||||
return found;
|
||||
}));
|
||||
}
|
||||
reports(dominio: Dominio, measure: Measure, params: HttpParams): Observable<Bundle> {
|
||||
return this.http.get<Bundle>(`/${requireDominio(dominio)}/fhir/MeasureReport`, { params: params.set('measure', measure.url ?? measure.id ?? '') });
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class FhirIndicadoresService extends IndicadoresService {
|
||||
private readonly measures = inject(FhirMeasures);
|
||||
override catalogo(dominio: Dominio = 'tea') {
|
||||
return this.measures.all(dominio).pipe(map(all => catalogoValido(all.map(indicadorDeMeasure))));
|
||||
}
|
||||
override metadatos(dominio: Dominio, indicador: string) {
|
||||
return this.measures.one(dominio, indicador).pipe(map(m => metadatosValidos(metadatosDeMeasure(m))));
|
||||
}
|
||||
override datos(dominio: Dominio, indicador: string, tipo: TipoPeriodo, periodos?: string[], scope: DatosScope = {}) {
|
||||
datosParams(tipo, periodos, scope);
|
||||
if (scope.filtros?.length) throw new Error('Filtro no admitido');
|
||||
let params = new HttpParams().set('_count', MAX_COUNT);
|
||||
params = periodos ? params.set('periodo', [...new Set(periodos)].join(',')) : params.set('tipo-periodo', tipo);
|
||||
return this.measures.one(dominio, indicador).pipe(
|
||||
switchMap(measure => this.measures.reports(dominio, measure, params).pipe(
|
||||
map(bundle => datosValidos(datosDeReportes(measure, resources(bundle, 'MeasureReport') as Report[], tipo, scope), indicador, tipo, periodos, scope)))));
|
||||
}
|
||||
override figura(selection: FigureSelection) {
|
||||
const dominio = requireDominio(selection.dominio ?? 'tea');
|
||||
const periodos = figuraPeriodos(selection);
|
||||
if (selection.figura !== 'fig_c3r_caja') throw new Error('Figura no disponible');
|
||||
const tipo = selection.tipoPeriodo ?? (periodos ? tipoDe(periodos[0]) : 'semestre');
|
||||
return this.datos(dominio, selection.indicador, tipo, periodos).pipe(map(datos => figuraValida(cajaDeDatos(datos))));
|
||||
}
|
||||
}
|
||||
|
||||
// Every measure of a domain shares its periods (`dim_periodo`, whole years); one report of each type gives the first
|
||||
// period and the search's total how many follow.
|
||||
@Injectable()
|
||||
export class FhirIndicadoresPeriodos extends IndicadoresPeriodos {
|
||||
private readonly measures = inject(FhirMeasures);
|
||||
private readonly queue = inject(IndicadoresRequests);
|
||||
private readonly byDomain = new Map<Dominio, Observable<AvailablePeriod[]>>();
|
||||
today = () => new Date();
|
||||
override periodos(domain: Dominio, id: string): Observable<AvailablePeriod[]> {
|
||||
const dominio = requireDominio(domain);
|
||||
let request = this.byDomain.get(dominio);
|
||||
if (!request) {
|
||||
request = this.measures.one(dominio, id).pipe(
|
||||
switchMap(measure => this.queue.run(() => this.measures.reports(dominio, measure, new HttpParams().set('tipo-periodo', 'semestre').set('_count', 1))).pipe(
|
||||
switchMap(semestres => this.queue.run(() => this.measures.reports(dominio, measure, new HttpParams().set('tipo-periodo', 'mes').set('_count', 1))).pipe(
|
||||
map(meses => [...this.listed(semestres, 'semestre'), ...this.listed(meses, 'mes')]
|
||||
.sort((a, b) => periodOrder(b.periodo) - periodOrder(a.periodo))))))),
|
||||
shareReplay({ bufferSize: 1, refCount: false }));
|
||||
this.byDomain.set(dominio, request);
|
||||
}
|
||||
return request;
|
||||
}
|
||||
private listed(bundle: Bundle, tipo: TipoPeriodo): AvailablePeriod[] {
|
||||
const first = (resources(bundle, 'MeasureReport')[0] as Report | undefined)?.period;
|
||||
if (!first || !bundle.total) return [];
|
||||
const today = this.today();
|
||||
return periodosDesde(first.start, tipo, bundle.total).filter(p => periodoIniciado(p, today)).map(periodo => ({ periodo, tipo }));
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { figureDisplayName } from './indicadores-figure-labels';
|
||||
|
||||
describe('UX-07A nombres de representaciones', () => {
|
||||
it.each([
|
||||
['fig_c1_barras_alteracion', 'Barras por alteración'],
|
||||
['fig_c1_grupos', 'Grupos'],
|
||||
['fig_c1_puntos', 'Puntos'],
|
||||
['fig_c2_apiladas', 'Barras apiladas'],
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// Exact IDs remain the option values and HTTP identities; never infer a type
|
||||
// from a prefix. Unknown options keep a neutral label in publication order.
|
||||
const FIGURE_LABELS: Readonly<Record<string, string>> = {
|
||||
fig_c1_barras_alteracion: 'Barras por alteración',
|
||||
fig_c1_barras_apiladas_edad: 'Barras apiladas por grupo de edad',
|
||||
fig_c1_barras_edad: 'Barras por grupo de edad',
|
||||
fig_c1_dona_edad: 'Dona por grupo de edad',
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { filasDelGrupo, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Color, c2Theme, C2_PALETTE } from './indicadores-c2-palette';
|
||||
import { sortedPeriods } from './indicadores-periodos';
|
||||
import { M28_COMPLETO, M28_EN_PROCESO } from './indicadores-kpi';
|
||||
|
||||
export interface HistoricoFigura {
|
||||
figure: PlotlyFigure;
|
||||
@@ -66,8 +67,9 @@ function banda(periodos: string[], bajo: (number | null)[], alto: (number | null
|
||||
}
|
||||
// Separate rows from what is missing or suppressed; a period is judged by its only row.
|
||||
function serie(data: IndicadorDatos, periodos: string[], valor: (row: Record<string, unknown>) => boolean) {
|
||||
const filas = new Map(data.filas.map(row => [row['periodo'] as string, row]));
|
||||
if (filas.size !== data.filas.length) throw new Error('Filas ambiguas');
|
||||
const delTotal = filasDelGrupo(data, 'TOTAL');
|
||||
const filas = new Map(delTotal.map(row => [row['periodo'] as string, row]));
|
||||
if (filas.size !== delTotal.length) throw new Error('Filas ambiguas');
|
||||
const suprimidos: string[] = [], sinDato: string[] = [];
|
||||
const validas = periodos.map(periodo => {
|
||||
const row = filas.get(periodo);
|
||||
@@ -149,24 +151,24 @@ export function historicoFigura(data: IndicadorDatos, tema: Tema, opciones: Hist
|
||||
if (!figura) throw new Error('Representación no soportada');
|
||||
return { ...figura, suprimidos: figura.suprimidos.map(etiquetaPeriodo), sinDato: figura.sinDato.map(etiquetaPeriodo) };
|
||||
}
|
||||
// The share of cases still in process, from the case-status counts. Cases out of the protocol aren't in the base.
|
||||
// The share of the children in the screening at each period's end who hadn't finished it, from M28's stages.
|
||||
export function enProcesoFigura(data: IndicadorDatos, tema: Tema): HistoricoFigura {
|
||||
const periodos = validar(data);
|
||||
const n = (periodo: string, categoria: string) => {
|
||||
const valor = data.filas.find(f => f['periodo'] === periodo && f['categoria'] === categoria)?.['n'];
|
||||
return numero(valor) ? valor : null;
|
||||
const n = (periodo: string, categorias: readonly string[]) => {
|
||||
const valores = categorias.map(c => data.filas.find(f => f['periodo'] === periodo && f['categoria'] === c)?.['n']);
|
||||
return valores.every(numero) ? (valores as number[]).reduce((s, v) => s + v, 0) : null;
|
||||
};
|
||||
const puntos = periodos.map(periodo => {
|
||||
const proceso = n(periodo, 'EN_PROCESO'), completo = n(periodo, 'COMPLETO');
|
||||
const proceso = n(periodo, M28_EN_PROCESO), completo = n(periodo, [M28_COMPLETO]);
|
||||
return proceso === null || completo === null || proceso + completo === 0 ? null : { proceso, base: proceso + completo };
|
||||
});
|
||||
const layout = ejes(data, periodos, [], tema, 'Porcentaje');
|
||||
return {
|
||||
figure: { data: [{ type: 'scatter', mode: 'lines+markers', name: 'En proceso', x: periodos.map(etiquetaPeriodo), connectgaps: false, line: { color: C2_PALETTE.series[1], width: 2 },
|
||||
y: puntos.map(p => p && Math.round(1000 * p.proceso / p.base) / 10), text: puntos.map(p => p ? `${p.proceso} de ${p.base} casos` : ''),
|
||||
y: puntos.map(p => p && Math.round(1000 * p.proceso / p.base) / 10), text: puntos.map(p => p ? `${p.proceso} de ${p.base} niños` : ''),
|
||||
hovertemplate: '%{x}<br>%{y} % en proceso<br>%{text}<extra></extra>' }],
|
||||
layout: { ...layout, showlegend: false, margin: { ...layout.margin, b: data.tipo_periodo === 'mes' ? 84 : 64 }, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
|
||||
comoLeer: 'De los casos completos o en proceso al cierre de cada periodo, el porcentaje que seguía en proceso. Los que quedaron fuera del protocolo no cuentan.',
|
||||
comoLeer: 'De los niños en el tamizaje al cierre de cada periodo, el porcentaje que todavía no lo completaba con un EEG de buena calidad.',
|
||||
suprimidos: [], sinDato: periodos.filter((_, i) => !puntos[i]).map(etiquetaPeriodo),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -36,6 +36,16 @@ describe('Figuras de histórico', () => {
|
||||
expect(suprimidos).toEqual(['feb 2024']);
|
||||
expect(figure.layout['shapes']).toEqual([expect.objectContaining({ x0: .5, x1: 1.5 })]);
|
||||
});
|
||||
it('C1 con grupos adicionales dibuja la línea del total', () => {
|
||||
// Pins down: a measure that publishes one group per alteration next to its total (TEA's EEG result) gets its
|
||||
// history from the total's row of each period. Fails if the other groups' rows count as a second row of the
|
||||
// period («Filas ambiguas»), or if two rows of the total stop being refused.
|
||||
const grupos = { TOTAL: 'Total', ritmo_posterior: 'Ritmo posterior' };
|
||||
const filas = base.periodos.flatMap(p => [{ ...c1(p, 40), grupo: 'TOTAL' }, { ...c1(p, 10), grupo: 'ritmo_posterior' }]);
|
||||
const data: IndicadorDatos = { ...base, contrato: 'C1', grupos, filas };
|
||||
expect(traza(data, 1).y).toEqual([40, 40, 40]);
|
||||
expect(() => historicoFigura({ ...data, filas: [...filas, { ...c1('2024-01', 5), grupo: 'TOTAL' }] }, 'claro')).toThrow('Filas ambiguas');
|
||||
});
|
||||
it('C1 es una línea que no cruza huecos y su banda tampoco', () => {
|
||||
const data: IndicadorDatos = { ...base, contrato: 'C1', filas: [c1('2024-01', 40), c1('2024-02', null, 1), c1('2024-03', 60)] };
|
||||
const { suprimidos, figure } = historicoFigura(data, 'claro');
|
||||
@@ -62,11 +72,11 @@ describe('Figuras de histórico', () => {
|
||||
expect(etiquetaPeriodo('2024-03')).toBe('mar 2024');
|
||||
expect(etiquetaPeriodo('2024-S2')).toBe('2024 S2');
|
||||
});
|
||||
it('el porcentaje en proceso se calcula sobre completos y en proceso, sin los que quedaron fuera', () => {
|
||||
it('el porcentaje en proceso suma las etapas antes del EEG sobre todos los niños en el tamizaje', () => {
|
||||
const fila = (periodo: string, categoria: string, n: number) => ({ periodo, categoria, n, suprimido: 0 });
|
||||
const { figure } = enProcesoFigura({ ...base, periodos: ['2024-01', '2024-02'], contrato: 'C2', filas: [
|
||||
fila('2024-01', 'COMPLETO', 10), fila('2024-01', 'EN_PROCESO', 30), fila('2024-01', 'FUERA_PROTOCOLO', 99),
|
||||
fila('2024-02', 'COMPLETO', 30), fila('2024-02', 'EN_PROCESO', 10), fila('2024-02', 'FUERA_PROTOCOLO', 99)] }, 'claro');
|
||||
fila('2024-01', 'EEG', 10), fila('2024-01', 'SOLO_MCHAT', 10), fila('2024-01', 'PSICOLOGIA', 10), fila('2024-01', 'NEUROPEDIATRIA', 10),
|
||||
fila('2024-02', 'EEG', 30), fila('2024-02', 'SOLO_MCHAT', 5), fila('2024-02', 'PSICOLOGIA', 5), fila('2024-02', 'NEUROPEDIATRIA', 0)] }, 'claro');
|
||||
expect(figure.data[0]['y']).toEqual([75, 25]);
|
||||
expect(figure.data[0]['x']).toEqual(['ene 2024', 'feb 2024']);
|
||||
});
|
||||
@@ -126,12 +136,12 @@ describe('Pestaña Histórico', () => {
|
||||
it('cada intervalo se consulta una vez y cambiar de tema no vuelve a consultar', () => {
|
||||
abrir();
|
||||
http.expectOne(r => r.url === datosUrl).flush(datos('mes', ['2024-01', '2024-02'])); render();
|
||||
fixture.componentInstance.elegido.set('semestre'); render();
|
||||
fixture.componentInstance.tipo.set('semestre'); render();
|
||||
const semestre = http.expectOne(r => r.url === datosUrl);
|
||||
expect(semestre.request.params.get('periodos')).toBe('2024-S1');
|
||||
semestre.flush(datos('semestre', ['2024-S1'])); render();
|
||||
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('2024 S1 (1 semestre)');
|
||||
fixture.componentInstance.elegido.set('mes'); render();
|
||||
fixture.componentInstance.tipo.set('mes'); render();
|
||||
fixture.componentRef.setInput('tema', 'oscuro'); render();
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
@@ -147,11 +157,11 @@ describe('Pestaña Histórico', () => {
|
||||
c.elegirVentana(5); render();
|
||||
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('ago 2024 a dic 2024 (5 meses)');
|
||||
http.expectNone(() => true);
|
||||
c.elegido.set('semestre'); render();
|
||||
c.tipo.set('semestre'); render();
|
||||
expect(c.ventana()).toBe(0);
|
||||
http.expectOne(r => r.url === datosUrl).flush(datos('semestre', semestres)); render();
|
||||
expect(c.opciones().map(o => o.etiqueta)).toEqual(['Últimos 5 semestres', 'Todos (6 semestres)', 'Personalizado…']);
|
||||
c.elegido.set('mes'); render();
|
||||
c.tipo.set('mes'); render();
|
||||
expect(c.ventana()).toBe(5);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
@@ -163,7 +173,7 @@ describe('Pestaña Histórico', () => {
|
||||
for (const { id } of items) {
|
||||
const c2 = id.startsWith('M28');
|
||||
http.expectOne(r => r.url === `/tea/indicadores/${id}/datos`).flush({ id, contrato: c2 ? 'C2' : 'C3r', tipo_periodo: 'mes', periodos: ['2024-01'],
|
||||
filas: c2 ? [{ periodo: '2024-01', categoria: 'COMPLETO', n: 3, orden: 0, suprimido: 0 }, { periodo: '2024-01', categoria: 'EN_PROCESO', n: 1, orden: 1, suprimido: 0 }]
|
||||
filas: c2 ? [{ periodo: '2024-01', categoria: 'EEG', n: 3, orden: 0, suprimido: 0 }, { periodo: '2024-01', categoria: 'SOLO_MCHAT', n: 1, orden: 1, suprimido: 0 }, { periodo: '2024-01', categoria: 'PSICOLOGIA', n: 0, orden: 2, suprimido: 0 }, { periodo: '2024-01', categoria: 'NEUROPEDIATRIA', n: 0, orden: 3, suprimido: 0 }]
|
||||
: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 5, q1: 2, q3: id.startsWith('M25') ? 100 : 10 }] });
|
||||
}
|
||||
render();
|
||||
@@ -191,10 +201,10 @@ describe('Pestaña Histórico', () => {
|
||||
expect(c.opciones().at(-1)!.etiqueta).toBe('Personalizado (1 mes)');
|
||||
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('feb 2024 (1 mes, elegidos)');
|
||||
// The other granularity keeps its own choice.
|
||||
c.elegido.set('semestre'); render();
|
||||
c.tipo.set('semestre'); render();
|
||||
expect(c.ventana()).toBe(0);
|
||||
http.expectOne(r => r.url === datosUrl).flush(datos_('semestre', ['2024-S1'])); render();
|
||||
c.elegido.set('mes'); render();
|
||||
c.tipo.set('mes'); render();
|
||||
expect(c.ventana()).toBe(-1);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
@@ -37,7 +37,7 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
|
||||
}
|
||||
if (listos && TIEMPOS.includes(panel.item.id)) return [];
|
||||
if (panel.item.id === CASOS && panel.estado === 'listo' && panel.datos) {
|
||||
return [panel, { item: { id: 'en_proceso', titulo: 'Porcentaje de casos en proceso', contrato: 'C1' }, rango: panel.rango, estado: 'listo', figura: enProcesoFigura(panel.datos, tema) }];
|
||||
return [panel, { item: { id: 'en_proceso', titulo: 'Porcentaje de niños en proceso', contrato: 'C1' }, rango: panel.rango, estado: 'listo', figura: enProcesoFigura(panel.datos, tema) }];
|
||||
}
|
||||
return [panel];
|
||||
});
|
||||
@@ -51,9 +51,9 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
|
||||
template: `
|
||||
<div class="controles">
|
||||
<span id="historico-intervalo">Intervalo de análisis</span>
|
||||
<mat-button-toggle-group aria-labelledby="historico-intervalo" hideSingleSelectionIndicator [value]="tipo()" (change)="elegido.set($event.value)">
|
||||
@if (tipos().includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
|
||||
@if (tipos().includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
|
||||
<mat-button-toggle-group aria-labelledby="historico-intervalo" hideSingleSelectionIndicator [value]="tipo()" (change)="tipo.set($event.value)">
|
||||
<mat-button-toggle value="mes">Mensual</mat-button-toggle>
|
||||
<mat-button-toggle value="semestre">Semestral</mat-button-toggle>
|
||||
</mat-button-toggle-group>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Periodos a mostrar</mat-label>
|
||||
@@ -123,13 +123,7 @@ export class IndicadoresHistorico {
|
||||
readonly catalog = input.required<readonly Indicador[]>();
|
||||
readonly tema = input.required<Tema>();
|
||||
readonly active = input(false);
|
||||
// Only the granularities some indicator publishes; monthly first when there is one.
|
||||
readonly tipos = computed(() => (['mes', 'semestre'] as const).filter(tipo => this.catalog().some(item => item.tipos_periodo.includes(tipo))));
|
||||
readonly elegido = signal<TipoPeriodo | undefined>(undefined);
|
||||
readonly tipo = computed<TipoPeriodo>(() => {
|
||||
const elegido = this.elegido(), tipos = this.tipos();
|
||||
return elegido && tipos.includes(elegido) ? elegido : tipos[0] ?? 'mes';
|
||||
});
|
||||
readonly tipo = signal<TipoPeriodo>('mes');
|
||||
// How many of the latest periods to show, per granularity; 0 shows them all.
|
||||
private readonly ventanas = signal<Partial<Record<TipoPeriodo, number>>>({});
|
||||
readonly ventana = computed(() => this.ventanas()[this.tipo()] ?? 0);
|
||||
|
||||
@@ -16,13 +16,10 @@ import { Indicador } from './indicadores.models';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub {}
|
||||
// The period and anchor rules are pinned on CaMa's first three cards (C2, C1, C3r); the fourth follows the same
|
||||
// rules (indicador-kpi-panel.spec.ts covers all four).
|
||||
const KPIS = { ...KPI_BY_DOMAIN, cama: KPI_BY_DOMAIN.cama.slice(0, 3) };
|
||||
describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartida de %s', domain => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController, page: IndicadoresPage;
|
||||
const periods = ['2026-S2', '2026-S1', '2025-S2'];
|
||||
const definitions = KPIS[domain];
|
||||
const definitions = KPI_BY_DOMAIN[domain];
|
||||
const otherDomain = domain === 'cacu' ? 'cama' : 'cacu';
|
||||
const items = [...definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, tipos_periodo: ['semestre'], figuras: ['f', 'g'] })),
|
||||
// Two figures, so every domain keeps an ordinary card whose representation can change.
|
||||
@@ -92,7 +89,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
const ongoing = request(periods[0]);
|
||||
for (const section of ['seguimiento', 'datos', 'resumen', 'datos'] as const) {
|
||||
page.changeSection(section); fixture.detectChanges();
|
||||
for (const req of http.match(r => r.url.endsWith('/seguimiento'))) req.flush({}, { status: 404, statusText: 'Pending' });
|
||||
for (const req of http.match(r => r.url === '/cacu/seguimiento' || r.url === '/tea/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' });
|
||||
expect(page.initialPeriodState()).toBe('loading');
|
||||
expect(ongoing.cancelled).toBe(false);
|
||||
http.expectNone(() => true);
|
||||
@@ -112,7 +109,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
editor().select([periods[2]]); fixture.detectChanges();
|
||||
for (let i = 0; i < 3; i++) for (const section of ['seguimiento', 'datos', 'resumen'] as const) {
|
||||
page.changeSection(section); fixture.detectChanges();
|
||||
for (const req of http.match(r => r.url.endsWith('/seguimiento'))) req.flush({}, { status: 404, statusText: 'Pending' });
|
||||
for (const req of http.match(r => r.url === '/cacu/seguimiento' || r.url === '/tea/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' });
|
||||
expect(page.filters).toBe(state); expect(page.filters!.applied).toBe(applied);
|
||||
expect(editor().selectedPeriods).toEqual([periods[2]]);
|
||||
expect(cards()).toContain(card); expect(card.selectedFigure).toBe('g');
|
||||
@@ -227,7 +224,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
const catalogs = new Map<string, typeof items>([[domain, items]]);
|
||||
for (const target of ['tea', 'cacu', 'cama'] as const) {
|
||||
if (target === domain) continue;
|
||||
const definitions = KPIS[target];
|
||||
const definitions = KPI_BY_DOMAIN[target];
|
||||
const period = own.size === 1 ? '2024-S2' : '2025-S1';
|
||||
own.set(target, period);
|
||||
const catalog = definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, tipos_periodo: ['semestre'], figuras: ['f'] }));
|
||||
|
||||
@@ -48,8 +48,7 @@ describe.each(['cacu', 'cama'] as const)('P0 búsqueda del ancla C2 de %s', doma
|
||||
if (domain === 'cama') {
|
||||
expect(anchor.id).toBe('cama_birads_456_paciente');
|
||||
expect(anchor.title).toBe('Pacientes evaluadas con BI-RADS 4, 5 y 6');
|
||||
expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_tasa_deteccion_histopatologica',
|
||||
'cama_eu38a', 'cama_dias_resultado_diagnostico']);
|
||||
expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico']);
|
||||
} else expect(anchor.id).toBe('cacu_eu7');
|
||||
const run = start(); inventory(); request(periods[0]).flush(data(periods[0]));
|
||||
expect(run.selected()?.periodo).toBe(periods[0]);
|
||||
|
||||
@@ -129,15 +129,7 @@ const DATOS_2025_S2: Record<string, IndicadorDatos> = {
|
||||
|
||||
describe('KPI de CaMa con respuestas reales de WebApi', () => {
|
||||
const applied = { tipo: 'semestre' as const, selection: { mode: 'explicit' as const, periodos: ['2025-S2'] as [string] }, revision: 0 };
|
||||
// The card of each real answer; confirmación and tamizaje a diagnóstico are no longer cards, so theirs is
|
||||
// built from the answer, to keep checking the C1 and C3r rules on real data.
|
||||
const ids = Object.keys(DATOS_2025_S2);
|
||||
const result = (index: number) => {
|
||||
const data = DATOS_2025_S2[ids[index]];
|
||||
const definition = KPI_BY_DOMAIN.cama.find(d => d.id === ids[index])
|
||||
?? { id: data.id, title: data.id, contrato: data.contrato as 'C1' | 'C3r', unit: '' };
|
||||
return kpiResult(data, definition, 'cama', applied);
|
||||
};
|
||||
const result = (index: number) => kpiResult(DATOS_2025_S2[KPI_BY_DOMAIN.cama[index].id], KPI_BY_DOMAIN.cama[index], 'cama', applied);
|
||||
|
||||
it('pacientes evaluadas con BI-RADS 4, 5 y 6: la suma de sus categorías', () => {
|
||||
expect(result(0)).toEqual(expect.objectContaining({ state: 'Disponible', value: 31 }));
|
||||
|
||||
@@ -5,9 +5,7 @@ const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit'
|
||||
const total = { periodo: '2025-S1', grupo: 'TOTAL', estrato: null, suprimido: 0 };
|
||||
// Keep C1 numerical-contract coverage even though CaCu no longer presents a C1 KPI.
|
||||
const definitions = { ...KPI_BY_DOMAIN, cacu: [KPI_BY_DOMAIN.cacu[0],
|
||||
{ id: 'cacu_eu13', title: 'Confirmación', contrato: 'C1', unit: '%' } as KpiDefinition, KPI_BY_DOMAIN.cacu[1]],
|
||||
// One card of each contract, in the C2, C1, C3r order the tests index by.
|
||||
cama: KPI_BY_DOMAIN.cama.slice(0, 3) };
|
||||
{ id: 'cacu_eu13', title: 'Confirmación', contrato: 'C1', unit: '%' } as KpiDefinition, KPI_BY_DOMAIN.cacu[1]] };
|
||||
function data(domain: Dominio, index: number, filas: Record<string, unknown>[]): IndicadorDatos {
|
||||
const d = definitions[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: Object.fromEntries(filas.filter(row => typeof row['categoria'] === 'string').map(row => [row['categoria'], {}])), filas };
|
||||
}
|
||||
@@ -23,6 +21,14 @@ describe.each(['tea', 'cacu', 'cama'] as const)('KPI %s', domain => {
|
||||
expect(result.value).toBe('33.4'); expect(result.info).toContain('2 de 6');
|
||||
expect(run(1, [{ ...total, grupo: c1Group, valor: 0, numerador: 0, denominador: 6 }]).value).toBe('0.0');
|
||||
});
|
||||
it('C1 con grupos adicionales publicados lee la fila de su grupo', () => {
|
||||
// Pins down: the rows of the other groups a measure publishes (one per alteration) don't make the card
|
||||
// unconsolidable; a row of a group nobody published still does. Fails if those rows are mixed into the total.
|
||||
const rows = [{ ...total, grupo: c1Group, valor: 50, numerador: 3, denominador: 6 }, { ...total, grupo: 'ritmo_posterior', valor: 10, numerador: 1, denominador: 6 }];
|
||||
const d = { ...data(domain, 1, rows), grupos: { [c1Group]: 'Total', ritmo_posterior: 'Ritmo posterior' } };
|
||||
expect(kpiResult(d, definitions[domain][1], domain, applied).value).toBe('50.0');
|
||||
expect(kpiResult({ ...d, grupos: { [c1Group]: 'Total' } }, definitions[domain][1], domain, applied).state).toBe('Selección no consolidable');
|
||||
});
|
||||
it('C3r conserva mediana cero y Q1/Q3, sin reglas provisionales en la tarjeta', () => {
|
||||
const result = run(2, [{ ...total, mediana: 0, n: 5, q1: 0, q3: 7, unidad: 'dias' }]);
|
||||
expect(result.value).toBe(0);
|
||||
@@ -62,11 +68,10 @@ it('TEA usa sus cinco indicadores destacados y su grupo C1 es TOTAL', () => {
|
||||
['M23_pacientes_evaluados', 'C2'], ['M24_confirmacion_diagnostico', 'C1'], ['M25_dias_mchat_diagnostico', 'C3r'],
|
||||
['M21_diagnosticados_con_eeg', 'C1'], ['M22_diagnosticados_sin_eeg', 'C1']]);
|
||||
const eeg = data('tea', 3, [{ ...total, grupo: 'TOTAL', valor: 62.3, numerador: 71, denominador: 114 }]);
|
||||
expect(kpiResult(eeg, KPI_BY_DOMAIN.tea[3], 'tea', applied).info).toBe('71 de 114 pacientes con TEA positivo tienen un EEG ligado.');
|
||||
expect(kpiResult(eeg, KPI_BY_DOMAIN.tea[3], 'tea', applied).info).toBe('71 de 114 pacientes con diagnóstico confirmado tienen un EEG de buena calidad.');
|
||||
const d = data('tea', 1, [{ ...total, grupo: 'TOTAL', valor: 50, numerador: 3, denominador: 6 }]);
|
||||
expect(kpiResult(d, KPI_BY_DOMAIN.tea[1], 'tea', applied)).toEqual({ state: 'Disponible', value: '50.0',
|
||||
info: '3 de 6 pacientes con nota médica con diagnóstico CIE-10 F84.0.' });
|
||||
expect(kpiResult(data('tea', 1, [{ ...total, grupo: 'total', valor: 50, numerador: 3, denominador: 6 }]), KPI_BY_DOMAIN.tea[1], 'tea', applied).state)
|
||||
.toBe('Selección no consolidable');
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Dominio, IndicadorDatos } from './indicadores.models';
|
||||
import { Dominio, filasDelGrupo, IndicadorDatos } from './indicadores.models';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { percentNumber } from './indicadores-format';
|
||||
|
||||
@@ -15,9 +15,12 @@ export const CACU_RESULTADO_KPI: KpiDefinition = {
|
||||
// in indicadores_kit, except the C2 patient counts, whose card shows the sum of the categories
|
||||
// (patients), not the distribution. If a TOML title changes, change it here too, until the
|
||||
// cards read the `titulo` that the API already sends.
|
||||
// What only TEA's summary paragraph needs: case status and the time of each screening step.
|
||||
// M28's stages at the period's end: a child finishes the screening with a good EEG; the other stages are in process.
|
||||
export const M28_COMPLETO = 'EEG';
|
||||
export const M28_EN_PROCESO = ['SOLO_MCHAT', 'PSICOLOGIA', 'NEUROPEDIATRIA'];
|
||||
// What only TEA's summary paragraph needs: the children by stage and the time of each screening step.
|
||||
export const KPI_RESUMEN_TEA: KpiDefinition[] = [
|
||||
{ id: 'M28_casos_por_estado', title: 'Casos iniciados', contrato: 'C2', unit: 'casos' },
|
||||
{ id: 'M28_casos_por_estado', title: 'Niños en el tamizaje', contrato: 'C2', unit: 'pacientes' },
|
||||
{ id: 'M26_dias_mchat_ados2', title: 'Tiempo de M-CHAT a ADOS-2', contrato: 'C3r', unit: 'días (mediana)' },
|
||||
{ id: 'M27_dias_ados2_diagnostico', title: 'Tiempo de ADOS-2 a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
|
||||
];
|
||||
@@ -27,9 +30,9 @@ export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
|
||||
{ id: 'M24_confirmacion_diagnostico', title: 'Porcentaje de confirmación diagnóstica', contrato: 'C1', unit: '%' },
|
||||
{ id: 'M25_dias_mchat_diagnostico', title: 'Tiempo de aplicación de M-CHAT (psicología) a diagnóstico positivo', contrato: 'C3r', unit: 'días (mediana)' },
|
||||
{ id: 'M21_diagnosticados_con_eeg', title: 'Porcentaje de pacientes con diagnóstico de TEA con EEG', contrato: 'C1', unit: '%',
|
||||
c1Info: (n, d) => `${n} de ${d} pacientes con TEA positivo tienen un EEG ligado.` },
|
||||
c1Info: (n, d) => `${n} de ${d} pacientes con diagnóstico confirmado tienen un EEG de buena calidad.` },
|
||||
{ id: 'M22_diagnosticados_sin_eeg', title: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG', contrato: 'C1', unit: '%',
|
||||
c1Info: (n, d) => `${n} de ${d} pacientes con TEA positivo no tienen ningún EEG ligado.` },
|
||||
c1Info: (n, d) => `${n} de ${d} pacientes con diagnóstico confirmado no tienen todavía un EEG de buena calidad.` },
|
||||
],
|
||||
cacu: [
|
||||
{ id: 'cacu_eu7', title: 'Pacientes evaluadas', contrato: 'C2', unit: 'pacientes' },
|
||||
@@ -37,10 +40,8 @@ export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
|
||||
],
|
||||
cama: [
|
||||
{ id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 y 6', contrato: 'C2', unit: 'pacientes' },
|
||||
{ id: 'cama_tasa_deteccion_histopatologica', title: 'Tasa de detección histopatológica', contrato: 'C1', unit: '%',
|
||||
c1Info: (n, d) => `${n} de ${d} biopsias con resultado maligno.` },
|
||||
{ id: 'cama_eu38a', title: 'Tiempo de tamizaje a resultado', contrato: 'C3r', unit: 'días (mediana)' },
|
||||
{ id: 'cama_dias_resultado_diagnostico', title: 'Tiempo de resultado a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
|
||||
{ id: 'cama_confirmacion_birads45', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%' },
|
||||
{ id: 'cama_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
|
||||
],
|
||||
};
|
||||
// C1 rows of CaCu/CaMa carry the linkId `total`; TEA's ficha names its single group `TOTAL`.
|
||||
@@ -50,11 +51,6 @@ const C1_INFO: Record<Dominio, (numerador: number, denominador: number) => strin
|
||||
cacu: (n, d) => `${n} de ${d} pacientes con lesión de alto grado o mayor en biopsia.`,
|
||||
cama: (n, d) => `${n} de ${d} mastografías BI-RADS 4 y 5 con reporte de biopsia.`,
|
||||
};
|
||||
const C2_INFO: Record<Dominio, string> = {
|
||||
tea: 'Conteo de pacientes únicos en el periodo.',
|
||||
cacu: 'Pacientes con citología tomada en el periodo.',
|
||||
cama: 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.',
|
||||
};
|
||||
const C3R_INFO: Record<Dominio, (n: number, q1: number, q3: number) => string> = {
|
||||
tea: (n, q1, q3) => `${n} pacientes; Q1 a Q3: ${q1} a ${q3} días.`,
|
||||
cacu: (n, q1, q3) => `${n} citologías; primer cuartil: ${q1} días; tercer cuartil: ${q3} días.`,
|
||||
@@ -76,9 +72,9 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai
|
||||
if (data.periodos.length !== 1 || new Set(data.filas.map(row => row['periodo'])).size > 1) return unscoped;
|
||||
const period = data.periodos[0];
|
||||
if (applied.selection.mode === 'explicit' && (applied.selection.periodos.length !== 1 || applied.selection.periodos[0] !== period)) return unscoped;
|
||||
const rows = data.filas;
|
||||
if (!rows.length) return { state: 'Sin filas utilizables' };
|
||||
const group = definition.contrato === 'C1' ? C1_GROUP[domain] : 'TOTAL';
|
||||
const rows = definition.contrato === 'C1' ? filasDelGrupo(data, group) : data.filas;
|
||||
if (!rows.length) return { state: 'Sin filas utilizables' };
|
||||
if (rows.some(row => row['periodo'] !== period || row['grupo'] !== group || row['estrato'] != null)) return unscoped;
|
||||
if (definition.contrato !== 'C2' && rows.length !== 1) return unscoped;
|
||||
if (rows.some(row => finite(row['suprimido']) && row['suprimido'] !== 0)) return { state: 'Dato oculto por tamaño' };
|
||||
@@ -95,7 +91,7 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai
|
||||
if (!rows.every(row => count(row['n']))) return empty;
|
||||
const value = rows.reduce((sum, row) => sum + (row['n'] as number), 0);
|
||||
if (!count(value)) return empty;
|
||||
return { state: 'Disponible', value, categorias: Object.fromEntries(rows.map(row => [row['categoria'] as string, row['n'] as number])), info: C2_INFO[domain] };
|
||||
return { state: 'Disponible', value, categorias: Object.fromEntries(rows.map(row => [row['categoria'] as string, row['n'] as number])), info: domain === 'cacu' ? 'Pacientes con citología tomada en el periodo.' : 'Conteo de pacientes únicos en el periodo.' };
|
||||
}
|
||||
if (definition.contrato === 'C1') {
|
||||
if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100 || !count(row['numerador']) || !count(row['denominador']) || row['numerador'] > row['denominador']) return empty;
|
||||
|
||||
@@ -44,8 +44,8 @@ describe('UX-04 navegación Angular', () => {
|
||||
const harness = await setup();
|
||||
await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage);
|
||||
load(domain, harness); harness.detectChanges();
|
||||
// Domain switching lives in the App header (app.spec.ts); the page must not add a second one.
|
||||
expect(harness.routeNativeElement!.querySelectorAll('nav.domain-nav a')).toHaveLength(0);
|
||||
// Our shell keeps the domain nav on the page itself, see indicadores-page.html.
|
||||
expect(harness.routeNativeElement!.querySelectorAll('nav.domain-nav a')).toHaveLength(3);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('mantiene la ruta, restaura borradores y reconsulta la aplicación entre TEA/CaCu/CaMa', async () => {
|
||||
|
||||
@@ -10,6 +10,14 @@
|
||||
}
|
||||
</header>
|
||||
@if (!fichaPacienteAbierta()) {
|
||||
<!-- Upstream moved domain switching into its own app shell's header (a
|
||||
dropdown in app.ts/app.html); our shell is shared with other workspace
|
||||
sections (Conectar, Gobernanza) so it stays here instead, same as before. -->
|
||||
<nav aria-label="Dominios de indicadores" class="domain-nav">
|
||||
@for (domain of dominios; track domain) {
|
||||
<a mat-button [routerLink]="['/indicadores', domain]" [attr.aria-current]="dominio === domain ? 'page' : null">{{ domainNavLabels[domain] }}</a>
|
||||
}
|
||||
</nav>
|
||||
<div class="section-tabs" [class.dark-theme]="tema === 'oscuro'" role="tablist" [attr.aria-label]="'Secciones de ' + domainLabels[dominio]" (keydown)="sectionKeydown($event)">
|
||||
@for (section of sections; track section.id) {
|
||||
<button type="button" role="tab" [id]="'tab-' + section.id" [attr.aria-controls]="'panel-' + section.id"
|
||||
@@ -23,7 +31,7 @@
|
||||
@if (!catalogLoading() && filters; as state) {
|
||||
<section class="global-filters" aria-labelledby="global-filters-title" [attr.data-domain]="dominio">
|
||||
<h2 id="global-filters-title" class="section-title">Filtros generales de {{ domainLabels[dominio] }}</h2>
|
||||
<p class="section-description">{{ dominio === 'tea' ? 'Se aplica a las figuras y los indicadores destacados.' : 'Se aplica a los indicadores de oportunidad y las gráficas, salvo las de selección independiente.' }}</p>
|
||||
<p class="section-description">{{ dominio === 'cacu' ? 'La selección se aplica a los indicadores de oportunidad y las gráficas, salvo las que indican selección independiente: Todos con reporte.' : 'La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.' }}</p>
|
||||
<app-indicador-period-filters [state]="state" [types]="filterTypes()" [availability]="availability()" [initialPresentation]="initialPeriodBlocked"
|
||||
(retryAvailability)="retryAvailability()"
|
||||
(edited)="editFilters()" (apply)="applyFilters()" />
|
||||
@@ -48,7 +56,7 @@
|
||||
@if (kpis.length && !initialPeriodBlocked) {
|
||||
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
|
||||
@let resumen = teaResumenPeriodo;
|
||||
<h2 id="kpi-section-title" class="section-title">{{ dominio !== 'tea' ? 'Indicadores de oportunidad' : resumen ? 'Resumen' : 'Indicadores destacados' }}</h2>
|
||||
<h2 id="kpi-section-title" class="section-title">{{ dominio === 'cacu' ? 'Indicadores de oportunidad' : resumen ? 'Resumen' : 'Indicadores destacados' }}</h2>
|
||||
@if (resumen) { <app-tea-resumen-periodo [periodo]="resumen" [paneles]="kpiPanels()" /> }
|
||||
<!-- With the summary the panels keep loading the data, but their cards are not shown. -->
|
||||
<div class="kpi-grid" [class.kpi-grid-oculto]="resumen" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : 0)">
|
||||
@@ -66,7 +74,7 @@
|
||||
|
||||
<section class="graphic-section" aria-labelledby="graphic-section-title">
|
||||
<div class="catalog-heading">
|
||||
<h2 id="graphic-section-title" class="section-title">{{ dominio !== 'tea' ? 'Indicadores clínicos' : 'Indicadores gráficos' }}</h2>
|
||||
<h2 id="graphic-section-title" class="section-title">{{ dominio === 'cacu' ? 'Indicadores clínicos' : 'Indicadores gráficos' }}</h2>
|
||||
@if (!catalogLoading() && !catalogError() && catalog().length) {
|
||||
<p class="catalog-count" role="status">{{ catalogOrder().length }} indicadores publicados</p>
|
||||
}
|
||||
@@ -119,7 +127,7 @@
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@if (conHistorico) {
|
||||
@if (dominio === 'tea') {
|
||||
<section id="panel-historico" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-historico" tabindex="0" [hidden]="activeSection() !== 'historico'">
|
||||
<app-indicadores-historico [dominio]="dominio" [catalog]="catalog()" [tema]="tema" [active]="activeSection() === 'historico'" />
|
||||
</section>
|
||||
|
||||
@@ -4,17 +4,43 @@
|
||||
// The workspace shell clips overflow, so the page scrolls itself.
|
||||
:host { display: block; flex: 1; min-width: 0; min-height: 0; overflow-y: auto; padding: 0 var(--space-6) var(--space-7); }
|
||||
.dashboard { max-width: 1440px; margin: 0 auto; min-width: 0; container: dashboard / inline-size; }
|
||||
h1 { font-family: var(--issste-font-heading); font-size: 1.75rem; font-weight: 500; line-height: 1.25; letter-spacing: 0; margin: .5rem 0; }
|
||||
h1 { font: var(--mat-sys-headline-large); font-family: var(--issste-font-heading); font-weight: 700; margin: .65rem 0; }
|
||||
header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
||||
.domain { color: var(--mat-sys-primary); font: var(--mat-sys-label-large); }
|
||||
// Kept here (not moved to our app shell, see the template comment above the
|
||||
// nav) -- same rules as before upstream relocated its own copy into app.scss.
|
||||
.domain-nav {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--issste-space-2);
|
||||
padding: var(--issste-space-2);
|
||||
justify-content: center;
|
||||
margin: var(--issste-space-4) 0;
|
||||
border-radius: var(--issste-radius);
|
||||
}
|
||||
.domain-nav a {
|
||||
flex: 0 1 6rem;
|
||||
max-width: 10rem;
|
||||
color: var(--issste-text);
|
||||
border: 1px solid var(--issste-border);
|
||||
background: var(--issste-surface);
|
||||
min-height: 44px;
|
||||
border-radius: var(--issste-radius);
|
||||
}
|
||||
.domain-nav a[aria-current='page'] {
|
||||
background: var(--issste-accent);
|
||||
font-weight: 700;
|
||||
text-decoration: none;
|
||||
}
|
||||
@media (max-width: 550px) {
|
||||
.domain-nav { gap: var(--issste-space-2); padding-inline: 0; }
|
||||
}
|
||||
.state { padding: 1.25rem; margin: 0; }
|
||||
.section-title { font-family: var(--issste-font-heading); font-size: 1.25rem; font-weight: 500; line-height: 1.3; margin: 0; overflow-wrap: anywhere; }
|
||||
.section-title { font-family: var(--issste-font-heading); font-size: 1.5rem; line-height: 1.3; margin: 0; overflow-wrap: anywhere; }
|
||||
.section-description { color: var(--issste-text-secondary); margin: var(--issste-space-2) 0 var(--issste-space-4); overflow-wrap: anywhere; }
|
||||
.kpi-section, .graphic-section { min-width: 0; }
|
||||
.graphic-section { margin-top: var(--issste-space-6); padding-top: var(--issste-space-6); border-top: 1px solid var(--issste-border); }
|
||||
.kpi-grid, .catalog-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||
// Every card of a row of cards is as tall as the tallest one.
|
||||
.kpi-grid { grid-auto-rows: 1fr; }
|
||||
.kpi-section .kpi-grid.kpi-grid-oculto { display: none; }
|
||||
.catalog-grid { align-items: stretch; }
|
||||
.reporte-acciones { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); margin-bottom: var(--issste-space-4); }
|
||||
@@ -31,12 +57,10 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
||||
@container dashboard (min-width: 1304px) { .catalog-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
|
||||
@media (max-width: 550px) {
|
||||
h1 { font-size: 1.5rem; }
|
||||
h1 { font-size: var(--mat-sys-headline-medium-size); line-height: var(--mat-sys-headline-medium-line-height); }
|
||||
}
|
||||
|
||||
.global-filters { margin-block: var(--issste-space-4); padding: var(--issste-space-3) var(--issste-space-4); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); min-width: 0; }
|
||||
.global-filters .section-title { font-size: 1rem; }
|
||||
.global-filters .section-description { margin: var(--issste-space-1) 0 var(--issste-space-2); font: var(--mat-sys-body-small); }
|
||||
.global-filters { margin-block: var(--issste-space-6); padding: clamp(.75rem, 2vw, 1.5rem); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); min-width: 0; }
|
||||
|
||||
@container dashboard (min-width: 1000px) { .kpi-grid { grid-template-columns: repeat(min(3, var(--kpi-count)), minmax(0, 1fr)); } }
|
||||
|
||||
@@ -45,9 +69,6 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr));
|
||||
align-items: stretch;
|
||||
}
|
||||
// Cáncer de mama's four cards: one size, four in a row on wide screens and two by two below.
|
||||
@container dashboard (min-width: 600px) { .kpi-section[data-domain='cama'] .kpi-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
@container dashboard (min-width: 1100px) { .kpi-section[data-domain='cama'] .kpi-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); } }
|
||||
|
||||
.section-tabs { display: flex; justify-content: center; flex-wrap: wrap; gap: var(--issste-space-1);
|
||||
border-block-start: 2px solid var(--issste-accent); border-block-end: 1px solid var(--issste-border);
|
||||
|
||||
@@ -136,9 +136,13 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('UX-06B mantiene una sola navegación entre dominios, sin duplicar botones', () => {
|
||||
// The App header owns the domain menu (app.spec.ts); fails if the page brings back its own links.
|
||||
// Our shell has no domain selector of its own (unlike upstream's App),
|
||||
// so the page keeps exactly the one it always had -- not duplicated.
|
||||
// (Needs a render pass first: unlike upstream's trivial "absent" check,
|
||||
// confirming presence requires the template to have actually painted.)
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelectorAll('nav.domain-nav')).toHaveLength(0);
|
||||
expect(fixture.nativeElement.querySelectorAll('nav.domain-nav')).toHaveLength(1);
|
||||
expect(fixture.nativeElement.querySelectorAll('nav.domain-nav a')).toHaveLength(3);
|
||||
expect(cards()).toHaveLength(0);
|
||||
// Constructing the page legitimately initializes its domain catalog.
|
||||
const catalogRequest = http.expectOne('/tea/indicadores');
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { DOCUMENT } from '@angular/common';
|
||||
import { afterEveryRender, afterNextRender, ChangeDetectorRef, Component, DestroyRef, ElementRef, Injector, inject, computed, signal, viewChild, viewChildren } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { ActivatedRoute } from '@angular/router';
|
||||
import { ActivatedRoute, RouterLink } from '@angular/router';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
@@ -11,9 +11,7 @@ import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatSelect, MatSelectModule } from '@angular/material/select';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { catchError, first, map, of, startWith, Subject, switchMap, takeUntil } from 'rxjs';
|
||||
import { Dominio, isDominio, Indicador, Tema } from './indicadores.models';
|
||||
import { vistaEscenario } from './indicadores-eu7-escenario';
|
||||
import { esSocioConteos } from './indicadores-conteos-pareados';
|
||||
import { Dominio, DOMINIOS, isDominio, Indicador, Tema } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
@@ -37,20 +35,17 @@ const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
||||
{ id: 'seguimiento', label: 'Seguimiento' },
|
||||
{ id: 'datos', label: 'Datos y definiciones' },
|
||||
];
|
||||
// Domains with enough periods for their history to say anything.
|
||||
const CON_HISTORICO: readonly Dominio[] = ['tea', 'cama'];
|
||||
const MIN_BUSQUEDA = 5;
|
||||
const HISTORICO_SECTIONS: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]];
|
||||
// Only TEA has enough periods for its history to say anything.
|
||||
const TEA_SECTIONS: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]];
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-page',
|
||||
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
|
||||
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
|
||||
templateUrl: './indicadores-page.html',
|
||||
styleUrl: './indicadores-page.scss',
|
||||
})
|
||||
export class IndicadoresPage {
|
||||
get sections() { return this.conHistorico ? HISTORICO_SECTIONS : SECTIONS; }
|
||||
get conHistorico() { return CON_HISTORICO.includes(this.dominio); }
|
||||
get sections() { return this.dominio === 'tea' ? TEA_SECTIONS : SECTIONS; }
|
||||
readonly activeSection = signal<DashboardSection>('resumen');
|
||||
readonly fichaPacienteAbierta = signal(false);
|
||||
setFichaPacienteAbierta(open: boolean) {
|
||||
@@ -270,12 +265,14 @@ export class IndicadoresPage {
|
||||
private readonly memory = inject(IndicadoresMemory);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly route = inject(ActivatedRoute, { optional: true });
|
||||
readonly dominios = DOMINIOS;
|
||||
dominio: Dominio = 'tea';
|
||||
readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama' };
|
||||
readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'CaMa' };
|
||||
// At the start of the header line.
|
||||
readonly domainTitles: Record<Dominio, string> = { ...this.domainLabels, cacu: 'Cáncer cervicouterino', cama: 'Cáncer de mama' };
|
||||
readonly domainTitles: Record<Dominio, string> = { ...this.domainLabels, cacu: 'Cáncer cervicouterino' };
|
||||
// Short form for the domain-switcher buttons (our shell's own nav, see the
|
||||
// template comment above it) -- `domainLabels`/`domainTitles` are prose-length.
|
||||
readonly domainNavLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' };
|
||||
readonly kpisByDomain = { ...KPI_BY_DOMAIN, tea: [...KPI_BY_DOMAIN.tea, ...KPI_RESUMEN_TEA] };
|
||||
figureApplied(item: Indicador) { return figureApplied(this.dominio, item.id, this.filters!.applied); }
|
||||
independentPeriods(item: Indicador) { return independentFigurePeriods(this.dominio, item.id); }
|
||||
@@ -309,17 +306,13 @@ export class IndicadoresPage {
|
||||
readonly catalog = signal<Indicador[]>([]);
|
||||
// Ids of the indicators to render; null shows the whole catalog.
|
||||
readonly indicatorSelection = signal<string[] | null>(null);
|
||||
// With a few indicators every card is in view; the selector only pays off from MIN_BUSQUEDA on.
|
||||
readonly searchVisible = computed(() => this.catalogOrder().length >= MIN_BUSQUEDA);
|
||||
readonly searchVisible = computed(() => this.catalogOrder().length >= 2);
|
||||
// Stable presentation priority; pins still take precedence in the grid.
|
||||
readonly catalogOrder = computed(() => {
|
||||
const catalog = this.catalog();
|
||||
// The interactive views go first.
|
||||
// A paired partner is drawn on its pair's card, not on one of its own.
|
||||
const ids = catalog.map(item => item.id);
|
||||
const resumen = catalog.filter(item => (!item.vistas || item.vistas.includes('resumen')) && !esSocioConteos(this.dominio, item.id, ids));
|
||||
const primero = (item: Indicador) => !!vistaEscenario(this.dominio, item);
|
||||
return [...resumen.filter(primero), ...resumen.filter(item => !primero(item))];
|
||||
return this.dominio === 'cacu'
|
||||
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')]
|
||||
: catalog.filter(item => !item.vistas || item.vistas.includes('resumen'));
|
||||
});
|
||||
readonly selectedIndicators = computed(() => this.indicatorSelection() ?? this.catalog().map(item => item.id));
|
||||
readonly selectionSummary = computed(() => {
|
||||
|
||||
@@ -9,9 +9,6 @@ import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { Dominio, IndicadorDatos } from './indicadores.models';
|
||||
|
||||
// The period and anchor rules are pinned on CaMa's first three cards (C2, C1, C3r); the fourth follows the same
|
||||
// rules (indicador-kpi-panel.spec.ts covers all four).
|
||||
const KPIS = { ...KPI_BY_DOMAIN, cama: KPI_BY_DOMAIN.cama.slice(0, 3) };
|
||||
describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
@@ -24,12 +21,12 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||
const payload = (id: string, periods: string[]) => ({ id, periodos: periods.map(periodo => ({ periodo, tipo: periodo.includes('-S') ? 'semestre' : 'mes' })) });
|
||||
function catalog(domain: Dominio) {
|
||||
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
|
||||
http.expectOne('/' + domain + '/indicadores').flush(KPIS[domain].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].map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] })));
|
||||
fixture.detectChanges();
|
||||
return http.match(r => r.url.endsWith('/periodos'));
|
||||
}
|
||||
function load(domain: Dominio, periods: string[][]) {
|
||||
catalog(domain).forEach((r, i) => r.flush(payload(KPIS[domain][i].id, periods[i])));
|
||||
catalog(domain).forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN[domain][i].id, periods[i])));
|
||||
fixture.detectChanges();
|
||||
}
|
||||
// Regression assertions below target the original KPI contracts. The added lab
|
||||
@@ -46,7 +43,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); }
|
||||
function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; }
|
||||
function data(index: number, domain: Dominio, period: string, suppressed = false): IndicadorDatos {
|
||||
const d = KPIS[domain][index];
|
||||
const d = KPI_BY_DOMAIN[domain][index];
|
||||
return { id: d.id, contrato: d.contrato, tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period], categorias: { A: {} }, filas: [{
|
||||
periodo: period, grupo: d.contrato === 'C1' ? 'total' : 'TOTAL', estrato: null, categoria: 'A',
|
||||
n: 0, valor: 0, numerador: 0, denominador: 5, mediana: 0, q1: 0, q3: 0, unidad: 'dias', suprimido: suppressed ? 1 : 0,
|
||||
@@ -59,7 +56,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||
if (!requests.length) return resolved;
|
||||
resolved.push(...requests);
|
||||
requests.forEach(r => {
|
||||
const index = KPIS[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos'));
|
||||
const index = KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos'));
|
||||
r.flush(data(index, domain, r.request.params.get('periodos')!, suppressed));
|
||||
});
|
||||
fixture.detectChanges();
|
||||
@@ -67,11 +64,11 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||
}
|
||||
it.each(['cacu', 'cama'] as const)('%s comparte el periodo del ancla aunque otros inventarios difieran y conserva sus ceros', domain => {
|
||||
load(domain, [['2026-S1', '2024-S2', '2025-S2'], ['2025-S1', '2026-S2', '2025-12'], ['2025-S2', '2024-S1']]);
|
||||
const anchor = http.expectOne(r => r.url.endsWith('/' + KPIS[domain][0].id + '/datos'));
|
||||
const anchor = http.expectOne(r => r.url.endsWith('/' + KPI_BY_DOMAIN[domain][0].id + '/datos'));
|
||||
const positive = data(0, domain, '2026-S1'); positive.filas[0]['n'] = 4; anchor.flush(positive); fixture.detectChanges();
|
||||
const requests = flushDatos(domain);
|
||||
expect(requests.map(r => r.request.params.get('periodos'))).toEqual(KPIS[domain].slice(1).map(() => '2026-S1'));
|
||||
expect(panels().map(p => p.temporalReference)).toEqual(KPIS[domain].map(() => '2026-S1'));
|
||||
expect(requests.map(r => r.request.params.get('periodos'))).toEqual(KPI_BY_DOMAIN[domain].slice(1).map(() => '2026-S1'));
|
||||
expect(panels().map(p => p.temporalReference)).toEqual(KPI_BY_DOMAIN[domain].map(() => '2026-S1'));
|
||||
expect(panels().map(p => p.result().value)).toEqual(domain === 'cacu' ? [4, 0] : [4, '0.0', 0]);
|
||||
expect(fixture.componentInstance.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2026-S1'] });
|
||||
expect(fixture.componentInstance.filters!.applied.revision).toBe(1);
|
||||
@@ -115,7 +112,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||
it('error de disponibilidad ofrece reintento sin sustituir la selección y conserva éxitos en caché', () => {
|
||||
const requests = catalog('cacu');
|
||||
requests[0].flush('private', { status: 503, statusText: 'Unavailable' });
|
||||
requests.slice(1).forEach((r, i) => r.flush(payload(KPIS.cacu[i + 1].id, ['2025-S2'])));
|
||||
requests.slice(1).forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN.cacu[i + 1].id, ['2025-S2'])));
|
||||
fixture.detectChanges(); flushDatos('cacu');
|
||||
expect(fixture.componentInstance.initialPeriodState()).toBe('error');
|
||||
expect(panels()).toHaveLength(0);
|
||||
@@ -133,7 +130,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||
const outgoing = catalog('cacu'); const incoming = catalog('cama');
|
||||
expect(outgoing.every(r => r.cancelled)).toBe(true);
|
||||
expect(() => outgoing[0].flush(payload('cacu_eu7', ['2099-S2']))).toThrow();
|
||||
incoming.forEach((r, i) => r.flush(payload(KPIS.cama[i].id, ['2025-S1'])));
|
||||
incoming.forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN.cama[i].id, ['2025-S1'])));
|
||||
fixture.detectChanges(); const requests = flushDatos('cama');
|
||||
expect(requests.every(r => r.request.url.startsWith('/cama/') && r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
||||
expect(editor().options).toEqual(['2025-S1']);
|
||||
|
||||
@@ -45,10 +45,9 @@ describe('Selección de indicadores gráficos', () => {
|
||||
function result() { return (fixture.nativeElement.querySelector('#catalog-search-result') as HTMLElement).textContent!.trim(); }
|
||||
function choose(selection: string[]) { page.changeIndicatorSelection(selection); fixture.detectChanges(); }
|
||||
|
||||
it.each([0, 1, 4, 5, 6])('muestra el selector desde cinco indicadores: catálogo de %i', count => {
|
||||
// Fails if the selector shows for a handful of cards, or stops showing for a long catalog.
|
||||
it.each([0, 1, 2, 5])('muestra el selector desde dos indicadores: catálogo de %i', count => {
|
||||
load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'id-' + i })));
|
||||
expect(!!select()).toBe(count >= 5); expect(cards()).toHaveLength(count);
|
||||
expect(!!select()).toBe(count >= 2); expect(cards()).toHaveLength(count);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('lista todo el catálogo, con todos seleccionados al inicio', () => {
|
||||
|
||||
@@ -37,13 +37,15 @@ describe('Secciones compartidas por dominio', () => {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
|
||||
const root = harness.routeNativeElement!;
|
||||
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
|
||||
expect(tabs.map(t => t.textContent?.trim())).toEqual(domain === 'tea' || domain === 'cama'
|
||||
expect(tabs.map(t => t.textContent?.trim())).toEqual(domain === 'tea'
|
||||
? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']);
|
||||
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(tabs.map((_, i) => String(i === 0)));
|
||||
const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;
|
||||
expect(root.querySelector('[role="tablist"]')?.getAttribute('aria-label')).toContain(page.domainLabels[domain]);
|
||||
// The App header switches domains (see app.html); the page has no switcher of its own.
|
||||
expect(root.querySelector('nav.domain-nav')).toBeNull();
|
||||
// Upstream moved domain selection to its own App shell; ours keeps it on
|
||||
// the page itself (see indicadores-page.html), since our shell is shared
|
||||
// with other workspace sections.
|
||||
expect(root.querySelector('nav.domain-nav')).not.toBeNull();
|
||||
for (const tab of tabs) {
|
||||
const panel = root.querySelector<HTMLElement>('#' + tab.getAttribute('aria-controls'))!;
|
||||
expect(panel.getAttribute('aria-labelledby')).toBe(tab.id);
|
||||
@@ -51,14 +53,25 @@ describe('Secciones compartidas por dominio', () => {
|
||||
}
|
||||
const cards = harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance);
|
||||
tab('seguimiento').click(); harness.detectChanges();
|
||||
http.expectOne(r => r.url === '/' + domain + '/seguimiento').flush({}, { status: 404, statusText: 'Pending' });
|
||||
harness.detectChanges();
|
||||
if (domain === 'cacu' || domain === 'tea') {
|
||||
http.expectOne(r => r.url === '/' + domain + '/seguimiento').flush({}, { status: 404, statusText: 'Pending' });
|
||||
harness.detectChanges();
|
||||
}
|
||||
const tracking = root.querySelector<HTMLElement>('#panel-seguimiento')!;
|
||||
expect(tracking.hidden).toBe(false);
|
||||
expect(tracking.textContent).toContain('El seguimiento aún no está disponible');
|
||||
// Every domain queries its list; until it is published there is no table, only the form.
|
||||
expect(tracking.querySelector('tbody')).toBeNull();
|
||||
expect(tracking.querySelector('input[type=date]')).not.toBeNull();
|
||||
if (domain === 'cacu') {
|
||||
expect(tracking.querySelector('tbody')).toBeNull();
|
||||
expect(tracking.querySelector('input[type=date]')).not.toBeNull();
|
||||
} else if (domain === 'tea') {
|
||||
expect(tracking.querySelector('tbody')).toBeNull();
|
||||
expect(tracking.querySelector('input[type=date]')).not.toBeNull();
|
||||
} else {
|
||||
expect(tracking.querySelectorAll('thead th')).toHaveLength(6);
|
||||
expect(tracking.querySelectorAll('tbody tr')).toHaveLength(1);
|
||||
expect(tracking.querySelector('tbody td')?.getAttribute('colspan')).toBe('6');
|
||||
expect(tracking.querySelectorAll('input,button,select')).toHaveLength(0);
|
||||
}
|
||||
tab('datos').click(); harness.detectChanges();
|
||||
expect(root.querySelector<HTMLElement>('#panel-datos')!.hidden).toBe(false);
|
||||
tab('resumen').click(); harness.detectChanges();
|
||||
|
||||
@@ -6,7 +6,7 @@ const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v ===
|
||||
const escape = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
export function stratifiedCapabilities(item: Indicador): DimensionEstrato[] {
|
||||
return item.contrato === 'C2' && Array.isArray(item.filtros)
|
||||
? (['grupo_edad', 'estatus_seguimiento', 'birads'] as const).filter(d => item.filtros!.some(f => f?.estrato === d
|
||||
? (['grupo_edad', 'estatus_seguimiento'] as const).filter(d => item.filtros!.some(f => f?.estrato === d
|
||||
&& typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0
|
||||
&& f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : [];
|
||||
}
|
||||
|
||||
@@ -5,23 +5,24 @@
|
||||
}
|
||||
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado'">
|
||||
<h2>Seguimiento de {{ domainLabel }}</h2>
|
||||
@if (dominio !== 'cacu' && dominio !== 'tea') {
|
||||
<p>El seguimiento aún no está disponible.</p>
|
||||
<div class="tracking-table" role="region" aria-label="Estructura prevista de seguimiento" tabindex="0">
|
||||
<table>
|
||||
<thead><tr><th scope="col">Paciente / identificación</th><th scope="col">Proceso o etapa</th><th scope="col">Estado</th><th scope="col">Fecha de referencia</th><th scope="col">Responsable</th><th scope="col">Acciones</th></tr></thead>
|
||||
<tbody><tr><td colspan="6">No hay registros de seguimiento disponibles.</td></tr></tbody>
|
||||
</table>
|
||||
</div>
|
||||
} @else {
|
||||
<form (ngSubmit)="apply()">
|
||||
<label>Fecha de corte <input name="corte" type="date" [(ngModel)]="draft.corte" /></label>
|
||||
<label>Ventana de meses <select name="meses" [(ngModel)]="draft.meses">
|
||||
@for (m of [1,3,6,12]; track m) { <option [ngValue]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</option> }
|
||||
</select></label>
|
||||
@if (propio) {
|
||||
<label>{{ dominio === 'tea' ? 'Alteraciones EEG' : 'Estatus de seguimiento' }} <select name="estatus" [(ngModel)]="draft.estatus">
|
||||
<option [ngValue]="undefined">{{ dominio === 'tea' ? 'Todas' : 'Todos' }}</option>
|
||||
@for (s of statuses; track s.codigo) { <option [value]="s.codigo">{{ s.etiqueta }}</option> }
|
||||
</select></label>
|
||||
}
|
||||
@for (f of filtrosTabla; track f.clave) {
|
||||
<label>{{ f.etiqueta }} <select [name]="'filtro-' + f.clave" [attr.name]="'filtro-' + f.clave" [(ngModel)]="filtrosDraft[f.clave]">
|
||||
<option [ngValue]="undefined">Todos</option>
|
||||
@for (o of f.opciones; track o.codigo) { <option [value]="o.codigo">{{ o.etiqueta }}</option> }
|
||||
</select></label>
|
||||
}
|
||||
@if (dominio === 'tea') {
|
||||
<label>Grupo de edad <select name="grupo_edad" [(ngModel)]="draft.grupo_edad">
|
||||
<option [ngValue]="undefined">Todos</option>
|
||||
@@ -91,22 +92,6 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
} @else if (tablaData; as response) {
|
||||
<div class="tracking-table" role="region" aria-label="Lista de seguimiento de demostración" tabindex="0">
|
||||
<table>
|
||||
<caption>Resultados disponibles por paciente</caption>
|
||||
<thead><tr>@for (c of response.columnas; track c.clave) { <th scope="col">{{ c.etiqueta }}</th> }</tr></thead>
|
||||
<tbody>
|
||||
@for (item of response.items; track item['id_seudonimo']) {
|
||||
<tr [attr.data-paciente]="item['id_seudonimo']">
|
||||
@for (c of response.columnas; track c.clave) {
|
||||
<td>{{ valorTabla(item[c.clave]) }}@for (d of detallesTabla(c); track d.clave) { @if (item[d.clave] !== null && item[d.clave] !== undefined) { <small>{{ d.etiqueta }}: {{ valorTabla(item[d.clave]) }}</small> } }</td>
|
||||
}
|
||||
</tr>
|
||||
} @empty { <tr><td [attr.colspan]="response.columnas.length">No hay registros para los filtros aplicados.</td></tr> }
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
} @else if (data; as response) {
|
||||
<div class="tracking-table" role="region" aria-label="Lista de seguimiento de demostración" tabindex="0">
|
||||
<table>
|
||||
@@ -132,4 +117,5 @@
|
||||
<button type="button" [disabled]="response.paginacion.page >= response.paginacion.total_pages" (click)="navigate(response.paginacion.page + 1)">Siguiente</button>
|
||||
</nav>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
:host { display: block; min-width: 0; padding: var(--issste-space-4); overflow-wrap: anywhere;
|
||||
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
h2 { font-size: 1.25rem; font-weight: 500; margin-top: 0; }
|
||||
h2 { font-size: 1.5rem; margin-top: 0; }
|
||||
p { color: var(--issste-text-secondary); }
|
||||
form { display: flex; flex-wrap: wrap; align-items: end; gap: 1rem; margin-bottom: 1rem; }
|
||||
label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; }
|
||||
@@ -31,7 +31,7 @@ tbody tr[data-paciente]:hover { background-color: color-mix(in srgb, var(--issst
|
||||
tbody tr[data-paciente]:focus-within { outline: 2px solid var(--issste-accent); outline-offset: -2px; }
|
||||
.patient-link { min-height: 44px; padding: .35rem .5rem; border: 0; border-radius: var(--issste-radius); background: transparent; color: var(--issste-accent); font: inherit; font-weight: 600; text-align: left; text-decoration: underline; text-underline-offset: .15em; cursor: pointer; }
|
||||
.patient-link:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; }
|
||||
.eeg { display: inline-block; padding: .15rem .6rem; border-radius: var(--issste-radius); border: 1px solid var(--issste-border); font-weight: 600; }
|
||||
.eeg { display: inline-block; padding: .15rem .6rem; border-radius: 999px; border: 1px solid var(--issste-border); font-weight: 600; }
|
||||
.eeg-anormal { border-color: var(--issste-accent); color: var(--issste-accent); }
|
||||
tbody tr.tea-row { cursor: pointer; transition: background-color 120ms ease; }
|
||||
tbody tr.tea-row:hover, tbody tr.tea-row.abierta { background-color: color-mix(in srgb, var(--issste-accent) 7%, transparent); }
|
||||
|
||||
@@ -12,7 +12,6 @@ import { Dominio } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { ALTERACIONES_EEG, ESTADOS_CASO, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service';
|
||||
import { TeaPacienteResumen } from './tea-paciente-resumen';
|
||||
import { SeguimientoColumna, SeguimientoFiltro, SeguimientoTablaResponse, SeguimientoTablaService, SeguimientoValor } from './seguimiento-tabla.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-tracking',
|
||||
@@ -28,7 +27,6 @@ export class IndicadoresTracking implements OnChanges {
|
||||
private readonly service = inject(CacuSeguimientoService);
|
||||
private readonly indicators = inject(IndicadoresService);
|
||||
private readonly teaService = inject(TeaSeguimientoService);
|
||||
private readonly tablaService = inject(SeguimientoTablaService);
|
||||
private readonly destroy = inject(DestroyRef);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private readonly injector = inject(Injector);
|
||||
@@ -37,22 +35,18 @@ export class IndicadoresTracking implements OnChanges {
|
||||
private controlPaciente?: HTMLElement;
|
||||
private readonly requests = new Subject<SeguimientoQuery | null>();
|
||||
private readonly teaRequests = new Subject<SeguimientoQuery | null>();
|
||||
private readonly tablaRequests = new Subject<{ dominio: Dominio; q: SeguimientoQuery } | null>();
|
||||
private initialized = false;
|
||||
private previousDomain?: Dominio;
|
||||
status: 'idle' | 'loading' | 'ready' | 'pending' | 'error' = 'idle';
|
||||
message = '';
|
||||
data?: SeguimientoResponse;
|
||||
teaData?: TeaSeguimientoResponse;
|
||||
// Domains whose list announces its own filters and columns.
|
||||
tablaData?: SeguimientoTablaResponse;
|
||||
filtrosTabla: SeguimientoFiltro[] = [];
|
||||
// One open summary at a time, like an accordion.
|
||||
teaAbierto?: string;
|
||||
statuses: SeguimientoStatus[] = [];
|
||||
private metadataLoaded = false;
|
||||
categories: Record<string, { etiqueta: string; color?: string | null }> = {};
|
||||
draft: SeguimientoQuery = { meses: 3, page: 1, page_size: 50, filtros: {} };
|
||||
draft: SeguimientoQuery = { meses: 3, page: 1, page_size: 50 };
|
||||
private applied: SeguimientoQuery = { ...this.draft };
|
||||
readonly latestStudy = latestStudy;
|
||||
readonly gruposEdad = GRUPOS_EDAD_TEA;
|
||||
@@ -63,8 +57,7 @@ export class IndicadoresTracking implements OnChanges {
|
||||
// Kept from the last answer, so the filter doesn't empty while a query is running.
|
||||
tiposAlteracion: { codigo: string; etiqueta: string }[] = [];
|
||||
get provisional() { return this.data?.reglas.some(r => r.estado === 'provisional'); }
|
||||
get response() { return this.dominio === 'tea' ? this.teaData : this.dominio === 'cacu' ? this.data : this.tablaData; }
|
||||
get propio() { return this.dominio === 'cacu' || this.dominio === 'tea'; }
|
||||
get response() { return this.dominio === 'tea' ? this.teaData : this.data; }
|
||||
constructor() {
|
||||
const failure = (error: unknown, q: SeguimientoQuery) => of({ data: undefined, status: error instanceof HttpErrorResponse && error.status === 404 && q.page === 1 ? 'pending' as const : 'error' as const,
|
||||
message: error instanceof HttpErrorResponse && error.status === 400 ? 'Revisa la fecha, la ventana y los filtros seleccionados.'
|
||||
@@ -100,43 +93,24 @@ export class IndicadoresTracking implements OnChanges {
|
||||
this.draft = { ...this.applied };
|
||||
}
|
||||
});
|
||||
this.tablaRequests.pipe(switchMap(r => r ? defer(() => this.tablaService.consultar(r.dominio, r.q)).pipe(
|
||||
map(data => ({ data, message: '', status: 'ready' as const })), catchError(error => failure(error, r.q))) : of(null)), takeUntilDestroyed(this.destroy)).subscribe(result => {
|
||||
if (!result) return;
|
||||
this.changeDetector.markForCheck();
|
||||
this.status = result.status; this.tablaData = result.data; this.message = result.message;
|
||||
if (result.data) {
|
||||
const data = result.data;
|
||||
this.filtrosTabla = data.filtros_disponibles;
|
||||
const filtros = Object.fromEntries(Object.entries(data.filtros).filter((e): e is [string, string] => e[1] !== null));
|
||||
this.applied = { corte: data.corte, meses: data.ventana.meses, filtros, page: data.paginacion.page, page_size: data.paginacion.page_size };
|
||||
this.draft = { ...this.applied, filtros: { ...filtros } };
|
||||
}
|
||||
});
|
||||
}
|
||||
ngOnChanges() {
|
||||
if (this.previousDomain !== this.dominio) {
|
||||
if (this.pacienteDetalle.estado().tipo !== 'cerrado') this.fichaPacienteAbierta.emit(false);
|
||||
this.pacienteDetalle.cerrar(); this.controlPaciente = undefined;
|
||||
this.previousDomain = this.dominio; this.requests.next(null); this.teaRequests.next(null); this.tablaRequests.next(null);
|
||||
this.data = undefined; this.teaData = undefined; this.tablaData = undefined; this.filtrosTabla = [];
|
||||
this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50, filtros: {} }; this.applied = { ...this.draft };
|
||||
this.previousDomain = this.dominio; this.requests.next(null); this.teaRequests.next(null); this.data = undefined; this.teaData = undefined;
|
||||
this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50 }; this.applied = { ...this.draft };
|
||||
}
|
||||
if (this.dominio === 'cacu' && this.active && !this.initialized) { this.initialized = true; this.load(this.applied); }
|
||||
if (this.dominio === 'tea' && this.active && !this.initialized) { this.initialized = true; this.statuses = ALTERACIONES_EEG; this.load(this.applied); }
|
||||
if (!this.propio && this.active && !this.initialized) { this.initialized = true; this.load(this.applied); }
|
||||
}
|
||||
private load(q: SeguimientoQuery) {
|
||||
if (this.dominio !== 'cacu' && this.dominio !== 'tea') return;
|
||||
if (!validSeguimientoQuery(q)) { this.message = 'Revisa la fecha, la ventana y el tamaño de página (1 a 200).'; return; }
|
||||
this.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.tablaData = undefined; this.applied = { ...q };
|
||||
if (this.dominio === 'tea') this.teaRequests.next(q);
|
||||
else if (this.dominio === 'cacu') this.requests.next(q);
|
||||
else this.tablaRequests.next({ dominio: this.dominio, q });
|
||||
this.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.applied = { ...q };
|
||||
(this.dominio === 'tea' ? this.teaRequests : this.requests).next(q);
|
||||
}
|
||||
apply() { this.load({ ...this.draft, filtros: Object.fromEntries(Object.entries(this.draft.filtros ?? {}).filter(([, v]) => v)), page: 1 }); }
|
||||
valorTabla(v: SeguimientoValor | undefined) { return v === null || v === undefined || v === '' ? 'No disponible' : typeof v === 'number' ? v.toLocaleString('es-MX') : v; }
|
||||
detallesTabla(c: SeguimientoColumna) { return c.detalles ?? []; }
|
||||
get filtrosDraft() { return this.draft.filtros ??= {}; }
|
||||
apply() { this.load({ ...this.draft, page: 1 }); }
|
||||
retry() { this.load(this.applied); }
|
||||
navigate(page: number) {
|
||||
if (!this.response || page < 1 || page > this.response.paginacion.total_pages) return;
|
||||
|
||||
@@ -18,13 +18,8 @@ export interface Indicador {
|
||||
filtros?: IndicadorFiltro[];
|
||||
// Tabs that show it; without this field, all of them.
|
||||
vistas?: string[];
|
||||
// Interactive donut and bars by one stratum, like CaCu's EU7.
|
||||
escenario?: VistaEscenario;
|
||||
}
|
||||
export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado' | 'birads';
|
||||
export const DIMENSIONES_ESTRATO: readonly DimensionEstrato[] = ['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado', 'birads'];
|
||||
// `etiqueta` names one value of the stratum in lower case, as in «por escenario clínico».
|
||||
export interface VistaEscenario { estrato: DimensionEstrato; etiqueta: string; }
|
||||
export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado';
|
||||
export interface IndicadorFiltro { estrato: string; etiqueta: string; valores: { valor: string; etiqueta: string }[]; }
|
||||
export interface DatosScope { estrato?: DimensionEstrato; filtros?: readonly string[]; }
|
||||
export interface EstratoTotal { periodo: string; grupo: string; estrato: string; n: number | null; suprimido: 0 | 1; }
|
||||
@@ -68,6 +63,14 @@ export interface PlotlyFigure {
|
||||
export type Tema = 'claro' | 'oscuro';
|
||||
export interface FigureSelection { dominio?: Dominio; tipoPeriodo?: TipoPeriodo; indicador: string; figura: string; tema: Tema; periodos?: string[]; }
|
||||
|
||||
// A measure may publish more groups next to `group` (TEA's EEG result: one per alteration). The rows without those
|
||||
// of the other published groups; a row of a group nobody published stays, for the caller to refuse.
|
||||
export function filasDelGrupo(data: IndicadorDatos, group: string): Record<string, unknown>[] {
|
||||
const published = data['grupos'];
|
||||
const others = new Set(Object.keys(published && typeof published === 'object' ? published : {}).filter(id => id !== group));
|
||||
return others.size ? data.filas.filter(row => !others.has(row['grupo'] as string)) : data.filas;
|
||||
}
|
||||
|
||||
export function parsePeriodos(value: string, tipo: TipoPeriodo = 'semestre'): string[] | null {
|
||||
if (tipo !== 'semestre' && tipo !== 'mes') return null;
|
||||
const parts = value.split(',').map(part => part.trim());
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { DatosScope, DIMENSIONES_ESTRATO, DimensionEstrato, Dominio, IndicadorDatos, IndicadorMetadatos, FigureSelection, Indicador, parsePeriodos, PlotlyFigure, requireDominio } from './indicadores.models';
|
||||
import { DatosScope, Dominio, IndicadorDatos, IndicadorMetadatos, FigureSelection, Indicador, parsePeriodos, PlotlyFigure, requireDominio, TipoPeriodo } from './indicadores.models';
|
||||
|
||||
function record(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
@@ -11,102 +11,116 @@ export class IndicadoresService {
|
||||
private readonly http = inject(HttpClient);
|
||||
catalogo(dominio: Dominio = 'tea') {
|
||||
const domain = requireDominio(dominio);
|
||||
return this.http.get<unknown>(`/${domain}/indicadores`).pipe(map(value => {
|
||||
if (!Array.isArray(value) || !value.every(item => record(item)
|
||||
&& typeof item['id'] === 'string' && item['id'].trim().length > 0 && typeof item['titulo'] === 'string'
|
||||
&& typeof item['contrato'] === 'string' && Array.isArray(item['figuras'])
|
||||
&& (item['version'] === undefined || typeof item['version'] === 'string')
|
||||
&& item['figuras'].every((figure: unknown) => typeof figure === 'string' && figure.trim().length > 0)
|
||||
&& new Set(item['figuras']).size === item['figuras'].length
|
||||
&& Array.isArray(item['tipos_periodo']) && item['tipos_periodo'].length > 0
|
||||
&& item['tipos_periodo'].every((tipo: unknown) => tipo === 'semestre' || tipo === 'mes')
|
||||
&& new Set(item['tipos_periodo']).size === item['tipos_periodo'].length
|
||||
&& (item['escenario'] === undefined || record(item['escenario']) && typeof item['escenario']['etiqueta'] === 'string'
|
||||
&& DIMENSIONES_ESTRATO.includes(item['escenario']['estrato'] as DimensionEstrato)))) {
|
||||
throw new Error('Respuesta de catálogo inválida');
|
||||
}
|
||||
if (new Set(value.map(item => item['id'])).size !== value.length) throw new Error('IDs de catálogo duplicados');
|
||||
return value as Indicador[];
|
||||
}));
|
||||
return this.http.get<unknown>(`/${domain}/indicadores`).pipe(map(catalogoValido));
|
||||
}
|
||||
metadatos(dominio: Dominio, indicador: string) {
|
||||
return this.http.get<unknown>(`/${requireDominio(dominio)}/indicadores/${encodeURIComponent(indicador)}/metadatos`).pipe(map(value => {
|
||||
if (!record(value)) throw new Error('Metadatos inválidos');
|
||||
const description = value['descripcion'];
|
||||
if (description !== undefined && description !== null && typeof description !== 'string') throw new Error('Metadatos inválidos');
|
||||
const ficha = value['ficha'];
|
||||
if (ficha !== undefined && ficha !== null) {
|
||||
if (!record(ficha)) throw new Error('Metadatos inválidos');
|
||||
for (const field of ['codigo', 'para', 'unidad', 'pregunta', 'definicion', 'nota']) {
|
||||
const content = ficha[field];
|
||||
if (content !== undefined && content !== null && typeof content !== 'string') throw new Error('Metadatos inválidos');
|
||||
}
|
||||
}
|
||||
for (const field of ['referencias', 'poblaciones']) {
|
||||
const list = value[field];
|
||||
if (list !== undefined && list !== null && (!Array.isArray(list) || !list.every(v => record(v) && (field === 'referencias'
|
||||
? typeof v['tipo'] === 'string' && typeof v['etiqueta'] === 'string' && (v['ref'] === null || typeof v['ref'] === 'string')
|
||||
: typeof v['grupo'] === 'string' && typeof v['codigo'] === 'string' && typeof v['descripcion'] === 'string')))) throw new Error('Metadatos inválidos');
|
||||
}
|
||||
const figureDetails = value['figuras_detalle'];
|
||||
if (figureDetails !== undefined && figureDetails !== null && (!Array.isArray(figureDetails) || !figureDetails.every(v => record(v)
|
||||
&& typeof v['figura'] === 'string' && v['figura'].trim().length > 0
|
||||
&& (v['descripcion'] === null || typeof v['descripcion'] === 'string')
|
||||
&& (v['como_leer'] === null || Array.isArray(v['como_leer']) && v['como_leer'].every(line => typeof line === 'string'))))) {
|
||||
throw new Error('Metadatos inválidos');
|
||||
}
|
||||
if (Array.isArray(figureDetails) && new Set(figureDetails.map(item => (item as Record<string, unknown>)['figura'])).size !== figureDetails.length) {
|
||||
throw new Error('Metadatos inválidos');
|
||||
}
|
||||
return value as IndicadorMetadatos;
|
||||
}));
|
||||
return this.http.get<unknown>(`/${requireDominio(dominio)}/indicadores/${encodeURIComponent(indicador)}/metadatos`).pipe(map(metadatosValidos));
|
||||
}
|
||||
datos(dominio: Dominio, indicador: string, tipo: 'semestre' | 'mes', periodos?: string[], scope: DatosScope = {}) {
|
||||
datos(dominio: Dominio, indicador: string, tipo: TipoPeriodo, periodos?: string[], scope: DatosScope = {}) {
|
||||
const domain = requireDominio(dominio);
|
||||
if (periodos && (!periodos.length || parsePeriodos(periodos.join(','), tipo) === null)) {
|
||||
throw new Error('Periodos inválidos');
|
||||
}
|
||||
let params = new HttpParams();
|
||||
if (scope.estrato) {
|
||||
if (!DIMENSIONES_ESTRATO.includes(scope.estrato)) throw new Error('Dimensión no admitida');
|
||||
params = params.set('estrato', scope.estrato);
|
||||
}
|
||||
if (scope.filtros?.length) params = params.set('filtro', scope.filtros.join(','));
|
||||
if (periodos) params = params.set('periodos', [...new Set(periodos)].join(','));
|
||||
return this.http.get<unknown>(`/${domain}/indicadores/${encodeURIComponent(indicador)}/datos`, { params }).pipe(map(value => {
|
||||
if (!record(value) || value['id'] !== indicador || typeof value['contrato'] !== 'string'
|
||||
|| value['tipo_periodo'] !== tipo
|
||||
|| !Array.isArray(value['periodos']) || !value['periodos'].every(p => typeof p === 'string')
|
||||
|| !Array.isArray(value['filas']) || !value['filas'].every(record)
|
||||
|| (value['notas'] !== undefined && (!Array.isArray(value['notas']) || !value['notas'].every(n => typeof n === 'string')))) {
|
||||
throw new Error('Respuesta de datos inválida');
|
||||
}
|
||||
const publishedPeriods = value['periodos'] as string[];
|
||||
if ((value['estrato'] ?? undefined) !== scope.estrato) throw new Error('Dimensión recibida distinta de la solicitada');
|
||||
if ((periodos && publishedPeriods.some(p => !periodos.includes(p)))
|
||||
|| value['filas'].some(row => typeof row['periodo'] !== 'string' || !publishedPeriods.includes(row['periodo']))) {
|
||||
throw new Error('Los datos recibidos no corresponden a los periodos solicitados');
|
||||
}
|
||||
return value as unknown as IndicadorDatos;
|
||||
}));
|
||||
const params = datosParams(tipo, periodos, scope);
|
||||
return this.http.get<unknown>(`/${domain}/indicadores/${encodeURIComponent(indicador)}/datos`, { params })
|
||||
.pipe(map(value => datosValidos(value, indicador, tipo, periodos, scope)));
|
||||
}
|
||||
figura(selection: FigureSelection) {
|
||||
const dominio = requireDominio(selection.dominio ?? 'tea');
|
||||
if (selection.periodos !== undefined) {
|
||||
if (!selection.periodos.length) throw new Error('Selección explícita vacía');
|
||||
const text = selection.periodos.join(',');
|
||||
const tipos = selection.tipoPeriodo ? [selection.tipoPeriodo] : (['semestre', 'mes'] as const);
|
||||
if (!tipos.some(tipo => parsePeriodos(text, tipo) !== null)) {
|
||||
throw new Error('Periodos inválidos o de tipos mezclados');
|
||||
}
|
||||
}
|
||||
let params = new HttpParams().set('tema', selection.tema);
|
||||
if (selection.periodos?.length) params = params.set('periodos', [...new Set(selection.periodos.map(periodo => periodo.trim()))].join(','));
|
||||
const periodos = figuraPeriodos(selection);
|
||||
if (periodos) params = params.set('periodos', periodos.join(','));
|
||||
const url = `/${dominio}/indicadores/${encodeURIComponent(selection.indicador)}/figuras/${encodeURIComponent(selection.figura)}`;
|
||||
return this.http.get<unknown>(url, { params }).pipe(map(value => {
|
||||
if (!record(value) || !Array.isArray(value['data']) || !value['data'].every(record)
|
||||
|| !record(value['layout'])) throw new Error('Respuesta de figura inválida');
|
||||
return value as unknown as PlotlyFigure;
|
||||
}));
|
||||
return this.http.get<unknown>(url, { params }).pipe(map(figuraValida));
|
||||
}
|
||||
}
|
||||
|
||||
export function catalogoValido(value: unknown): Indicador[] {
|
||||
if (!Array.isArray(value) || !value.every(item => record(item)
|
||||
&& typeof item['id'] === 'string' && item['id'].trim().length > 0 && typeof item['titulo'] === 'string'
|
||||
&& typeof item['contrato'] === 'string' && Array.isArray(item['figuras'])
|
||||
&& (item['version'] === undefined || typeof item['version'] === 'string')
|
||||
&& item['figuras'].every((figure: unknown) => typeof figure === 'string' && figure.trim().length > 0)
|
||||
&& new Set(item['figuras']).size === item['figuras'].length
|
||||
&& Array.isArray(item['tipos_periodo']) && item['tipos_periodo'].length > 0
|
||||
&& item['tipos_periodo'].every((tipo: unknown) => tipo === 'semestre' || tipo === 'mes')
|
||||
&& new Set(item['tipos_periodo']).size === item['tipos_periodo'].length)) {
|
||||
throw new Error('Respuesta de catálogo inválida');
|
||||
}
|
||||
if (new Set(value.map(item => item['id'])).size !== value.length) throw new Error('IDs de catálogo duplicados');
|
||||
return value as Indicador[];
|
||||
}
|
||||
export function metadatosValidos(value: unknown): IndicadorMetadatos {
|
||||
if (!record(value)) throw new Error('Metadatos inválidos');
|
||||
const description = value['descripcion'];
|
||||
if (description !== undefined && description !== null && typeof description !== 'string') throw new Error('Metadatos inválidos');
|
||||
const ficha = value['ficha'];
|
||||
if (ficha !== undefined && ficha !== null) {
|
||||
if (!record(ficha)) throw new Error('Metadatos inválidos');
|
||||
for (const field of ['codigo', 'para', 'unidad', 'pregunta', 'definicion', 'nota']) {
|
||||
const content = ficha[field];
|
||||
if (content !== undefined && content !== null && typeof content !== 'string') throw new Error('Metadatos inválidos');
|
||||
}
|
||||
}
|
||||
for (const field of ['referencias', 'poblaciones']) {
|
||||
const list = value[field];
|
||||
if (list !== undefined && list !== null && (!Array.isArray(list) || !list.every(v => record(v) && (field === 'referencias'
|
||||
? typeof v['tipo'] === 'string' && typeof v['etiqueta'] === 'string' && (v['ref'] === null || typeof v['ref'] === 'string')
|
||||
: typeof v['grupo'] === 'string' && typeof v['codigo'] === 'string' && typeof v['descripcion'] === 'string')))) throw new Error('Metadatos inválidos');
|
||||
}
|
||||
const figureDetails = value['figuras_detalle'];
|
||||
if (figureDetails !== undefined && figureDetails !== null && (!Array.isArray(figureDetails) || !figureDetails.every(v => record(v)
|
||||
&& typeof v['figura'] === 'string' && v['figura'].trim().length > 0
|
||||
&& (v['descripcion'] === null || typeof v['descripcion'] === 'string')
|
||||
&& (v['como_leer'] === null || Array.isArray(v['como_leer']) && v['como_leer'].every(line => typeof line === 'string'))))) {
|
||||
throw new Error('Metadatos inválidos');
|
||||
}
|
||||
if (Array.isArray(figureDetails) && new Set(figureDetails.map(item => (item as Record<string, unknown>)['figura'])).size !== figureDetails.length) {
|
||||
throw new Error('Metadatos inválidos');
|
||||
}
|
||||
return value as IndicadorMetadatos;
|
||||
}
|
||||
// The `/datos` query; throws on a period list or dimension the contract doesn't admit.
|
||||
export function datosParams(tipo: TipoPeriodo, periodos?: string[], scope: DatosScope = {}) {
|
||||
if (periodos && (!periodos.length || parsePeriodos(periodos.join(','), tipo) === null)) {
|
||||
throw new Error('Periodos inválidos');
|
||||
}
|
||||
let params = new HttpParams();
|
||||
if (scope.estrato) {
|
||||
if (!['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado'].includes(scope.estrato)) throw new Error('Dimensión no admitida');
|
||||
params = params.set('estrato', scope.estrato);
|
||||
}
|
||||
if (scope.filtros?.length) params = params.set('filtro', scope.filtros.join(','));
|
||||
if (periodos) params = params.set('periodos', [...new Set(periodos)].join(','));
|
||||
return params;
|
||||
}
|
||||
export function datosValidos(value: unknown, indicador: string, tipo: TipoPeriodo, periodos?: string[], scope: DatosScope = {}): IndicadorDatos {
|
||||
if (!record(value) || value['id'] !== indicador || typeof value['contrato'] !== 'string'
|
||||
|| value['tipo_periodo'] !== tipo
|
||||
|| !Array.isArray(value['periodos']) || !value['periodos'].every(p => typeof p === 'string')
|
||||
|| !Array.isArray(value['filas']) || !value['filas'].every(record)
|
||||
|| (value['notas'] !== undefined && (!Array.isArray(value['notas']) || !value['notas'].every(n => typeof n === 'string')))) {
|
||||
throw new Error('Respuesta de datos inválida');
|
||||
}
|
||||
const publishedPeriods = value['periodos'] as string[];
|
||||
if ((value['estrato'] ?? undefined) !== scope.estrato) throw new Error('Dimensión recibida distinta de la solicitada');
|
||||
if ((periodos && publishedPeriods.some(p => !periodos.includes(p)))
|
||||
|| value['filas'].some(row => typeof row['periodo'] !== 'string' || !publishedPeriods.includes(row['periodo']))) {
|
||||
throw new Error('Los datos recibidos no corresponden a los periodos solicitados');
|
||||
}
|
||||
return value as unknown as IndicadorDatos;
|
||||
}
|
||||
// The figure's explicit periods, trimmed and unique; throws on an empty list or mixed period types.
|
||||
export function figuraPeriodos(selection: FigureSelection): string[] | undefined {
|
||||
if (selection.periodos !== undefined) {
|
||||
if (!selection.periodos.length) throw new Error('Selección explícita vacía');
|
||||
const text = selection.periodos.join(',');
|
||||
const tipos = selection.tipoPeriodo ? [selection.tipoPeriodo] : (['semestre', 'mes'] as const);
|
||||
if (!tipos.some(tipo => parsePeriodos(text, tipo) !== null)) {
|
||||
throw new Error('Periodos inválidos o de tipos mezclados');
|
||||
}
|
||||
}
|
||||
return selection.periodos?.length ? [...new Set(selection.periodos.map(periodo => periodo.trim()))] : undefined;
|
||||
}
|
||||
export function figuraValida(value: unknown): PlotlyFigure {
|
||||
if (!record(value) || !Array.isArray(value['data']) || !value['data'].every(record)
|
||||
|| !record(value['layout'])) throw new Error('Respuesta de figura inválida');
|
||||
return value as unknown as PlotlyFigure;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { Component, inject, OnInit, signal } from '@angular/core';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { forkJoin, map, of, switchMap } from 'rxjs';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
import { compositionFigure, durationFigure, proportionFigure } from './measure-report';
|
||||
import { KpiEntry, MeasureReportService } from './measure-report.service';
|
||||
|
||||
const PERIODOS = ['2025-S1', '2025-S2'];
|
||||
|
||||
/** Every measure the WebApi answers on request, drawn from its FHIR `MeasureReport`s: one contract for all. */
|
||||
@Component({
|
||||
selector: 'app-kpis-page',
|
||||
imports: [MatProgressBarModule, PlotlyChart],
|
||||
template: `
|
||||
<h1>Indicadores</h1>
|
||||
@if (status() === 'loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando indicadores" /> }
|
||||
@if (status() === 'error') { <p role="alert">No se pudieron cargar los indicadores.</p> }
|
||||
@for (item of figures(); track item.id) {
|
||||
<section><app-plotly-chart [figure]="item.figure" [label]="item.id" /></section>
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class KpisPage implements OnInit {
|
||||
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
|
||||
readonly figures = signal<{ id: string; figure: PlotlyFigure }[]>([]);
|
||||
private readonly service = inject(MeasureReportService);
|
||||
|
||||
ngOnInit() {
|
||||
this.service.list('cacu').pipe(
|
||||
switchMap(kpis => kpis.length === 0 ? of([]) : forkJoin(kpis.map(kpi => this.figureOf(kpi)))),
|
||||
).subscribe({
|
||||
next: figures => { this.figures.set(figures); this.status.set('ready'); },
|
||||
error: () => this.status.set('error'),
|
||||
});
|
||||
}
|
||||
|
||||
/** Drawn by its scoring, from the one contract: nothing here is per measure. */
|
||||
private figureOf(kpi: KpiEntry) {
|
||||
const drawn = (figure: PlotlyFigure) => ({ id: kpi.id, figure });
|
||||
switch (kpi.scoring) {
|
||||
case 'composition':
|
||||
return this.service.composition('cacu', kpi.id, PERIODOS).pipe(map(s => drawn(compositionFigure(s, kpi.id))));
|
||||
case 'continuous-variable':
|
||||
return this.service.duration('cacu', kpi.id, PERIODOS).pipe(map(s => drawn(durationFigure(s, kpi.id))));
|
||||
default:
|
||||
return this.service.series('cacu', kpi.id, PERIODOS).pipe(map(s => drawn(proportionFigure(s, kpi.id))));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { Dominio, requireDominio } from './indicadores.models';
|
||||
import { CompositionSeries, compositionFrom, DurationSeries, durationFrom, MeasureReportBundle, Series, seriesFrom } from './measure-report';
|
||||
|
||||
export interface KpiEntry { id: string; url: string; version: string; scoring: 'proportion' | 'composition' | 'continuous-variable' }
|
||||
|
||||
/** A measure's periods answered on request by the WebApi, as FHIR `MeasureReport`s, read into a series. */
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class MeasureReportService {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
/** The measures the WebApi answers on request for the domain. */
|
||||
list(dominio: Dominio) {
|
||||
return this.http.get<KpiEntry[]>(`/${requireDominio(dominio)}/indicadores`);
|
||||
}
|
||||
|
||||
composition(dominio: Dominio, indicador: string, periodos: string[]) {
|
||||
const params = new HttpParams().set('periodos', periodos.join(','));
|
||||
return this.http
|
||||
.get<MeasureReportBundle>(`/${requireDominio(dominio)}/indicadores/${encodeURIComponent(indicador)}`, { params })
|
||||
.pipe(map((bundle): CompositionSeries => compositionFrom(bundle)));
|
||||
}
|
||||
|
||||
duration(dominio: Dominio, indicador: string, periodos: string[]) {
|
||||
const params = new HttpParams().set('periodos', periodos.join(','));
|
||||
return this.http
|
||||
.get<MeasureReportBundle>(`/${requireDominio(dominio)}/indicadores/${encodeURIComponent(indicador)}`, { params })
|
||||
.pipe(map((bundle): DurationSeries => durationFrom(bundle)));
|
||||
}
|
||||
|
||||
series(dominio: Dominio, indicador: string, periodos: string[], cortes: { evento?: string; conocimiento?: string } = {}) {
|
||||
let params = new HttpParams().set('periodos', periodos.join(','));
|
||||
if (cortes.evento) params = params.set('corte_evento', cortes.evento);
|
||||
if (cortes.conocimiento) params = params.set('corte_conocimiento', cortes.conocimiento);
|
||||
return this.http
|
||||
.get<MeasureReportBundle>(`/${requireDominio(dominio)}/indicadores/${encodeURIComponent(indicador)}`, { params })
|
||||
.pipe(map((bundle): Series => seriesFrom(bundle)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
// What this covers: reading the WebApi's FHIR `MeasureReport` bundles (`/<domain>/indicadores/<id>`) into a series, drawing
|
||||
// it here, the service that asks for it and the component that shows it.
|
||||
// Fixtures: `cacu_ind1_measure_report_bundle.json` (IND1, 2025-S1 and 2025-S2) and
|
||||
// `cacu_eu13_measure_report_bundle.json` (EU13, 2025-S1, with the `grupo_edad` stratifier) and
|
||||
// `cacu_eu7_measure_report_bundle.json` (EU7, a composition, 2025-S1 and 2025-S2) and
|
||||
// `cacu_dias_toma_diagnostico_measure_report_bundle.json` (days to diagnosis, a duration, 2025-S2): written by the
|
||||
// WebApi's route tests over the synthetic fixture database, counts and days only.
|
||||
import { Component, input } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import ind1 from './fixtures/cacu_ind1_measure_report_bundle.json';
|
||||
import eu13 from './fixtures/cacu_eu13_measure_report_bundle.json';
|
||||
import eu7 from './fixtures/cacu_eu7_measure_report_bundle.json';
|
||||
import dias from './fixtures/cacu_dias_toma_diagnostico_measure_report_bundle.json';
|
||||
import { IndicadorMeasureReport } from './indicador-measure-report';
|
||||
import { compositionFigure, compositionFrom, durationFigure, durationFrom, InvalidMeasureReport, MeasureReportBundle, periodLabel, proportionFigure, seriesFrom } from './measure-report';
|
||||
import { KpisPage } from './kpis-page';
|
||||
import { MeasureReportService } from './measure-report.service';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||
class ChartStub { figure = input<unknown>(); label = input<string>(); }
|
||||
|
||||
const IND1 = ind1 as unknown as MeasureReportBundle;
|
||||
const EU13 = eu13 as unknown as MeasureReportBundle;
|
||||
const EU7 = eu7 as unknown as MeasureReportBundle;
|
||||
const DIAS = dias as unknown as MeasureReportBundle;
|
||||
|
||||
describe('measure reports', () => {
|
||||
it('names a period from its FHIR dates', () => {
|
||||
// Pins down: semesters and months read as the WebApp names them. Fails if FHIR's inclusive end is misread.
|
||||
expect(periodLabel({ start: '2025-01-01', end: '2025-06-30' })).toBe('2025-S1');
|
||||
expect(periodLabel({ start: '2025-07-01', end: '2025-12-31' })).toBe('2025-S2');
|
||||
expect(periodLabel({ start: '2025-03-01', end: '2025-03-31' })).toBe('2025-03');
|
||||
expect(periodLabel({ start: '2025-01-01', end: '2025-03-31' })).toBe('2025-01-01 a 2025-03-31');
|
||||
});
|
||||
|
||||
it('reads one point per period from a bundle', () => {
|
||||
// Pins down: the counts come from the populations, the order from the bundle. Fails if the reading of FHIR's
|
||||
// population codes or of `improvementNotation` changes.
|
||||
const series = seriesFrom(IND1);
|
||||
expect(series.measure).toBe('cacu/IND1|0.3.2');
|
||||
expect(series.lowerIsBetter).toBe(true);
|
||||
expect(series.total).toEqual([
|
||||
{ period: '2025-S1', numerator: 1, denominator: 4, value: 0.25 },
|
||||
{ period: '2025-S2', numerator: 1, denominator: 4, value: 0.25 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('reads the strata of a stratifier', () => {
|
||||
// Pins down: each stratum's value is a series of its own. Fails if `stratifier` stops being read.
|
||||
expect(seriesFrom(EU13).strata).toEqual({
|
||||
grupo_edad: { '45-54': [{ period: '2025-S1', numerator: 0, denominator: 4, value: 0 }] },
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects what is not a bundle of reports of one measure', () => {
|
||||
// Pins down: a malformed answer fails loudly instead of drawing zeros. Fails if validation is dropped.
|
||||
expect(() => seriesFrom({ resourceType: 'Bundle', entry: [] } as MeasureReportBundle)).toThrow(InvalidMeasureReport);
|
||||
const mixed = { ...IND1, entry: [IND1.entry[0], { resource: { ...IND1.entry[1].resource, measure: 'otro' } }] };
|
||||
expect(() => seriesFrom(mixed)).toThrow(InvalidMeasureReport);
|
||||
});
|
||||
|
||||
it('draws the figure here: percentages per period, one line per stratum value', () => {
|
||||
// Pins down: the WebApp decides the figure from the data. Fails if values stop being percentages, or a
|
||||
// stratum stops giving one trace per value.
|
||||
const total = proportionFigure(seriesFrom(IND1), 'Pacientes con citología anómala');
|
||||
expect(total.data).toHaveLength(1);
|
||||
expect(total.data[0]['x']).toEqual(['2025-S1', '2025-S2']);
|
||||
expect(total.data[0]['y']).toEqual([25, 25]);
|
||||
const byAge = proportionFigure(seriesFrom(EU13), 'Tasa de detección', 'grupo_edad');
|
||||
expect(byAge.data.map(trace => trace['name'])).toEqual(['45-54']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('MeasureReportService and IndicadorMeasureReport', () => {
|
||||
beforeEach(() => TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }));
|
||||
|
||||
it('asks the WebApi for the periods and cut-offs and reads the bundle', async () => {
|
||||
// Pins down the request: the route, `periodos` comma-separated and the cut-offs only when given. Fails if
|
||||
// the URL or a parameter's name drifts from the WebApi's.
|
||||
const answer = firstValueFrom(TestBed.inject(MeasureReportService)
|
||||
.series('cacu', 'IND1', ['2025-S1', '2025-S2'], { evento: '2025-12-31' }));
|
||||
const request = TestBed.inject(HttpTestingController).expectOne(r => r.url === '/cacu/indicadores/IND1');
|
||||
expect(request.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
||||
expect(request.request.params.get('corte_evento')).toBe('2025-12-31');
|
||||
expect(request.request.params.has('corte_conocimiento')).toBe(false);
|
||||
request.flush(IND1);
|
||||
expect((await answer).total.map(p => p.value)).toEqual([0.25, 0.25]);
|
||||
});
|
||||
|
||||
it('shows the figure it drew from the answer', () => {
|
||||
// Pins down: the component hands the chart the figure built from the bundle. Fails if it stops drawing.
|
||||
TestBed.overrideComponent(IndicadorMeasureReport, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
const fixture = TestBed.createComponent(IndicadorMeasureReport);
|
||||
Object.assign(fixture.componentInstance, { dominio: 'cacu', indicador: 'IND1', titulo: 'IND1', periodos: ['2025-S1', '2025-S2'] });
|
||||
fixture.componentInstance.ngOnChanges();
|
||||
TestBed.inject(HttpTestingController).expectOne(r => r.url === '/cacu/indicadores/IND1').flush(IND1);
|
||||
fixture.detectChanges();
|
||||
expect(fixture.componentInstance.status()).toBe('ready');
|
||||
expect(fixture.componentInstance.figure()?.data[0]['y']).toEqual([25, 25]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('compositions', () => {
|
||||
it('reads the categories of each period from the `resultado` stratifier', () => {
|
||||
// Pins down: a composition is a count per category and period, zero where a period lacks one. Fails if the
|
||||
// stratifier stops being read or a missing category stops being zero.
|
||||
const series = compositionFrom(EU7);
|
||||
expect(series.periods).toEqual(['2025-S1', '2025-S2']);
|
||||
expect(series.categories).toEqual({ LIEBG: [1, 0], NEGATIVO: [2, 1], SIN_DATO: [1, 2], LIEAG: [0, 1] });
|
||||
});
|
||||
|
||||
it('takes the categories from the first stratifier, whatever its column is called', () => {
|
||||
// Pins down: a composition whose category isn't `resultado` (the confirmation by biopsia_grado) is read too, and
|
||||
// a stratifier can still be asked for by name. Fails if the reader goes back to a fixed name.
|
||||
const renamed = { ...EU7, entry: EU7.entry.map(e => ({ resource: { ...e.resource, group: [{ ...e.resource.group[0],
|
||||
stratifier: e.resource.group[0].stratifier!.map((s, i) => (i === 0 ? { ...s, code: [{ text: 'biopsia_grado' }] } : s)) }] } })) };
|
||||
expect(compositionFrom(renamed).categories).toEqual(compositionFrom(EU7).categories);
|
||||
expect(() => compositionFrom(EU7, 'no_existe')).toThrow(InvalidMeasureReport);
|
||||
});
|
||||
|
||||
it('draws stacked bars, one segment per category', () => {
|
||||
// Pins down: the WebApp draws compositions from the same contract. Fails if a category stops being a trace.
|
||||
const figure = compositionFigure(compositionFrom(EU7), 'EU7');
|
||||
expect(figure.layout['barmode']).toBe('stack');
|
||||
expect(figure.data.map(trace => trace['name']).sort()).toEqual(['LIEAG', 'LIEBG', 'NEGATIVO', 'SIN_DATO']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('durations', () => {
|
||||
it('reads the samples measurable and measured, the median and the quartiles of each period', () => {
|
||||
// Pins down: a duration's populations and its score with the quartiles as extensions. Fails if the WebApi's
|
||||
// duration contract or its reading drifts.
|
||||
expect(durationFrom(DIAS).points).toEqual([
|
||||
{ period: '2025-S2', initial: 4, n: 2, q1: 70.25, median: 100.5, q3: 130.75 },
|
||||
]);
|
||||
expect(durationFrom(DIAS).lowerIsBetter).toBe(true);
|
||||
});
|
||||
|
||||
it('draws a box per period from the served quartiles, without whiskers', () => {
|
||||
// Pins down: the WebApp draws durations from the same contract. Fails if the box stops using the quartiles or
|
||||
// starts drawing extremes it wasn't given.
|
||||
const [box] = durationFigure(durationFrom(DIAS), 'Días a diagnóstico').data;
|
||||
expect(box['type']).toBe('box');
|
||||
expect([box['q1'], box['median'], box['q3']]).toEqual([[70.25], [100.5], [130.75]]);
|
||||
expect([box['lowerfence'], box['upperfence']]).toEqual([[70.25], [130.75]]);
|
||||
});
|
||||
|
||||
it('rejects a duration measured without its median', () => {
|
||||
// Pins down: a malformed answer fails loudly. Fails if the check on the score is dropped.
|
||||
const [entry] = DIAS.entry;
|
||||
const broken = { ...DIAS, entry: [{ resource: { ...entry.resource, group: [{ ...entry.resource.group[0], measureScore: undefined }] } }] };
|
||||
expect(() => durationFrom(broken)).toThrow(InvalidMeasureReport);
|
||||
});
|
||||
});
|
||||
|
||||
describe('KpisPage', () => {
|
||||
beforeEach(() => TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }));
|
||||
|
||||
it('draws every measure the WebApi lists, each from its reports', () => {
|
||||
// Pins down: the page needs nothing per measure: it lists `/cacu/indicadores` and draws proportions, compositions
|
||||
// and durations from the one contract. Fails if a scoring stops being drawn or the page starts naming measures.
|
||||
TestBed.overrideComponent(KpisPage, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
const fixture = TestBed.createComponent(KpisPage);
|
||||
fixture.componentInstance.ngOnInit();
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/cacu/indicadores').flush([
|
||||
{ id: 'IND1', url: 'cacu/IND1', version: '0.3.2', scoring: 'proportion' },
|
||||
{ id: 'CACU_EU13', url: 'cacu/CACU_EU13', version: '0.3.2', scoring: 'proportion' },
|
||||
{ id: 'CACU_EU7', url: 'cacu/CACU_EU7', version: '0.3.3', scoring: 'composition' },
|
||||
{ id: 'CACU_DIAS_TOMA_DIAGNOSTICO', url: 'cacu/CACU_DIAS_TOMA_DIAGNOSTICO', version: '0.2.3', scoring: 'continuous-variable' },
|
||||
]);
|
||||
http.expectOne(r => r.url === '/cacu/indicadores/IND1').flush(IND1);
|
||||
http.expectOne(r => r.url === '/cacu/indicadores/CACU_EU13').flush(EU13);
|
||||
http.expectOne(r => r.url === '/cacu/indicadores/CACU_EU7').flush(EU7);
|
||||
http.expectOne(r => r.url === '/cacu/indicadores/CACU_DIAS_TOMA_DIAGNOSTICO').flush(DIAS);
|
||||
fixture.detectChanges();
|
||||
expect(fixture.componentInstance.status()).toBe('ready');
|
||||
expect(fixture.componentInstance.figures().map(f => f.id)).toEqual(['IND1', 'CACU_EU13', 'CACU_EU7', 'CACU_DIAS_TOMA_DIAGNOSTICO']);
|
||||
expect(fixture.componentInstance.figures()[2].figure.layout['barmode']).toBe('stack');
|
||||
expect(fixture.componentInstance.figures()[3].figure.data[0]['type']).toBe('box');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
|
||||
/** The part of FHIR R4's `MeasureReport` the WebApi's `/<domain>/indicadores/<id>` serves: one group, its populations,
|
||||
* its score and its strata. */
|
||||
export interface CodeableConcept { coding?: { system?: string; code: string }[]; text?: string }
|
||||
export interface ReportPopulation { code: CodeableConcept; count: number }
|
||||
export interface ReportStratum { value: CodeableConcept; population: ReportPopulation[]; measureScore?: { value: number } }
|
||||
export interface ReportStratifier { code: CodeableConcept[]; stratum: ReportStratum[] }
|
||||
export interface Score { value: number; unit?: string; extension?: { url: string; valueDecimal?: number }[] }
|
||||
export interface ReportGroup {
|
||||
id?: string;
|
||||
population: ReportPopulation[];
|
||||
measureScore?: Score;
|
||||
stratifier?: ReportStratifier[];
|
||||
}
|
||||
export interface MeasureReport {
|
||||
resourceType: 'MeasureReport';
|
||||
status: string;
|
||||
type: string;
|
||||
measure: string;
|
||||
period: { start: string; end: string };
|
||||
group: ReportGroup[];
|
||||
improvementNotation?: CodeableConcept;
|
||||
extension?: { url: string; valueDate?: string; valueDateTime?: string; valueInteger?: number }[];
|
||||
}
|
||||
export interface MeasureReportBundle { resourceType: 'Bundle'; entry: { resource: MeasureReport }[] }
|
||||
|
||||
/** One period of a series: its label, the counts and the proportion (null without a denominator). */
|
||||
export interface Point { period: string; numerator: number; denominator: number; value: number | null }
|
||||
export interface Series {
|
||||
measure: string;
|
||||
lowerIsBetter: boolean;
|
||||
total: Point[];
|
||||
strata: Record<string, Record<string, Point[]>>;
|
||||
}
|
||||
|
||||
export class InvalidMeasureReport extends Error {}
|
||||
|
||||
/** "2025-S1", "2025-03" or "2025-01-01 a 2025-03-31": the period's name from FHIR's dates (the end is inclusive). */
|
||||
export function periodLabel(period: { start: string; end: string }): string {
|
||||
const [y1, m1, d1] = period.start.split('-').map(Number);
|
||||
const [y2, m2] = period.end.split('-').map(Number);
|
||||
const months = (y2 - y1) * 12 + (m2 - m1) + 1;
|
||||
if (d1 === 1 && months === 1) return `${y1}-${String(m1).padStart(2, '0')}`;
|
||||
if (d1 === 1 && months === 6 && (m1 === 1 || m1 === 7)) return `${y1}-S${m1 === 1 ? 1 : 2}`;
|
||||
return `${period.start} a ${period.end}`;
|
||||
}
|
||||
|
||||
function count(populations: ReportPopulation[], code: string): number {
|
||||
const found = populations.find(p => p.code.coding?.some(c => c.code === code));
|
||||
if (!found || !Number.isInteger(found.count) || found.count < 0) throw new InvalidMeasureReport(`Falta la población ${code}`);
|
||||
return found.count;
|
||||
}
|
||||
|
||||
function point(period: string, populations: ReportPopulation[]): Point {
|
||||
const numerator = count(populations, 'numerator');
|
||||
const denominator = count(populations, 'denominator');
|
||||
return { period, numerator, denominator, value: denominator ? numerator / denominator : null };
|
||||
}
|
||||
|
||||
/** The series of a measure from the reports of its periods, in the order they came. */
|
||||
export function seriesFrom(bundle: MeasureReportBundle): Series {
|
||||
if (bundle?.resourceType !== 'Bundle' || !Array.isArray(bundle.entry) || bundle.entry.length === 0) {
|
||||
throw new InvalidMeasureReport('Respuesta de KPI inválida');
|
||||
}
|
||||
const reports = bundle.entry.map(e => e.resource);
|
||||
if (!reports.every(r => r?.resourceType === 'MeasureReport' && r.group?.length === 1)) {
|
||||
throw new InvalidMeasureReport('Respuesta de KPI inválida');
|
||||
}
|
||||
const measures = new Set(reports.map(r => r.measure));
|
||||
if (measures.size !== 1) throw new InvalidMeasureReport('Los reportes son de indicadores distintos');
|
||||
const strata: Series['strata'] = {};
|
||||
const total = reports.map(report => {
|
||||
const period = periodLabel(report.period);
|
||||
const [group] = report.group;
|
||||
for (const stratifier of group.stratifier ?? []) {
|
||||
const name = stratifier.code[0]?.text ?? '';
|
||||
for (const stratum of stratifier.stratum) {
|
||||
const value = stratum.value.text ?? '';
|
||||
((strata[name] ??= {})[value] ??= []).push(point(period, stratum.population));
|
||||
}
|
||||
}
|
||||
return point(period, group.population);
|
||||
});
|
||||
const lowerIsBetter = reports[0].improvementNotation?.coding?.some(c => c.code === 'decrease') ?? false;
|
||||
return { measure: reports[0].measure, lowerIsBetter, total, strata };
|
||||
}
|
||||
|
||||
const hover = (p: Point) => `${p.period}<br>${p.numerator} de ${p.denominator}`
|
||||
+ (p.value === null ? '<br>sin denominador' : `<br>${(100 * p.value).toFixed(1)} %`);
|
||||
|
||||
/** The figure, drawn here: one point per period, as a percentage; with a stratum, one line per value. */
|
||||
export function proportionFigure(series: Series, title: string, stratum?: string): PlotlyFigure {
|
||||
const traces = stratum
|
||||
? Object.entries(series.strata[stratum] ?? {}).map(([value, points]) => ({ name: value, points }))
|
||||
: [{ name: 'Total', points: series.total }];
|
||||
const data = traces.map(({ name, points }) => ({
|
||||
type: 'scatter', mode: 'lines+markers', name,
|
||||
x: points.map(p => p.period),
|
||||
y: points.map(p => (p.value === null ? null : 100 * p.value)),
|
||||
text: points.map(hover), hoverinfo: 'text',
|
||||
}));
|
||||
const notes = series.lowerIsBetter ? [{ text: 'Menos es mejor.', showarrow: false, xref: 'paper', yref: 'paper', x: 0, y: -0.2 }] : [];
|
||||
return {
|
||||
data,
|
||||
layout: {
|
||||
title: { text: title }, showlegend: traces.length > 1,
|
||||
xaxis: { type: 'category', title: { text: 'Periodo' } },
|
||||
yaxis: { title: { text: 'Porcentaje' }, ticksuffix: ' %', rangemode: 'tozero' },
|
||||
annotations: notes,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/** A composition: per period, how many units fall in each category. The categories are the report's first
|
||||
* stratifier (the WebApi puts them first, named after the category's column), or the one named `stratifier`. */
|
||||
export interface CompositionSeries { measure: string; periods: string[]; categories: Record<string, number[]> }
|
||||
|
||||
export function compositionFrom(bundle: MeasureReportBundle, stratifier?: string): CompositionSeries {
|
||||
if (bundle?.resourceType !== 'Bundle' || !Array.isArray(bundle.entry) || bundle.entry.length === 0) {
|
||||
throw new InvalidMeasureReport('Respuesta de KPI inválida');
|
||||
}
|
||||
const reports = bundle.entry.map(e => e.resource);
|
||||
const periods = reports.map(r => periodLabel(r.period));
|
||||
const categories: Record<string, number[]> = {};
|
||||
reports.forEach((report, i) => {
|
||||
const stratifiers = report.group[0]?.stratifier ?? [];
|
||||
const found = stratifier === undefined ? stratifiers[0] : stratifiers.find(s => s.code[0]?.text === stratifier);
|
||||
if (!found) throw new InvalidMeasureReport(`Falta el estratificador ${stratifier ?? 'de categorías'}`);
|
||||
for (const stratum of found.stratum) {
|
||||
const name = stratum.value.text ?? '';
|
||||
(categories[name] ??= periods.map(() => 0))[i] = count(stratum.population, 'initial-population');
|
||||
}
|
||||
});
|
||||
return { measure: reports[0].measure, periods, categories };
|
||||
}
|
||||
|
||||
/** Stacked bars, one per period, a segment per category, drawn here. */
|
||||
export function compositionFigure(series: CompositionSeries, title: string): PlotlyFigure {
|
||||
const data = Object.entries(series.categories).map(([name, counts]) => ({
|
||||
type: 'bar', name, x: series.periods, y: counts,
|
||||
text: counts.map((n, i) => `${series.periods[i]}<br>${name}: ${n}`), hoverinfo: 'text',
|
||||
}));
|
||||
return {
|
||||
data,
|
||||
layout: { title: { text: title }, barmode: 'stack', showlegend: true,
|
||||
xaxis: { type: 'category', title: { text: 'Periodo' } }, yaxis: { title: { text: 'Pacientes' }, rangemode: 'tozero' } },
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/** A duration: per period, the units measurable and measured and, if any was, the quartiles of their days. */
|
||||
export interface DurationPoint { period: string; initial: number; n: number; q1: number | null; median: number | null; q3: number | null }
|
||||
export interface DurationSeries { measure: string; lowerIsBetter: boolean; points: DurationPoint[] }
|
||||
|
||||
const quartile = (score: Score | undefined, name: string) =>
|
||||
score?.extension?.find(e => e.url.endsWith(`/${name}`))?.valueDecimal ?? null;
|
||||
|
||||
export function durationFrom(bundle: MeasureReportBundle): DurationSeries {
|
||||
if (bundle?.resourceType !== 'Bundle' || !Array.isArray(bundle.entry) || bundle.entry.length === 0) {
|
||||
throw new InvalidMeasureReport('Respuesta de KPI inválida');
|
||||
}
|
||||
const reports = bundle.entry.map(e => e.resource);
|
||||
const points = reports.map(report => {
|
||||
const [group] = report.group;
|
||||
const n = count(group.population, 'measure-observation');
|
||||
const score = group.measureScore;
|
||||
if (n > 0 && score === undefined) throw new InvalidMeasureReport('Falta la mediana');
|
||||
return { period: periodLabel(report.period), initial: count(group.population, 'initial-population'), n,
|
||||
q1: quartile(score, 'q1'), median: score?.value ?? null, q3: quartile(score, 'q3') };
|
||||
});
|
||||
const lowerIsBetter = reports[0].improvementNotation?.coding?.some(c => c.code === 'decrease') ?? false;
|
||||
return { measure: reports[0].measure, lowerIsBetter, points };
|
||||
}
|
||||
|
||||
/** One box per period, from the served quartiles: first to third quartile and the median, no whiskers. */
|
||||
export function durationFigure(series: DurationSeries, title: string): PlotlyFigure {
|
||||
const measured = series.points.filter(p => p.median !== null);
|
||||
const data = [{
|
||||
type: 'box', name: 'Días', x: measured.map(p => p.period),
|
||||
q1: measured.map(p => p.q1), median: measured.map(p => p.median), q3: measured.map(p => p.q3),
|
||||
lowerfence: measured.map(p => p.q1), upperfence: measured.map(p => p.q3),
|
||||
text: measured.map(p => `${p.period}<br>n = ${p.n} de ${p.initial}<br>mediana ${p.median} días`), hoverinfo: 'text',
|
||||
}];
|
||||
const notes = series.lowerIsBetter ? [{ text: 'Menos días es mejor.', showarrow: false, xref: 'paper', yref: 'paper', x: 0, y: -0.2 }] : [];
|
||||
return {
|
||||
data,
|
||||
layout: { title: { text: title }, showlegend: false, annotations: notes,
|
||||
xaxis: { type: 'category', title: { text: 'Periodo' } }, yaxis: { title: { text: 'Días' }, rangemode: 'tozero' } },
|
||||
};
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { isoDate, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||
import { validSeguimientoQuery } from './cacu-seguimiento.service';
|
||||
import { Dominio, requireDominio } from './indicadores.models';
|
||||
|
||||
// Follow-up list whose filters and columns come with the answer, so a domain needs no code of its own.
|
||||
export type SeguimientoValor = string | number | null;
|
||||
// `detalles` are shown under the value, each with its label (for example the date of a result).
|
||||
export interface SeguimientoColumna { clave: string; etiqueta: string; detalles?: { clave: string; etiqueta: string }[] }
|
||||
export interface SeguimientoFiltro { clave: string; etiqueta: string; opciones: SeguimientoStatus[] }
|
||||
export interface SeguimientoTablaResponse extends Pick<SeguimientoResponse, 'simulado' | 'corte' | 'ventana' | 'paginacion'> {
|
||||
filtros: Record<string, string | null>;
|
||||
filtros_disponibles: SeguimientoFiltro[];
|
||||
columnas: SeguimientoColumna[];
|
||||
// Every item has `id_seudonimo`; the rest are the columns' keys and their details.
|
||||
items: Record<string, SeguimientoValor>[];
|
||||
}
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
|
||||
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
|
||||
const valor = (v: unknown) => v === null || typeof v === 'string' || typeof v === 'number' && Number.isFinite(v);
|
||||
// Keys travel as query parameters, so they are restricted to what can't collide with the shared ones.
|
||||
const clave = (v: unknown) => text(v) && /^[a-z][a-z0-9_]*$/.test(v) && !['meses', 'page', 'page_size', 'corte'].includes(v);
|
||||
const opcion = (v: unknown) => record(v) && text(v['codigo']) && text(v['etiqueta']);
|
||||
|
||||
export function seguimientoTablaResponse(v: unknown): SeguimientoTablaResponse {
|
||||
// Same rule as CaCu and TEA: demonstration records only.
|
||||
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||||
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'], available = v['filtros_disponibles'], columns = v['columnas'];
|
||||
if (!isoDate(v['corte']) || !record(window) || ![1, 3, 6, 12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta'])
|
||||
|| !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(available) || !available.every(f => record(f) && clave(f['clave']) && text(f['etiqueta']) && Array.isArray(f['opciones']) && f['opciones'].every(opcion))
|
||||
|| new Set(available.map(f => f['clave'])).size !== available.length
|
||||
|| !record(filters) || !Object.entries(filters).every(([k, f]) => f === null || typeof f === 'string' && available.some(a => a['clave'] === k))
|
||||
|| !Array.isArray(columns) || !columns.length || !columns.every(c => record(c) && text(c['clave']) && text(c['etiqueta'])
|
||||
&& (c['detalles'] === undefined || Array.isArray(c['detalles']) && c['detalles'].every(d => record(d) && text(d['clave']) && text(d['etiqueta']))))
|
||||
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number)
|
||||
|| !v['items'].every(item => record(item) && text(item['id_seudonimo']) && Object.values(item).every(valor)))
|
||||
throw new Error('Respuesta de seguimiento inválida');
|
||||
return v as unknown as SeguimientoTablaResponse;
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class SeguimientoTablaService {
|
||||
private readonly http = inject(HttpClient);
|
||||
consultar(dominio: Dominio, query: SeguimientoQuery) {
|
||||
if (!validSeguimientoQuery(query) || !Object.keys(query.filtros ?? {}).every(clave)) throw new Error('Parámetros de seguimiento inválidos');
|
||||
let params = new HttpParams().set('meses', query.meses).set('page', query.page).set('page_size', query.page_size);
|
||||
if (query.corte) params = params.set('corte', query.corte);
|
||||
for (const [k, v] of Object.entries(query.filtros ?? {})) if (v) params = params.set(k, v);
|
||||
return this.http.get<unknown>(`/${requireDominio(dominio)}/seguimiento`, { params }).pipe(map(seguimientoTablaResponse));
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import eu7 from './fixtures/eu7-c2-ejemplos.json';
|
||||
import { Indicador, IndicadorDatos } from './indicadores.models';
|
||||
import { modelo, vistaEscenario } from './indicadores-eu7-escenario';
|
||||
import { IndicadoresTracking } from './indicadores-tracking';
|
||||
import { seguimientoTablaResponse } from './seguimiento-tabla.service';
|
||||
|
||||
// Covers what lets a domain reuse CaCu's views without code of its own: the interactive donut and bars
|
||||
// chosen by the catalog's `escenario`, and the follow-up list whose filters and columns come in the answer.
|
||||
// Fixtures: `eu7-c2-ejemplos.json` (CaCu's EU7 answers, relabelled here as another stratum) and `lista`,
|
||||
// a two-patient CaMa list built below.
|
||||
|
||||
// Two CaMa patients, one without a biopsy, with the filters and columns the list announces.
|
||||
const lista = () => ({
|
||||
simulado: true, corte: '2026-10-20', ventana: { meses: 3, desde: '2026-07-21', hasta: '2026-10-20' },
|
||||
filtros: { birads: null }, filtros_disponibles: [{ clave: 'birads', etiqueta: 'Categoría BI-RADS', opciones: [{ codigo: 'BIRADS_5', etiqueta: 'BI-RADS 5' }] }],
|
||||
columnas: [{ clave: 'id_seudonimo', etiqueta: 'Identificador seudónimo' },
|
||||
{ clave: 'birads', etiqueta: 'Última mastografía', detalles: [{ clave: 'mastografia_fecha', etiqueta: 'Fecha' }] },
|
||||
{ clave: 'biopsia', etiqueta: 'Resultado histopatológico' }],
|
||||
paginacion: { page: 1, page_size: 50, total_items: 2, total_pages: 1 },
|
||||
items: [{ id_seudonimo: 'M-0001', birads: 'BI-RADS 5', mastografia_fecha: '2026-09-01', biopsia: 'Carcinoma invasor' },
|
||||
{ id_seudonimo: 'M-0002', birads: 'BI-RADS 4A', mastografia_fecha: '2026-08-15', biopsia: null }],
|
||||
});
|
||||
|
||||
describe('Vista de dona y barras por estrato', () => {
|
||||
const item = (extra: Partial<Indicador> = {}): Indicador => ({ id: 'x', titulo: 'X', contrato: 'C2', figuras: [], tipos_periodo: ['semestre'], ...extra });
|
||||
it('la elige el campo escenario del catálogo, y CaCu EU7 la conserva sin él', () => {
|
||||
// Fails if the view goes back to being recognised by CaCu's indicator id only.
|
||||
expect(vistaEscenario('cama', item({ escenario: { estrato: 'birads', etiqueta: 'categoría BI-RADS' } }))?.estrato).toBe('birads');
|
||||
expect(vistaEscenario('cacu', item({ id: 'cacu_eu7' }))?.estrato).toBe('estatus_seguimiento');
|
||||
expect(vistaEscenario('cama', item())).toBeUndefined();
|
||||
});
|
||||
it('arma el modelo con otro indicador y otro estrato', () => {
|
||||
// Fails if `modelo` checks CaCu's id or its stratum instead of the ones it is given.
|
||||
const relabel = (d: unknown, estrato: string | null) => ({ ...structuredClone(d) as IndicadorDatos, id: 'cama_histopatologia_birads', ...(estrato ? { estrato } : {}) });
|
||||
const general = relabel(eu7.general, null), porBirads = relabel(eu7.estatus_seguimiento, 'birads');
|
||||
expect(modelo(general, porBirads, '2025-S2', 'birads').total).toBe(946);
|
||||
expect(() => modelo(general, porBirads, '2025-S2')).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Seguimiento con filtros y columnas anunciados', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresTracking>>, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
fixture = TestBed.createComponent(IndicadoresTracking); http = TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('domainLabel', 'cáncer de mama');
|
||||
fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
const text = () => fixture.nativeElement.textContent as string;
|
||||
|
||||
it('pinta las columnas, los detalles y los valores ausentes de la respuesta', () => {
|
||||
// Fails if CaMa stops querying its own list or the table stops following `columnas`.
|
||||
http.expectOne(r => r.url === '/cama/seguimiento').flush(lista()); fixture.detectChanges();
|
||||
const headers = Array.from(fixture.nativeElement.querySelectorAll('thead th')).map(e => (e as HTMLElement).textContent?.trim());
|
||||
expect(headers).toEqual(['Identificador seudónimo', 'Última mastografía', 'Resultado histopatológico']);
|
||||
expect(text()).toContain('Fecha: 2026-09-01');
|
||||
expect(fixture.nativeElement.querySelectorAll('tbody tr')[1].textContent).toContain('No disponible');
|
||||
});
|
||||
it('envía cada filtro anunciado con su clave y sin los vacíos', () => {
|
||||
// Fails if the announced filters stop reaching the query, or an empty choice is sent as a value.
|
||||
http.expectOne(r => r.url === '/cama/seguimiento').flush(lista()); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('select[name="filtro-birads"]')).not.toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('select[name="estatus"]')).toBeNull();
|
||||
fixture.componentInstance.filtrosDraft['birads'] = 'BIRADS_5'; fixture.componentInstance.apply();
|
||||
let req = http.expectOne(r => r.url === '/cama/seguimiento');
|
||||
expect(req.request.params.get('birads')).toBe('BIRADS_5');
|
||||
req.flush({ ...lista(), filtros: { birads: 'BIRADS_5' } });
|
||||
fixture.componentInstance.filtrosDraft['birads'] = ''; fixture.componentInstance.apply();
|
||||
req = http.expectOne(r => r.url === '/cama/seguimiento');
|
||||
expect(req.request.params.has('birads')).toBe(false);
|
||||
req.flush(lista());
|
||||
});
|
||||
it('sin lista publicada queda pendiente', () => {
|
||||
// Fails if a 404 on the first page is shown as an error instead of a list not yet published.
|
||||
http.expectOne(r => r.url === '/cama/seguimiento').flush({}, { status: 404, statusText: 'Not found' }); fixture.detectChanges();
|
||||
expect(text()).toContain('Funcionalidad pendiente de publicación');
|
||||
});
|
||||
it('solo admite datos de demostración y respuestas coherentes', () => {
|
||||
// Fails if the validation stops guarding the table from real records or from filters it didn't announce.
|
||||
expect(() => seguimientoTablaResponse({ ...lista(), simulado: false })).toThrow();
|
||||
expect(() => seguimientoTablaResponse({ ...lista(), filtros: { edad: '40-49' } })).toThrow();
|
||||
expect(() => seguimientoTablaResponse({ ...lista(), filtros_disponibles: [{ clave: 'page', etiqueta: 'X', opciones: [] }] })).toThrow();
|
||||
expect(() => seguimientoTablaResponse({ ...lista(), items: [{ birads: 'BI-RADS 5' }] })).toThrow();
|
||||
http.expectOne(r => r.url === '/cama/seguimiento').flush(lista());
|
||||
});
|
||||
});
|
||||
@@ -25,7 +25,7 @@ button.nombre:focus-visible::after { outline: 2px solid var(--issste-text); outl
|
||||
.leyenda-mapa .rojo { margin-inline-start: .5rem; background: #B2182B; }
|
||||
dd[data-calidad=aceptable] { color: #B26A00; }
|
||||
.dominio { display: grid; grid-template-columns: 1fr auto; gap: .15rem 1rem; margin-bottom: .4rem; font-size: .85rem; }
|
||||
.bar { grid-column: 1 / -1; height: .375rem; border-radius: var(--issste-radius); background: var(--issste-border); overflow: hidden; }
|
||||
.bar { grid-column: 1 / -1; height: .375rem; border-radius: 999px; background: var(--issste-border); overflow: hidden; }
|
||||
.bar span { display: block; height: 100%; background: var(--issste-text); }
|
||||
details { margin-top: .5rem; }
|
||||
summary { cursor: pointer; font-weight: 600; font-size: .9rem; min-height: 44px; display: flex; align-items: center; gap: .5rem; list-style: none; }
|
||||
@@ -44,7 +44,7 @@ dt { color: var(--issste-text-secondary); } dd { margin: 0; text-align: end; fon
|
||||
.regiones li { padding: .1rem 0; }
|
||||
.regiones li span:last-child { float: inline-end; font-variant-numeric: tabular-nums; }
|
||||
.regiones .destacada { font-weight: 700; }
|
||||
h3 .mock { display: inline-block; white-space: nowrap; margin-inline-start: .5rem; padding: .1rem .5rem; border: 1px dashed var(--issste-border); border-radius: var(--issste-radius);
|
||||
h3 .mock { display: inline-block; white-space: nowrap; margin-inline-start: .5rem; padding: .1rem .5rem; border: 1px dashed var(--issste-border); border-radius: 999px;
|
||||
font-size: .75rem; font-weight: 400; color: var(--issste-text-secondary); vertical-align: middle; }
|
||||
.sin-alteraciones { margin: 0 0 .75rem; font-weight: 600; }
|
||||
.metricas, .efectos { margin: 0; padding: 0; list-style: none; }
|
||||
|
||||
@@ -16,19 +16,19 @@ describe('Resumen TEA por periodo', () => {
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
const completos = () => [panel('M28_casos_por_estado', { ...listo(100), categorias: { COMPLETO: 60, EN_PROCESO: 25, FUERA_PROTOCOLO: 15 } }), panel('M24_confirmacion_diagnostico', listo('86.5')),
|
||||
const completos = () => [panel('M28_casos_por_estado', { ...listo(100), categorias: { EEG: 60, SOLO_MCHAT: 15, PSICOLOGIA: 15, NEUROPEDIATRIA: 10 } }), panel('M24_confirmacion_diagnostico', listo('86.5')),
|
||||
panel('M25_dias_mchat_diagnostico', listo(22)), panel('M21_diagnosticados_con_eeg', listo('71.9')), panel('M22_diagnosticados_sin_eeg', listo('28.1')),
|
||||
panel('M26_dias_mchat_ados2', listo(8)), panel('M27_dias_ados2_diagnostico', listo(14))];
|
||||
|
||||
it('redacta el párrafo con cada población y resalta los valores', () => {
|
||||
const root: HTMLElement = render(completos()).nativeElement;
|
||||
const text = root.textContent!.replace(/\s+/g, ' ');
|
||||
expect(text).toContain('Al cierre del periodo 2025-S2, de los 100 casos iniciados hasta entonces, 60 están completos (con M-CHAT, ADOS-2, nota de neuropediatría y EEG), 25 siguen en proceso y 15 quedaron fuera del protocolo.');
|
||||
expect(text).toContain('De los pacientes con nota médica, 86.5 % tuvo diagnóstico positivo de TEA (CIE-10 F84.0).');
|
||||
expect(text).toContain('Al cierre del periodo 2025-S2, de los 100 niños en el tamizaje, 60 lo completaron con un EEG de buena calidad y 40 siguen en proceso: 15 solo con M-CHAT, 15 hasta la evaluación psicológica y 10 hasta la evaluación neuropediátrica.');
|
||||
expect(text).toContain('De los niños con diagnóstico confirmado o en proceso, 86.5 % tiene diagnóstico confirmado de TEA (CIE-10 F84.0).');
|
||||
expect(text).toContain('La mediana de M-CHAT a ADOS-2 fue de 8 días, de ADOS-2 a diagnóstico, de 14 días, y en total, de M-CHAT a diagnóstico, de 22 días.');
|
||||
expect(text).toContain('De los pacientes con TEA positivo por ADOS-2 (16 a 36 meses), 71.9 % tenían EEG y 28.1 % no lo tenían.');
|
||||
expect(text).toContain('De los niños con diagnóstico confirmado, 71.9 % tienen un EEG de buena calidad y 28.1 % todavía no.');
|
||||
expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim()))
|
||||
.toEqual(['2025-S2', '100', '60', '25', '15', '86.5 %', '8 días', '14 días', '22 días', '71.9 %', '28.1 %']);
|
||||
.toEqual(['2025-S2', '100', '60', '40', '15', '15', '10', '86.5 %', '8 días', '14 días', '22 días', '71.9 %', '28.1 %']);
|
||||
expect(root.querySelector('button')).toBeNull();
|
||||
});
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import { NgTemplateOutlet } from '@angular/common';
|
||||
import { Component, Input } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { M28_COMPLETO, M28_EN_PROCESO } from './indicadores-kpi';
|
||||
|
||||
interface Valor { texto: string; estado: 'listo' | 'cargando' | 'sin_dato'; detalle?: string; }
|
||||
|
||||
@@ -14,15 +15,18 @@ interface Valor { texto: string; estado: 'listo' | 'cargando' | 'sin_dato'; deta
|
||||
template: `
|
||||
<article class="resumen" [attr.aria-busy]="cargando">
|
||||
<p>
|
||||
Al cierre del periodo <span class="dato listo">{{ periodo }}</span>, de los <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M28_casos_por_estado', '') }" /> casos iniciados hasta entonces,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso('COMPLETO') }" /> están completos (con M-CHAT, ADOS-2, nota de neuropediatría y EEG),
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso('EN_PROCESO') }" /> siguen en proceso y <ng-container *ngTemplateOutlet="dato; context: { $implicit: caso('FUERA_PROTOCOLO') }" /> quedaron fuera del protocolo.
|
||||
De los pacientes con nota médica, <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M24_confirmacion_diagnostico', ' %') }" />
|
||||
tuvo diagnóstico positivo de TEA (CIE-10 F84.0). La mediana de M-CHAT a ADOS-2 fue de <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M26_dias_mchat_ados2', ' días') }" />, de ADOS-2 a diagnóstico, de
|
||||
Al cierre del periodo <span class="dato listo">{{ periodo }}</span>, de los <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M28_casos_por_estado', '') }" /> niños en el tamizaje,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(completo) }" /> lo completaron con un EEG de buena calidad y
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(enProceso) }" /> siguen en proceso:
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(['SOLO_MCHAT']) }" /> solo con M-CHAT,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(['PSICOLOGIA']) }" /> hasta la evaluación psicológica y
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(['NEUROPEDIATRIA']) }" /> hasta la evaluación neuropediátrica.
|
||||
De los niños con diagnóstico confirmado o en proceso, <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M24_confirmacion_diagnostico', ' %') }" />
|
||||
tiene diagnóstico confirmado de TEA (CIE-10 F84.0). La mediana de M-CHAT a ADOS-2 fue de <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M26_dias_mchat_ados2', ' días') }" />, de ADOS-2 a diagnóstico, de
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M27_dias_ados2_diagnostico', ' días') }" />, y en total, de M-CHAT a diagnóstico, de
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M25_dias_mchat_diagnostico', ' días') }" />.
|
||||
De los pacientes con TEA positivo por ADOS-2 (16 a 36 meses), <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M21_diagnosticados_con_eeg', ' %') }" />
|
||||
tenían EEG y <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M22_diagnosticados_sin_eeg', ' %') }" /> no lo tenían.
|
||||
De los niños con diagnóstico confirmado, <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M21_diagnosticados_con_eeg', ' %') }" />
|
||||
tienen un EEG de buena calidad y <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M22_diagnosticados_sin_eeg', ' %') }" /> todavía no.
|
||||
</p>
|
||||
@if (conError.length) {
|
||||
<button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button>
|
||||
@@ -59,12 +63,16 @@ export class TeaResumenPeriodo {
|
||||
return { texto: 'sin dato', estado: 'sin_dato', detalle: result.state };
|
||||
return { texto: result.value + sufijo, estado: 'listo' };
|
||||
}
|
||||
// One status of M28, under the same rules as valor().
|
||||
caso(categoria: string): Valor {
|
||||
readonly completo = [M28_COMPLETO];
|
||||
readonly enProceso = M28_EN_PROCESO;
|
||||
// The children of M28 in some stages, under the same rules as valor().
|
||||
caso(categorias: readonly string[]): Valor {
|
||||
const base = this.valor('M28_casos_por_estado', '');
|
||||
if (base.estado !== 'listo') return base;
|
||||
const n = this.panel('M28_casos_por_estado')?.result().categorias?.[categoria];
|
||||
return n === undefined ? { texto: 'sin dato', estado: 'sin_dato', detalle: 'Estado no publicado' } : { texto: String(n), estado: 'listo' };
|
||||
const counts = this.panel('M28_casos_por_estado')?.result().categorias;
|
||||
const n = categorias.map(c => counts?.[c]);
|
||||
return n.some(v => v === undefined) ? { texto: 'sin dato', estado: 'sin_dato', detalle: 'Etapa no publicada' }
|
||||
: { texto: String(n.reduce((s, v) => s! + v!, 0)), estado: 'listo' };
|
||||
}
|
||||
get cargando() { return this.paneles.some(p => p.result().loading); }
|
||||
get conError() { return this.paneles.filter(p => p.result().state === 'Error de consulta'); }
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { forkJoin, map, Observable, of, shareReplay } from 'rxjs';
|
||||
import { Bundle, code, codeIn, Concept, display, extension, isSimulated, Quantity, referenceId, Resource, resources } from './fhir';
|
||||
import { estratoValor } from './indicadores-fhir';
|
||||
import { SeguimientoQuery } from './cacu-seguimiento.models';
|
||||
import { validSeguimientoQuery } from './cacu-seguimiento.service';
|
||||
import {
|
||||
RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad,
|
||||
teaPacienteDetalle, TeaSeguimientoPaciente, teaSeguimientoResponse, TeaSeguimientoService,
|
||||
} from './tea-seguimiento.service';
|
||||
|
||||
// TEA's follow-up list and patient summary over the WebApi's FHIR endpoint: each child's screening is an
|
||||
// `EpisodeOfCare` with its resources included, and `Patient/<id>/$resumen-tea` is the summary. Both are mapped into the
|
||||
// shapes the page already reads, and checked by the same rules.
|
||||
|
||||
interface Observation extends Resource {
|
||||
code?: Concept; effectiveDateTime?: string; subject?: { reference?: string };
|
||||
valueInteger?: number; valueQuantity?: Quantity; valueString?: string; valueCodeableConcept?: Concept;
|
||||
interpretation?: Concept[]; dataAbsentReason?: Concept;
|
||||
referenceRange?: { low?: Quantity; high?: Quantity; text?: string }[];
|
||||
component?: { code?: Concept; valueInteger?: number; valueQuantity?: Quantity; valueString?: string; valueCodeableConcept?: Concept; extension?: Resource['extension'] }[];
|
||||
}
|
||||
interface Report extends Resource {
|
||||
effectiveDateTime?: string; subject?: { reference?: string }; result?: { reference?: string }[]; conclusionCode?: Concept[];
|
||||
}
|
||||
interface Metric { code?: string; display?: string; property?: { code: string; valueString?: string }[] }
|
||||
|
||||
const MAX_COUNT = 200;
|
||||
const METRICAS = 'tea-eeg-metrica';
|
||||
const INTERPRETACION: Record<string, TeaAlteracionEstado> = { H: 'aumentado', L: 'disminuido', N: 'normal' };
|
||||
|
||||
// The 10-20 electrodes on the page's head (x left to right, y back to front, radius 1) and the regions they average.
|
||||
export const ELECTRODOS: Record<string, [number, number]> = {
|
||||
Fp1: [-.25, .77], Fp2: [.25, .77], F7: [-.65, .47], F3: [-.33, .4], Fz: [0, .38], F4: [.33, .4], F8: [.65, .47],
|
||||
T3: [-.8, 0], C3: [-.4, 0], Cz: [0, 0], C4: [.4, 0], T4: [.8, 0],
|
||||
T5: [-.65, -.47], P3: [-.33, -.4], Pz: [0, -.38], P4: [.33, -.4], T6: [.65, -.47], O1: [-.25, -.77], O2: [.25, -.77],
|
||||
};
|
||||
const REGIONES: [string, string, string[]][] = [
|
||||
['frontal_izq', 'Frontal izquierda', ['Fp1', 'F3', 'F7']], ['frontal_der', 'Frontal derecha', ['Fp2', 'F4', 'F8']],
|
||||
['central', 'Central', ['Fz', 'C3', 'Cz', 'C4']], ['temporal_izq', 'Temporal izquierda', ['T3', 'T5']],
|
||||
['temporal_der', 'Temporal derecha', ['T4', 'T6']], ['parietal', 'Parietal', ['P3', 'Pz', 'P4']], ['occipital', 'Occipital', ['O1', 'O2']],
|
||||
];
|
||||
const EJE = Array.from({ length: 41 }, (_, i) => Math.round((-1 + i * .05) * 100) / 100);
|
||||
// How far from a measured electrode the map still shows a value; beyond it, no electrode speaks for the scalp.
|
||||
const ALCANCE = .45;
|
||||
|
||||
const round2 = (value: number) => Math.round(value * 100) / 100;
|
||||
export const grupoEdad = (codigo: string | undefined) =>
|
||||
!codigo ? '' : codigo === 'sin_dato' ? 'Sin dato' : `${estratoValor(codigo)} meses`;
|
||||
const grupoCodigo = (etiqueta: string) => etiqueta.replace(' meses', '').replace('-', '_');
|
||||
|
||||
function byCode(observations: Observation[], wanted: string): Observation | undefined {
|
||||
return observations.find(o => code(o.code) === wanted);
|
||||
}
|
||||
function component(o: Observation | undefined, wanted: string) {
|
||||
return o?.component?.find(c => code(c.code) === wanted);
|
||||
}
|
||||
|
||||
// The map of one metric's electrode z-scores: inverse-distance weights within reach of a measured electrode.
|
||||
export function mapaDeElectrodos(codigo: string, etiqueta: string, valores: Record<string, number>): TeaEegMapa {
|
||||
const puntos = Object.entries(valores).filter(([nombre]) => ELECTRODOS[nombre]).map(([nombre, z]) => ({ xy: ELECTRODOS[nombre], z }));
|
||||
const z = EJE.map(y => EJE.map(x => {
|
||||
let peso = 0, suma = 0;
|
||||
for (const p of puntos) {
|
||||
const d2 = (x - p.xy[0]) ** 2 + (y - p.xy[1]) ** 2;
|
||||
if (d2 < 1e-9) return round2(p.z);
|
||||
if (d2 > ALCANCE ** 2) continue;
|
||||
peso += 1 / d2; suma += p.z / d2;
|
||||
}
|
||||
return peso ? round2(suma / peso) : null;
|
||||
}));
|
||||
const regiones = REGIONES.flatMap(([c, e, nombres]) => {
|
||||
const medidos = nombres.filter(n => typeof valores[n] === 'number');
|
||||
return medidos.length ? [{ codigo: c, etiqueta: e, valor_z: round2(medidos.reduce((s, n) => s + valores[n], 0) / medidos.length) }] : [];
|
||||
}).sort((a, b) => Math.abs(b.valor_z) - Math.abs(a.valor_z));
|
||||
return { codigo, metrica: `${etiqueta} (puntuación z)`, z, regiones };
|
||||
}
|
||||
|
||||
export function ados2DeObservacion(o: Observation | undefined): TeaAdos2 | null {
|
||||
const css = component(o, 'ados2.css')?.valueInteger;
|
||||
if (!o?.effectiveDateTime || typeof css !== 'number') return null;
|
||||
const modulo = code(component(o, 'ados2.modulo')?.valueCodeableConcept)?.replace(/^ados2\.modulo\.(MODULO_)?/, '') ?? '';
|
||||
const clasificacion = code(component(o, 'ados2.clasificacion')?.valueCodeableConcept)?.replace('ados2.clasificacion.', '').toLowerCase();
|
||||
const items = (o.component ?? []).filter(c => extension(c, 'dominio'));
|
||||
const dominios: TeaAdosDominio[] = (o.component ?? []).filter(c => codeIn(c.code, 'ados2-dominio')).map(c => {
|
||||
const codigo = code(c.code)!;
|
||||
const reactivos = items.filter(i => extension(i, 'dominio')?.valueCode === codigo).map(i => ({
|
||||
codigo: (code(i.code) ?? '').split('_').pop()!.toUpperCase(),
|
||||
etiqueta: display(i.code) ?? '',
|
||||
puntaje: i.valueInteger ?? 0,
|
||||
puntaje_algoritmo: extension(i, 'puntaje-algoritmo')?.valueInteger ?? 0,
|
||||
}));
|
||||
return { codigo, etiqueta: display(c.code) ?? codigo, puntaje: c.valueInteger ?? 0, maximo: 2 * reactivos.length, reactivos };
|
||||
});
|
||||
return {
|
||||
fecha: o.effectiveDateTime.slice(0, 10), modulo, algoritmo: component(o, 'ados2.algoritmo')?.valueString ?? '',
|
||||
dominios, total: dominios.reduce((t, d) => t + d.puntaje, 0), total_maximo: dominios.reduce((t, d) => t + d.maximo, 0),
|
||||
clasificacion: (clasificacion ?? 'no_espectro') as TeaAdos2['clasificacion'], css,
|
||||
nivel_css: (RANGOS_CSS.find(r => css >= r.min && css <= r.max)?.codigo ?? 'minimo') as TeaAdos2['nivel_css'],
|
||||
};
|
||||
}
|
||||
|
||||
function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion {
|
||||
const codigo = code(o.code) ?? '';
|
||||
const metrica = metricas.find(m => m.code === codigo);
|
||||
const evaluable = !o.dataAbsentReason && typeof o.valueQuantity?.value === 'number';
|
||||
const estado = evaluable ? INTERPRETACION[code(o.interpretation?.[0]) ?? ''] ?? 'normal' : 'no_evaluable';
|
||||
const range = o.referenceRange?.[0];
|
||||
return {
|
||||
codigo, etiqueta: display(o.code) ?? metrica?.display ?? codigo,
|
||||
unidad: o.valueQuantity?.unit ?? metrica?.property?.find(p => p.code === 'unidad')?.valueString ?? '',
|
||||
referencia: { min: range?.low?.value ?? 0, max: range?.high?.value ?? 0 },
|
||||
valor: evaluable ? o.valueQuantity!.value! : null,
|
||||
valor_z: evaluable ? component(o, 'z')?.valueQuantity?.value ?? null : null,
|
||||
estado,
|
||||
efectos: (metrica?.property ?? []).filter(p => p.code === `efecto-${estado}`).map(p => p.valueString!).filter(Boolean),
|
||||
};
|
||||
}
|
||||
|
||||
// The study EEG of `report`, with the observations it lists and the electrode maps of its metrics.
|
||||
export function eegDeReporte(report: Report | undefined, observations: Observation[], metricas: Metric[]): TeaEeg | null {
|
||||
if (!report?.effectiveDateTime) return null;
|
||||
const ids = new Set((report.result ?? []).map(r => referenceId(r)));
|
||||
const listed = observations.filter(o => ids.has(o.id));
|
||||
const calidad = (concept: Concept | undefined) => (code(concept) ?? 'MALO').toLowerCase() as TeaNivelCalidad;
|
||||
const alteraciones = listed.filter(o => codeIn(o.code, METRICAS)).map(o => alteracion(o, metricas));
|
||||
// A metric's electrode values are `electrodos-<the metric observation's id>`.
|
||||
const mapas = observations.filter(o => o.id?.startsWith('electrodos-') && ids.has(o.id.slice('electrodos-'.length)))
|
||||
.map(o => {
|
||||
const valores = Object.fromEntries((o.component ?? []).map(c => [code(c.code), c.valueQuantity?.value])
|
||||
.filter((e): e is [string, number] => !!e[0] && typeof e[1] === 'number'));
|
||||
return mapaDeElectrodos(code(o.code)!, display(o.code) ?? code(o.code)!, valores);
|
||||
})
|
||||
.filter(m => alteraciones.some(a => a.codigo === m.codigo && a.estado !== 'no_evaluable'));
|
||||
return {
|
||||
fecha: report.effectiveDateTime.slice(0, 10),
|
||||
duracion_min: Math.round(extension(report, 'duracion-min')?.valueDecimal ?? 0),
|
||||
canales: extension(report, 'canales')?.valueInteger ?? 0,
|
||||
calidad: calidad(report.conclusionCode?.[0]),
|
||||
criterios_calidad: listed.filter(o => code(o.code)?.startsWith('eeg.calidad_')).map(o => ({
|
||||
codigo: code(o.code)!.replace('eeg.calidad_', ''), etiqueta: display(o.code) ?? '',
|
||||
valor: o.valueInteger ?? o.valueQuantity?.value ?? 0, unidad: typeof o.valueInteger === 'number' ? 'canales' : o.valueQuantity?.unit ?? '',
|
||||
nivel: calidad(o.interpretation?.[0]),
|
||||
})),
|
||||
alteraciones, mapas,
|
||||
ejes_mapa: { x: EJE, y: EJE, electrodos: Object.entries(ELECTRODOS).map(([nombre, [x, y]]) => ({ nombre, x, y })) },
|
||||
};
|
||||
}
|
||||
|
||||
function resultadoEeg(report: Report | undefined, observations: Observation[], validadas: boolean): 'normal' | 'anormal' | null {
|
||||
if (!validadas || !report || code(report.conclusionCode?.[0]) !== 'BUENO') return null;
|
||||
return alteracionesDe(report, observations).length ? 'anormal' : 'normal';
|
||||
}
|
||||
function alteracionesDe(report: Report | undefined, observations: Observation[]): string[] {
|
||||
const ids = new Set((report?.result ?? []).map(r => referenceId(r)));
|
||||
return observations.filter(o => ids.has(o.id) && codeIn(o.code, METRICAS) && ['H', 'L'].includes(code(o.interpretation?.[0]) ?? ''))
|
||||
.map(o => code(o.code)!);
|
||||
}
|
||||
|
||||
// One row of the list: the episode and what the search included for its patient.
|
||||
export function pacienteDeEpisodio(episode: Resource, included: Resource[], validadas: boolean): TeaSeguimientoPaciente {
|
||||
const id = episode.id!;
|
||||
const own = included.filter(r => referenceId((r['subject'] ?? r['patient']) as { reference?: string }) === id);
|
||||
const observations = own.filter(r => r.resourceType === 'Observation') as Observation[];
|
||||
const report = own.find(r => r.resourceType === 'DiagnosticReport') as Report | undefined;
|
||||
const ados2 = byCode(observations, 'ados2');
|
||||
const plan = own.find(r => r.resourceType === 'CarePlan') as { activity?: { detail?: { code?: Concept; status?: string } }[] } | undefined;
|
||||
const modulo = code(component(ados2, 'ados2.modulo')?.valueCodeableConcept)?.replace(/^ados2\.modulo\.(MODULO_)?/, '');
|
||||
return {
|
||||
id_seudonimo: id,
|
||||
grupo_edad: grupoEdad(extension(episode, 'grupo-edad')?.valueCoding?.code),
|
||||
ultimo_eeg: report?.effectiveDateTime?.slice(0, 10) ?? null,
|
||||
mchat: byCode(observations, 'mchat.puntaje')?.valueInteger ?? null,
|
||||
css_ados2: component(ados2, 'ados2.css')?.valueInteger ?? null,
|
||||
alteraciones_eeg: resultadoEeg(report, observations, validadas),
|
||||
modulo_ados2: modulo ?? null,
|
||||
estado_caso: episode['status'] === 'finished' ? 'completo' : 'en_proceso',
|
||||
pendientes: (plan?.activity ?? []).filter(a => a.detail?.status !== 'completed').map(a => a.detail?.code?.text ?? display(a.detail?.code) ?? ''),
|
||||
alteraciones: validadas ? alteracionesDe(report, observations) : [],
|
||||
};
|
||||
}
|
||||
|
||||
function parameter(p: Resource | undefined, name: string): number {
|
||||
const found = (p?.['parameter'] as { name: string; valueInteger?: number }[] | undefined)?.find(x => x.name === name);
|
||||
return found?.valueInteger ?? 0;
|
||||
}
|
||||
function porAlteracion(p: Resource | undefined, metricas: Metric[]) {
|
||||
return ((p?.['parameter'] ?? []) as { name: string; part?: { name: string; valueCode?: string; valueInteger?: number }[] }[])
|
||||
.filter(x => x.name === 'por_alteracion').map(x => {
|
||||
const codigo = x.part?.find(y => y.name === 'alteracion')?.valueCode ?? '';
|
||||
return { codigo, etiqueta: metricas.find(m => m.code === codigo)?.display ?? codigo, n: x.part?.find(y => y.name === 'pacientes')?.valueInteger ?? 0 };
|
||||
});
|
||||
}
|
||||
|
||||
function isoDay(date: Date) {
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
// From `meses` before the cut-off (plus a day) to the cut-off, as CaCu's list.
|
||||
export function ventana(corte: string, meses: number): { desde: string; hasta: string } {
|
||||
const [y, m, d] = corte.split('-').map(Number);
|
||||
const total = y * 12 + m - 1 - meses;
|
||||
const year = Math.floor(total / 12), month = total % 12;
|
||||
const last = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
|
||||
const desde = new Date(Date.UTC(year, month, Math.min(d, last) + 1));
|
||||
return { desde: isoDay(desde), hasta: corte };
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class FhirTeaSeguimientoService extends TeaSeguimientoService {
|
||||
private readonly client = inject(HttpClient);
|
||||
private metricas$?: Observable<Metric[]>;
|
||||
today = () => new Date();
|
||||
private metricas(): Observable<Metric[]> {
|
||||
this.metricas$ ??= this.client.get<{ concept?: Metric[] }>(`/tea/fhir/CodeSystem/${METRICAS}`).pipe(
|
||||
map(system => system.concept ?? []), shareReplay({ bufferSize: 1, refCount: false }));
|
||||
return this.metricas$;
|
||||
}
|
||||
override consultar(query: SeguimientoQuery) {
|
||||
if (!validSeguimientoQuery(query)) throw new Error('Parámetros de seguimiento inválidos');
|
||||
const corte = query.corte ?? isoDay(this.today());
|
||||
const { desde, hasta } = ventana(corte, query.meses);
|
||||
let params = new HttpParams().append('date', 'ge' + desde).append('date', 'le' + hasta);
|
||||
if (query.estatus) params = params.set('resultado-eeg', query.estatus);
|
||||
if (query.grupo_edad) params = params.set('grupo-edad', grupoCodigo(query.grupo_edad));
|
||||
const mchat = RANGOS_MCHAT.find(r => r.codigo === query.mchat), css = RANGOS_CSS.find(r => r.codigo === query.css);
|
||||
if (mchat) params = params.append('mchat', 'ge' + mchat.min).append('mchat', 'le' + mchat.max);
|
||||
if (css) params = params.append('css', 'ge' + css.min).append('css', 'le' + css.max);
|
||||
if (query.estado_caso) params = params.set('status', query.estado_caso === 'completo' ? 'finished' : 'active');
|
||||
if (query.alteracion) params = params.set('alteracion', query.alteracion);
|
||||
const page = params.set('_count', Math.min(query.page_size, MAX_COUNT)).set('_offset', (query.page - 1) * query.page_size).set('_include', '*');
|
||||
// The list has no children out of the protocol any more: the screening ends with a good EEG.
|
||||
const empty = query.estado_caso === 'fuera_protocolo';
|
||||
return forkJoin({
|
||||
bundle: empty ? of<Bundle>({ resourceType: 'Bundle', total: 0, entry: [] }) : this.client.get<Bundle>('/tea/fhir/EpisodeOfCare', { params: page }),
|
||||
resumen: this.client.get<Resource>('/tea/fhir/EpisodeOfCare/$resumen-eeg', { params }),
|
||||
metricas: this.metricas(),
|
||||
}).pipe(map(({ bundle, resumen, metricas }) => {
|
||||
const validadas = (resumen['parameter'] as { name: string }[] | undefined)?.some(p => p.name === 'normales') ?? false;
|
||||
const episodes = (bundle.entry ?? []).filter(e => e.search?.mode !== 'include' && e.resource.resourceType === 'EpisodeOfCare').map(e => e.resource);
|
||||
const included = (bundle.entry ?? []).filter(e => e.search?.mode === 'include').map(e => e.resource);
|
||||
const total = empty ? 0 : bundle.total ?? episodes.length;
|
||||
return teaSeguimientoResponse({
|
||||
simulado: episodes.every(isSimulated),
|
||||
corte, ventana: { meses: query.meses, desde, hasta },
|
||||
filtros: { alteraciones_eeg: query.estatus ?? null },
|
||||
paginacion: { page: query.page, page_size: query.page_size, total_items: total, total_pages: Math.ceil(total / query.page_size) },
|
||||
items: episodes.map(e => pacienteDeEpisodio(e, included, validadas)),
|
||||
tipos_alteracion: validadas ? metricas.map(m => ({ codigo: m.code ?? '', etiqueta: m.display ?? m.code ?? '' })) : [],
|
||||
resumen_eeg: {
|
||||
normales: parameter(resumen, 'normales'), anormales: parameter(resumen, 'anormales'), sin_eeg: parameter(resumen, 'sin_eeg_valido'),
|
||||
por_alteracion: porAlteracion(resumen, metricas),
|
||||
},
|
||||
});
|
||||
}));
|
||||
}
|
||||
override detalle(id: string) {
|
||||
return forkJoin({
|
||||
bundle: this.client.get<Bundle>(`/tea/fhir/Patient/${encodeURIComponent(id)}/$resumen-tea`),
|
||||
metricas: this.metricas(),
|
||||
}).pipe(map(({ bundle, metricas }) => {
|
||||
const all = resources(bundle);
|
||||
const observations = all.filter(r => r.resourceType === 'Observation') as Observation[];
|
||||
const metric = observations.find(o => codeIn(o.code, METRICAS) && o.referenceRange?.[0]?.text);
|
||||
const edad = metric?.referenceRange?.[0]?.text?.split(': ').pop();
|
||||
return teaPacienteDetalle({
|
||||
simulado: all.length > 0 && all.every(isSimulated),
|
||||
id_seudonimo: id,
|
||||
grupo_edad: grupoEdad(edad),
|
||||
ados2: ados2DeObservacion(byCode(observations, 'ados2')),
|
||||
eeg: eegDeReporte(resources(bundle, 'DiagnosticReport')[0] as Report | undefined, observations, metricas),
|
||||
}, id);
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -132,7 +132,7 @@ function validEeg(e: unknown): boolean {
|
||||
const nivel = (v: unknown) => ['bueno', 'aceptable', 'malo'].includes(v as string);
|
||||
if (!record(e) || !isoDate(e['fecha']) || !integer(e['duracion_min'], 1) || !integer(e['canales'], 1) || !nivel(e['calidad'])
|
||||
|| !Array.isArray(e['criterios_calidad']) || !e['criterios_calidad'].every(c => record(c) && text(c['codigo']) && text(c['etiqueta']) && nivel(c['nivel']) && text(c['unidad'])
|
||||
&& integer(c['valor']) && (c['unidad'] !== 'canales' || (c['valor'] as number) <= (e['canales'] as number)))) return false;
|
||||
&& (c['unidad'] === 'canales' ? integer(c['valor']) && (c['valor'] as number) <= (e['canales'] as number) : finite(c['valor']) && (c['valor'] as number) >= 0))) return false;
|
||||
if (!Array.isArray(e['alteraciones']) || !e['alteraciones'].every(validAlteracion)) return false;
|
||||
const ejes = e['ejes_mapa'];
|
||||
if (!record(ejes) || !Array.isArray(ejes['x']) || !Array.isArray(ejes['y']) || !Array.isArray(e['mapas'])) return false;
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
<section class="dashboard">
|
||||
<header><span class="domain">Trastorno del espectro autista, investigación</span><h1>Indicadores</h1><p>Explore la información del tamizaje.</p></header>
|
||||
<nav class="domain-nav" aria-label="Dominios de indicadores"><a routerLink="/indicadores/cacu">Cáncer cervicouterino</a><a routerLink="/indicadores/cama">Cáncer de mama</a><a routerLink="/indicadores/tea" aria-current="page">TEA</a></nav>
|
||||
<nav class="tabs" aria-label="Secciones de TEA">
|
||||
<button type="button" [attr.aria-current]="section() === 'resumen' ? 'page' : null" (click)="changeSection('resumen')">Resumen</button>
|
||||
<button type="button" [attr.aria-current]="section() === 'historico' ? 'page' : null" (click)="changeSection('historico')">Histórico</button>
|
||||
<button type="button" [attr.aria-current]="section() === 'seguimiento' ? 'page' : null" (click)="changeSection('seguimiento')">Seguimiento</button>
|
||||
</nav>
|
||||
@if (section() !== 'seguimiento') {
|
||||
<section aria-label="Consulta de indicadores">
|
||||
<h2>{{ section() === 'resumen' ? 'Resumen' : 'Histórico' }}</h2>
|
||||
<form (ngSubmit)="section() === 'resumen' ? loadSummary() : loadHistory()">
|
||||
@if (section() === 'resumen') { <label>Periodo <input name="periodo" [(ngModel)]="periodo" required placeholder="2025-S1"></label> }
|
||||
@else {
|
||||
<label>Indicador <select name="measure" [(ngModel)]="measureId">@for (m of measures(); track m.id) { <option [value]="m.id">{{ m.title }}</option> }</select></label>
|
||||
<label>Periodos separados por coma <input name="history" [(ngModel)]="historyPeriods" required></label>
|
||||
}
|
||||
<label>Corte de evento <input name="evento" type="date" [(ngModel)]="eventCutoff"></label>
|
||||
<label>Corte de conocimiento <input name="conocimiento" type="datetime-local" [(ngModel)]="knowledgeCutoff"></label>
|
||||
<button type="submit">Consultar</button>
|
||||
</form>
|
||||
@if (measureState() === 'cargando' || measureState() === 'inicial') { <p role="status">Consultando indicadores…</p> }
|
||||
@if (measureState() === 'error') { <p role="alert">{{ measureError() }}</p> }
|
||||
@if (measureState() === 'listo' && reports().length === 0) { <p>No hay indicadores para la selección.</p> }
|
||||
@for (report of reports(); track $index) {
|
||||
@if (measureState() === 'listo') { <article class="card"><h3>{{ title(report) }}</h3><p>{{ report.period?.start }} a {{ report.period?.end }}</p>
|
||||
@if (rows(report).length === 0) { <p>Sin datos para el periodo.</p> }
|
||||
@else { <dl>@for (row of rows(report); track $index) { <div><dt>{{ row.label }}</dt><dd>{{ row.value }}</dd></div> }</dl> }
|
||||
</article> }
|
||||
}
|
||||
</section>
|
||||
}
|
||||
<section [hidden]="section() !== 'seguimiento' || selected() !== null" aria-label="Seguimiento">
|
||||
<h2>Seguimiento</h2><p>Consulte los episodios según la fecha de corte y los filtros seleccionados.</p>
|
||||
<form (ngSubmit)="applyFilters()" class="filters">
|
||||
<label>Desde <input type="date" name="desde" [(ngModel)]="filters.since"></label><label>Fecha de corte <input type="date" name="corte" [(ngModel)]="filters.cutoff"></label>
|
||||
<label>Estado <select name="status" [(ngModel)]="filters.status"><option value="">Todos</option><option value="active">En seguimiento</option><option value="finished">Finalizado</option></select></label>
|
||||
<label>Etapa <select name="stage" [(ngModel)]="filters.stage"><option value="">Todas</option><option value="SOLO_MCHAT">Solo M-CHAT</option><option value="PSICOLOGIA">Psicología</option><option value="NEUROPEDIATRIA">Neuropediatría</option><option value="EEG">EEG</option></select></label>
|
||||
<label>Etapa desde <input type="date" name="stageFrom" [(ngModel)]="filters.stageFrom"></label><label>Etapa hasta <input type="date" name="stageTo" [(ngModel)]="filters.stageTo"></label>
|
||||
<label>Edad al M-CHAT <select name="age" [(ngModel)]="filters.age"><option value="">Todas</option><option value="16_23">16 a 23 meses</option><option value="24_29">24 a 29 meses</option><option value="30_36">30 a 36 meses</option></select></label>
|
||||
<label>M-CHAT mínimo <input type="number" name="mchatMin" [(ngModel)]="filters.mchatMin"></label><label>M-CHAT máximo <input type="number" name="mchatMax" [(ngModel)]="filters.mchatMax"></label>
|
||||
<label>CSS mínimo <input type="number" name="cssMin" [(ngModel)]="filters.cssMin"></label><label>CSS máximo <input type="number" name="cssMax" [(ngModel)]="filters.cssMax"></label>
|
||||
<label>EEG <select name="eeg" [(ngModel)]="filters.eeg"><option value="">Todos</option>@if (alterationsAvailable()) { <option value="normal">Normal</option><option value="anormal">Anormal</option> } @else { <option value="valido">Con EEG válido</option> }<option value="sin-eeg-valido">Sin EEG válido</option></select></label>
|
||||
@if (alterationsAvailable() && alterationTypes().length) { <label>Alteración <select name="alteration" [(ngModel)]="filters.alteration"><option value="">Todas</option>@for (item of alterationTypes(); track item.code) { <option [value]="item.code">{{ item.display }}</option> }</select></label> }
|
||||
<button type="submit">Aplicar filtros</button>
|
||||
</form>
|
||||
@if (episodeState() === 'cargando') { <p role="status">Consultando seguimiento…</p> }
|
||||
@if (episodeState() === 'error') { <p role="alert">{{ episodeError() }}</p> }
|
||||
@if (episodeState() === 'listo') {
|
||||
<p>{{ episodeTotal() }} episodios</p>
|
||||
@if (episodes().length === 0) { <p>No hay episodios para la selección.</p> }
|
||||
@else { <table><thead><tr><th>Paciente</th><th>Etapa</th><th>Fecha de etapa</th><th>Estado</th><th></th></tr></thead><tbody>
|
||||
@for (e of episodes(); track e.id) { <tr><td>{{ patientId(e) }}</td><td>{{ stage(e) }}</td><td>{{ stageDate(e) }}</td><td>{{ e.status === 'finished' ? 'Finalizado' : 'En seguimiento' }}</td><td><button type="button" [attr.data-patient]="patientId(e)" (click)="openPatient(e)">Abrir ficha</button></td></tr> }
|
||||
</tbody></table> }
|
||||
<div class="paging"><button type="button" [disabled]="page === 0" (click)="page = page - 1; loadEpisodes()">Anterior</button><span>Página {{ page + 1 }}</span><button type="button" [disabled]="(page + 1) * pageSize >= episodeTotal()" (click)="page = page + 1; loadEpisodes()">Siguiente</button></div>
|
||||
}
|
||||
</section>
|
||||
@if (section() === 'seguimiento' && selected()) {
|
||||
<section aria-label="Ficha del paciente"><button type="button" (click)="back()">Volver a Seguimiento</button><h2>Ficha del paciente</h2><p>{{ selected() }}</p><p>La ficha muestra la información disponible a la fecha actual.</p>
|
||||
@if (patientState() === 'cargando') { <p role="status">Consultando ficha…</p> }
|
||||
@if (patientState() === 'error') { <p role="alert">{{ patientError() }}</p> }
|
||||
@if (patientState() === 'listo') {
|
||||
<article class="card"><h3>ADOS-2</h3>@if (ados(); as ados) { <p>Fecha: {{ ados.effectiveDateTime }}</p><dl>@for (c of ados.component; track $index) { <div><dt>{{ c.code.coding?.[0]?.display || c.code.coding?.[0]?.code }}</dt><dd>{{ componentValue(c) }}</dd></div> }</dl> } @else { <p>Sin información de ADOS-2.</p> }</article>
|
||||
<article class="card"><h3>EEG del estudio</h3>@if (eeg(); as eeg) { <p>Fecha: {{ eeg.effectiveDateTime }}</p><p>Calidad: {{ eegQuality() }}</p><p>Duración: {{ eegExtension('duracion-min') }} minutos. Canales: {{ eegExtension('canales') }}.</p>@if (eeg.conclusion) { <p>{{ eeg.conclusion }}</p> }<dl>@for (o of quality(); track o.id) { <div><dt>{{ o.code.coding?.[0]?.display }}</dt><dd>{{ observationValue(o) }} ({{ qualityStatus(o) }})</dd></div> }</dl> } @else { <p>Sin información de EEG.</p> }</article>
|
||||
@if (alterationsAvailable() && alterations().length) { <article class="card"><h3>Métricas del EEG</h3><dl>@for (o of alterations(); track o.id) { <div><dt>{{ o.code.coding?.[0]?.display }}</dt><dd>{{ observationValue(o) }}</dd></div> }</dl></article> }
|
||||
}
|
||||
</section>
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,13 @@
|
||||
.dashboard { max-width: 1200px; margin: 0 auto; padding: 1.5rem; color: #142b3d; }
|
||||
.domain { color: #24735a; font-weight: 600; }
|
||||
.domain-nav, .tabs, form, .paging { display: flex; flex-wrap: wrap; gap: .8rem; align-items: end; margin: 1rem 0; }
|
||||
.domain-nav a { color: #216b56; padding: .5rem; }
|
||||
.tabs { border-bottom: 1px solid #c9d6d1; }
|
||||
button { border: 1px solid #216b56; border-radius: .3rem; background: #fff; color: #165a47; padding: .55rem .8rem; cursor: pointer; }
|
||||
button[aria-current="page"], button[type="submit"] { background: #216b56; color: white; }
|
||||
button:disabled { opacity: .5; cursor: default; }
|
||||
label { display: grid; gap: .25rem; font-size: .9rem; }
|
||||
input, select { padding: .45rem; border: 1px solid #8ba09a; border-radius: .25rem; }
|
||||
.card { border: 1px solid #d5e0dc; border-radius: .5rem; padding: 1rem; margin: 1rem 0; background: #fff; }
|
||||
dl div { display: flex; gap: 1rem; justify-content: space-between; border-bottom: 1px solid #edf1ef; padding: .3rem 0; } dd { margin: 0; font-weight: 600; }
|
||||
table { width: 100%; border-collapse: collapse; } th, td { text-align: left; padding: .55rem; border-bottom: 1px solid #d5e0dc; }
|
||||
@@ -0,0 +1,69 @@
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { TeaStatusPage } from './tea-status-page';
|
||||
|
||||
const tag = { tag: [{ system: 'https://isssteleon.org/fhir/CodeSystem/etiqueta', code: 'simulado' }] };
|
||||
const episode = (id: string) => ({ resourceType: 'EpisodeOfCare', id, meta: tag, patient: { reference: `Patient/${id}` }, type: [{ coding: [{ code: 'SOLO_MCHAT' }] }] });
|
||||
const measure = { resourceType: 'Measure', id: 'M28-casos-por-estado', title: 'Casos por estatus', url: 'https://isssteleon.org/fhir/Measure/M28-casos-por-estado' };
|
||||
const bundle = (...items: any[]) => ({ resourceType: 'Bundle', total: items.length, entry: items.map(resource => ({ resource })) });
|
||||
|
||||
describe('TEA FHIR journey', () => {
|
||||
function setup() {
|
||||
TestBed.configureTestingModule({ providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
const fixture = TestBed.createComponent(TeaStatusPage);
|
||||
const c = fixture.componentInstance;
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/fhir/Measure').flush(bundle(measure));
|
||||
http.expectOne(r => r.url.endsWith('/$evaluate-measure')).flush({ measure: measure.url, period: { start: '2025-01-01', end: '2025-06-30' }, group: [{ population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 6 }] }] });
|
||||
return { c, http };
|
||||
}
|
||||
it('distinguishes zero, missing and masked values and requests the historical periods', () => {
|
||||
const { c, http } = setup();
|
||||
expect(c.value({ count: 0 }, 'count')).toBe('0');
|
||||
expect(c.value({}, 'count')).toBe('Sin dato');
|
||||
expect(c.value({ _count: { extension: [{ valueCode: 'masked' }] } }, 'count')).toBe('Dato suprimido');
|
||||
c.changeSection('historico');
|
||||
const req = http.expectOne(r => r.url === '/tea/fhir/MeasureReport');
|
||||
expect(req.request.params.get('periodo')).toBe('2025-01,2025-02,2025-03');
|
||||
req.flush(bundle());
|
||||
expect(c.reports()).toEqual([]);
|
||||
http.verify();
|
||||
});
|
||||
it('retains filters and page and rejects a late patient response', () => {
|
||||
const { c, http } = setup();
|
||||
c.filters.stage = 'PSICOLOGIA'; c.filters.cutoff = '2025-12-31'; c.filters.cssMin = null as unknown as string; c.page = 1; c.changeSection('seguimiento');
|
||||
const list = http.expectOne(r => r.url.endsWith('/EpisodeOfCare'));
|
||||
expect(list.request.params.get('etapa')).toBe('PSICOLOGIA');
|
||||
expect(list.request.params.get('_offset')).toBe('5');
|
||||
expect(list.request.params.has('css')).toBe(false);
|
||||
list.flush({ ...bundle(episode('a'), episode('b')), total: 8 });
|
||||
c.openPatient(episode('a')); const a = http.expectOne(r => r.url.includes('/Patient/a/'));
|
||||
c.openPatient(episode('b')); const b = http.expectOne(r => r.url.includes('/Patient/b/'));
|
||||
b.flush(bundle({ resourceType: 'Patient', id: 'b', meta: tag }));
|
||||
a.flush(bundle({ resourceType: 'Patient', id: 'a', meta: tag }));
|
||||
expect(c.selected()).toBe('b'); expect(c.patientResources()[0].id).toBe('b');
|
||||
c.back(); expect(c.page).toBe(1); expect(c.filters.stage).toBe('PSICOLOGIA');
|
||||
http.verify();
|
||||
});
|
||||
it('rejects an untagged response and shows the OperationOutcome error', () => {
|
||||
const { c, http } = setup();
|
||||
c.changeSection('seguimiento');
|
||||
http.expectOne(r => r.url.endsWith('/EpisodeOfCare')).flush(bundle({ ...episode('a'), meta: {} }));
|
||||
expect(c.episodeState()).toBe('error');
|
||||
c.openPatient(episode('a'));
|
||||
http.expectOne(r => r.url.includes('/Patient/a/')).flush({ issue: [{ diagnostics: 'Paciente no encontrado' }] }, { status: 404, statusText: 'Not Found' });
|
||||
expect(c.patientError()).toBe('Paciente no encontrado');
|
||||
http.verify();
|
||||
});
|
||||
it('shows alteration groups only when the catalog offers M30', () => {
|
||||
const { c, http } = setup();
|
||||
expect(c.alterationsAvailable()).toBe(false);
|
||||
c.measures.set([measure, { id: 'M30-resultado-eeg', url: 'm30', scoring: { coding: [{ code: 'proportion' }] } }]);
|
||||
expect(c.alterationsAvailable()).toBe(true);
|
||||
const rows = c.rows({ measure: 'm30', group: [{ population: [] }, { code: { coding: [{ code: 'ritmo', display: 'Ritmo' }] }, population: [{ code: { coding: [{ code: 'numerator' }] }, count: 0 }] }] });
|
||||
expect(rows).toContainEqual({ label: 'Ritmo — Numerador', value: '0' });
|
||||
http.verify();
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user