Compare commits

...

9 Commits

74 changed files with 3007 additions and 849 deletions
+2 -5
View File
@@ -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
+10 -53
View File
@@ -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`.
+4
View File
@@ -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;
+10
View File
@@ -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 },
]
};
+13 -1
View File
@@ -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}`,
+1 -1
View File
@@ -136,7 +136,7 @@ export interface ImportSourcePayload extends SourceLocator {
defaults?: Record<string, unknown>;
}
// -- documents -----------------------------------------------------------------
// Clinical documents
export type OcrMode = 'auto' | 'always' | 'never';
+10 -8
View File
@@ -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) : [];
+2 -8
View File
@@ -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);
-1
View File
@@ -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;
+54
View File
@@ -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();
}
@@ -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,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';
@@ -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.
@@ -71,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);
@@ -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'); },
});
}
}
@@ -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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// 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] : [] };
}
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']);
});
@@ -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();
@@ -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];
});
@@ -21,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);
@@ -60,7 +68,7 @@ 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.' });
@@ -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' },
@@ -69,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' };
@@ -63,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, 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,100 +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)) {
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 (!['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 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;
}
+50
View File
@@ -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' } },
};
}
@@ -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();
});
});
@@ -0,0 +1,185 @@
import { HttpClient, HttpParams } from '@angular/common/http';
import { Component, ElementRef, inject, OnDestroy, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterLink } from '@angular/router';
import { forkJoin, Subscription } from 'rxjs';
type Resource = any;
type Section = 'resumen' | 'historico' | 'seguimiento';
type State = 'inicial' | 'cargando' | 'listo' | 'error';
const stages: Record<string, string> = { SOLO_MCHAT: 'Solo M-CHAT', PSICOLOGIA: 'Hasta evaluación psicológica', NEUROPEDIATRIA: 'Hasta evaluación neuropediátrica', EEG: 'Con EEG' };
const populations: Record<string, string> = { 'initial-population': 'Total', numerator: 'Numerador', denominator: 'Denominador', 'denominator-exclusion': 'Excluidos del denominador', 'measure-observation': 'Con valor', 'measure-population-exclusion': 'Sin valor' };
const code = (value: Resource) => value?.coding?.[0]?.code ?? '';
const text = (value: Resource) => value?.coding?.[0]?.display ?? value?.text ?? code(value);
const resources = (bundle: Resource): Resource[] => (bundle?.entry ?? []).map((entry: Resource) => entry.resource);
const simulated = (resource: Resource) => resource?.meta?.tag?.some((tag: Resource) => tag.system === 'https://isssteleon.org/fhir/CodeSystem/etiqueta' && tag.code === 'simulado');
@Component({
selector: 'app-tea-status-page',
imports: [FormsModule, RouterLink],
templateUrl: './tea-status-page.html',
styleUrl: './tea-status-page.scss',
})
export class TeaStatusPage implements OnDestroy {
private readonly http = inject(HttpClient);
private readonly element = inject<ElementRef<HTMLElement>>(ElementRef);
private requests: Subscription[] = [];
private revision = { measures: 0, episodes: 0, patient: 0 };
readonly section = signal<Section>('resumen');
readonly measures = signal<Resource[]>([]);
readonly alterationTypes = signal<Resource[]>([]);
readonly reports = signal<Resource[]>([]);
readonly measureState = signal<State>('inicial');
readonly measureError = signal('');
readonly episodes = signal<Resource[]>([]);
readonly episodeTotal = signal(0);
readonly episodeState = signal<State>('inicial');
readonly episodeError = signal('');
readonly selected = signal<string | null>(null);
readonly patientResources = signal<Resource[]>([]);
readonly patientState = signal<State>('inicial');
readonly patientError = signal('');
periodo = '2025-S1';
historyPeriods = '2025-01,2025-02,2025-03';
measureId = 'M28-casos-por-estado';
eventCutoff = '';
knowledgeCutoff = '';
page = 0;
pageSize = 5;
filters = { since: '', cutoff: '', status: '', stage: '', stageFrom: '', stageTo: '', age: '', mchatMin: '', mchatMax: '', cssMin: '', cssMax: '', eeg: '', alteration: '' };
readonly stages = stages;
constructor() {
this.requests.push(this.http.get<Resource>('/tea/fhir/Measure').subscribe({
next: bundle => {
this.measures.set(resources(bundle).filter(m => /^M(2[1-9]|30)-/.test(m.id)));
if (this.alterationsAvailable()) this.requests.push(this.http.get<Resource>('/tea/fhir/CodeSystem/tea-eeg-metrica').subscribe({ next: system => this.alterationTypes.set(system.concept ?? []), error: () => this.alterationTypes.set([]) }));
this.loadSummary();
},
error: () => { this.measureState.set('error'); this.measureError.set('No fue posible cargar los indicadores.'); },
}));
}
ngOnDestroy() { this.requests.forEach(s => s.unsubscribe()); }
changeSection(section: Section) {
this.section.set(section);
if (section === 'resumen') this.loadSummary();
if (section === 'historico') this.loadHistory();
if (section === 'seguimiento' && this.episodeState() === 'inicial') this.loadEpisodes();
}
private cutoffs(params: HttpParams): HttpParams {
if (this.eventCutoff) params = params.set('corte_evento', this.eventCutoff);
if (this.knowledgeCutoff) params = params.set('corte_conocimiento', new Date(this.knowledgeCutoff).toISOString());
return params;
}
loadSummary() {
const token = ++this.revision.measures;
const measures = this.measures();
if (!measures.length) { this.measureState.set('listo'); this.reports.set([]); return; }
this.measureState.set('cargando');
const params = this.cutoffs(new HttpParams().set('periodo', this.periodo));
this.requests.push(forkJoin(measures.map(m => this.http.get<Resource>(`/tea/fhir/Measure/${encodeURIComponent(m.id)}/$evaluate-measure`, { params }))).subscribe({
next: reports => { if (token === this.revision.measures) { this.reports.set(reports); this.measureState.set('listo'); } },
error: e => { if (token === this.revision.measures) { this.measureError.set(this.errorText(e)); this.measureState.set('error'); } },
}));
}
loadHistory() {
const token = ++this.revision.measures;
const measure = this.measures().find(m => m.id === this.measureId);
if (!measure) { this.measureState.set('error'); this.measureError.set('Seleccione un indicador disponible.'); return; }
this.measureState.set('cargando');
const params = this.cutoffs(new HttpParams().set('measure', measure.url).set('periodo', this.historyPeriods.replace(/\s/g, '')).set('_count', 200));
this.requests.push(this.http.get<Resource>('/tea/fhir/MeasureReport', { params }).subscribe({
next: bundle => { if (token === this.revision.measures) { const found = resources(bundle); if (bundle.total > found.length) { this.measureError.set('Seleccione como máximo 200 periodos.'); this.measureState.set('error'); return; } this.reports.set(found); this.measureState.set('listo'); } },
error: e => { if (token === this.revision.measures) { this.measureError.set(this.errorText(e)); this.measureState.set('error'); } },
}));
}
title(report: Resource) { return this.measures().find(m => report.measure?.split('|')[0] === m.url)?.title ?? report.measure; }
rows(report: Resource): { label: string; value: string }[] {
const group = report.group?.[0];
if (!group) return [];
const rows = (group.population ?? []).map((p: Resource) => ({ label: populations[code(p.code)] ?? text(p.code), value: this.value(p, 'count') }));
const measure = this.measures().find(m => report.measure?.split('|')[0] === m.url);
if (code(measure?.scoring) !== 'cohort') rows.push({ label: 'Resultado', value: group.measureScore ? this.score(group.measureScore) : 'Sin dato' });
for (const extension of group.measureScore?.extension ?? []) {
if (extension.url?.endsWith('/q1') || extension.url?.endsWith('/q3')) rows.push({ label: extension.url.endsWith('/q1') ? 'Primer cuartil' : 'Tercer cuartil', value: `${extension.valueDecimal} días` });
}
for (const stratum of group.stratifier?.[0]?.stratum ?? []) {
const name = code(stratum.value);
const label = stages[name] ?? ({ '16_23': '16 a 23 meses', '24_29': '24 a 29 meses', '30_36': '30 a 36 meses' } as Record<string, string>)[name] ?? text(stratum.value);
if (code(measure?.scoring) === 'cohort') rows.push({ label, value: this.value(stratum.population?.[0], 'count') });
else {
for (const p of stratum.population ?? []) rows.push({ label: `${label} — ${populations[code(p.code)] ?? text(p.code)}`, value: this.value(p, 'count') });
rows.push({ label: `${label} — resultado`, value: stratum.measureScore ? this.score(stratum.measureScore) : 'Sin dato' });
}
}
for (const extra of report.group?.slice(1) ?? []) {
const label = text(extra.code) || 'Grupo';
for (const p of extra.population ?? []) rows.push({ label: `${label} — ${populations[code(p.code)] ?? text(p.code)}`, value: this.value(p, 'count') });
rows.push({ label: `${label} — resultado`, value: extra.measureScore ? this.score(extra.measureScore) : 'Sin dato' });
}
return rows;
}
value(value: Resource, field: string): string {
if (value?.[`_${field}`]?.extension?.some((e: Resource) => e.valueCode === 'masked')) return 'Dato suprimido';
return value?.[field] == null ? 'Sin dato' : String(value[field]);
}
score(score: Resource): string {
if (score?._value?.extension?.some((e: Resource) => e.valueCode === 'masked')) return 'Dato suprimido';
if (score?.value == null) return 'Sin dato';
return score.unit === 'd' ? `${score.value} días` : `${(100 * score.value).toFixed(1)} %`;
}
private errorText(error: Resource) { return error?.error?.issue?.[0]?.diagnostics ?? 'No fue posible consultar la información. Intente de nuevo.'; }
applyFilters() { this.page = 0; this.loadEpisodes(); }
loadEpisodes() {
const token = ++this.revision.episodes;
this.episodeState.set('cargando');
let p = new HttpParams().set('_count', this.pageSize).set('_offset', this.page * this.pageSize).set('_include', '*');
const f = this.filters;
for (const [key, val] of [['status', f.status], ['etapa', f.stage], ['grupo-edad', f.age], ['resultado-eeg', f.eeg]] as const) if (val) p = p.set(key, val);
if (this.alterationsAvailable() && f.alteration) p = p.set('alteracion', f.alteration);
for (const [key, prefix, val] of [['date', 'ge', f.since], ['date', 'le', f.cutoff], ['fecha-etapa', 'ge', f.stageFrom], ['fecha-etapa', 'le', f.stageTo], ['mchat', 'ge', f.mchatMin], ['mchat', 'le', f.mchatMax], ['css', 'ge', f.cssMin], ['css', 'le', f.cssMax]] as const) if (val != null && val !== '') p = p.append(key, prefix + val);
this.requests.push(this.http.get<Resource>('/tea/fhir/EpisodeOfCare', { params: p }).subscribe({
next: bundle => {
if (token !== this.revision.episodes) return;
const found = resources(bundle);
if (found.some(r => !simulated(r))) { this.episodeError.set('La información recibida no está identificada como datos simulados.'); this.episodeState.set('error'); return; }
this.episodes.set(found.filter(r => r.resourceType === 'EpisodeOfCare')); this.episodeTotal.set(bundle.total ?? 0); this.episodeState.set('listo');
},
error: e => { if (token === this.revision.episodes) { this.episodeError.set(this.errorText(e)); this.episodeState.set('error'); } },
}));
}
stage(e: Resource) { const value = code(e.type?.[0]); return stages[value] ?? value ?? 'Sin dato'; }
stageDate(e: Resource) { return e.extension?.find((x: Resource) => x.url.endsWith('/fecha-etapa'))?.valueDate ?? 'Sin dato'; }
patientId(e: Resource): string { return e.patient?.reference?.startsWith('Patient/') ? e.patient.reference.slice(8) : ''; }
openPatient(e: Resource) {
const id = this.patientId(e);
if (!id) { this.episodeError.set('El episodio no identifica a un paciente.'); this.episodeState.set('error'); return; }
const token = ++this.revision.patient;
this.selected.set(id); this.patientState.set('cargando'); this.patientResources.set([]);
this.requests.push(this.http.get<Resource>(`/tea/fhir/Patient/${encodeURIComponent(id)}/$resumen-tea`).subscribe({
next: bundle => {
if (token !== this.revision.patient || this.selected() !== id) return;
const found = resources(bundle);
if (!found.some(r => r.resourceType === 'Patient' && r.id === id) || found.some(r => !simulated(r) || (r.resourceType === 'Patient' && r.id !== id) || (r.subject?.reference && r.subject.reference !== `Patient/${id}`))) {
this.patientError.set('No se pudo verificar la identidad o el origen de la ficha.'); this.patientState.set('error'); return;
}
this.patientResources.set(found); this.patientState.set('listo');
},
error: e => { if (token === this.revision.patient && this.selected() === id) { this.patientError.set(this.errorText(e)); this.patientState.set('error'); } },
}));
}
back() {
const id = this.selected(); ++this.revision.patient; this.selected.set(null);
setTimeout(() => this.element.nativeElement.querySelector<HTMLButtonElement>(`[data-patient="${id}"]`)?.focus());
}
ados() { return this.patientResources().find(r => r.resourceType === 'Observation' && code(r.code) === 'ados2'); }
eeg() { return this.patientResources().find(r => r.resourceType === 'DiagnosticReport' && code(r.code) === 'eeg'); }
eegQuality() { const quality = code(this.eeg()?.conclusionCode?.[0]); return quality === 'BUENO' ? 'Buena' : quality === 'MALO' ? 'Mala' : 'Sin dato'; }
eegExtension(name: string) { const e = this.eeg()?.extension?.find((x: Resource) => x.url.endsWith(`/${name}`)); return e?.valueDecimal ?? e?.valueInteger ?? 'Sin dato'; }
qualityStatus(observation: Resource) { const value = code(observation.interpretation?.[0]); return value === 'BUENO' ? 'buena' : value === 'MALO' ? 'mala' : 'sin dato'; }
quality() { const ids = new Set((this.eeg()?.result ?? []).map((r: Resource) => r.reference)); return this.patientResources().filter(r => r.resourceType === 'Observation' && ids.has(`Observation/${r.id}`) && code(r.code).startsWith('eeg.calidad_')); }
alterationsAvailable() { return this.measures().some(m => m.id.startsWith('M30-')); }
alterations() { return this.patientResources().filter(r => r.resourceType === 'Observation' && r.code?.coding?.[0]?.system?.endsWith('/tea-eeg-metrica') && !r.id?.startsWith('electrodos-')); }
componentValue(c: Resource) { return c.valueInteger ?? c.valueString ?? (text(c.valueCodeableConcept) || 'Sin dato'); }
observationValue(o: Resource) { return o.valueInteger ?? (o.valueQuantity ? `${o.valueQuantity.value} ${o.valueQuantity.unit ?? ''}` : 'Sin dato'); }
}
+1 -20
View File
@@ -2,9 +2,6 @@ import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import {
CohortExclusionsResponse,
CohortScenario,
CohortVersion,
ModelLineage,
ModelVersion,
PromotionCheck,
@@ -15,7 +12,7 @@ import {
OcrRunSummary,
} from './governance.types';
/** `/governance/*`: model and cohort versions, artifacts, and the OCR review queue. */
/** `/governance/*`: model versions, artifacts, and the OCR review queue. */
@Injectable({ providedIn: 'root' })
export class GovernanceApi {
private readonly http = inject(HttpClient);
@@ -56,22 +53,6 @@ export class GovernanceApi {
return this.http.post<ModelVersion>(`/governance/model-versions/${domain}/${scenario}/${version}/artifacts`, form);
}
listCohortScenarios(): Observable<{ scenarios: CohortScenario[] }> {
return this.http.get<{ scenarios: CohortScenario[] }>('/governance/cohort-scenarios');
}
buildCohortVersion(domain: string, scenario: string, description?: string): Observable<CohortVersion> {
return this.http.post<CohortVersion>('/governance/cohort-versions', { domain, scenario, ...(description ? { description } : {}) });
}
listCohortVersions(filters: { domain?: string; scenario?: string } = {}): Observable<{ cohort_versions: CohortVersion[] }> {
return this.http.get<{ cohort_versions: CohortVersion[] }>('/governance/cohort-versions', { params: toParams(filters) });
}
getCohortExclusions(cohortVersionId: number): Observable<CohortExclusionsResponse> {
return this.http.get<CohortExclusionsResponse>(`/governance/cohort-versions/${cohortVersionId}/exclusions`);
}
listOcrJobs(): Observable<{ jobs: OcrJob[] }> {
return this.http.get<{ jobs: OcrJob[] }>('/governance/ocr/jobs');
}
+18 -46
View File
@@ -1,20 +1,18 @@
/** Shapes of the `/governance/*` JSON contract. */
import { Domain } from '../../connect/api/api.types';
export type Environment = 'DEV' | 'PROD';
/** Derived from MLflow on every call, never stored. */
export type ModelStatus = 'desarrollo' | 'candidata' | 'produccion' | 'retirada';
/** Training, versioning and artifact storage live in MLflow; `name` is
* `<domain>-<scenario>` and `tags` carries our own promotion-relevant
* metadata (domain, scenario, environment, cohort_version_id, the three
* metadata (domain, scenario, environment, kit.armado_id, the three
* report URIs) — MLflow has no native columns for any of that. */
export interface ModelVersion {
name: string;
version: string;
run_id: string;
tags: Partial<Record<ReportField | 'domain' | 'scenario' | 'environment' | 'cohort_version_id' | 'retirada_en' | 'promovida_en', string>>;
tags: Partial<Record<ReportField | 'domain' | 'scenario' | 'environment' | 'kit.armado_id' | 'retirada_en' | 'promovida_en', string>>;
metrics: Record<string, number>;
created_at: string;
status: ModelStatus;
@@ -35,55 +33,29 @@ export type ArtifactPath = string;
export interface ModelLineage {
model_version: ModelVersion;
cohort_version: CohortVersion | null;
cohort_exclusions: CohortExclusionCount[];
cohorte_armado: CohorteArmado | null;
cohorte_exclusiones: CohorteExclusion[];
artifacts: ArtifactPath[];
predictions: number;
checks: PromotionCheck[];
}
export interface CohortScenario {
domain: string;
scenario: string;
criteria_version: string;
criteria: { code: string; reason_code: string; applicable_in_production: boolean }[];
/** The indicator kit's cohort build the version was trained on. */
export interface CohorteArmado {
armado_id: number;
url: string;
version: string;
huella: string;
n_miembros: number;
datos_as_of: string;
armado_en: string;
}
export interface CohortVersion {
cohort_version_id: number;
domain: string;
scenario: string;
criteria_version: string;
version_hash: string;
source_table: string;
description: string | null;
n_source: number;
n_included: number;
created_at: string;
}
export interface CohortExclusionCount {
cohort_exclusion_count_id: number;
cohort_version_id: number;
criterion_code: string;
reason_code: string;
count: number;
created_at: string;
}
export interface CohortExclusionDetail {
cohort_exclusion_id: number;
cohort_version_id: number;
pac_id_hospital: string;
episodio_id: number | null;
criterion_code: string;
reason_code: string;
excluded_at: string;
}
export interface CohortExclusionsResponse {
counts: CohortExclusionCount[];
detail: CohortExclusionDetail[];
/** One attrition step of a cohort build. */
export interface CohorteExclusion {
orden: number;
paso: string;
n: number;
}
export interface OcrJob {
@@ -1,61 +0,0 @@
<h2 mat-dialog-title>Exclusiones · {{ data.cohort.scenario }} ({{ data.cohort.version_hash.slice(0, 12) }}…)</h2>
<mat-dialog-content class="exclusions">
@if (loading()) {
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
}
@if (error(); as message) {
<p class="exclusions__alert" role="alert">{{ message }}</p>
}
@if (!loading() && !error()) {
<h3>Conteo por criterio</h3>
<table mat-table [dataSource]="counts()" class="exclusions__table">
<ng-container matColumnDef="criterion_code">
<th mat-header-cell *matHeaderCellDef>Criterio</th>
<td mat-cell *matCellDef="let row">{{ row.criterion_code }}</td>
</ng-container>
<ng-container matColumnDef="reason_code">
<th mat-header-cell *matHeaderCellDef>Razón</th>
<td mat-cell *matCellDef="let row">{{ row.reason_code }}</td>
</ng-container>
<ng-container matColumnDef="count">
<th mat-header-cell *matHeaderCellDef>Conteo</th>
<td mat-cell *matCellDef="let row">{{ row.count }}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="countColumns"></tr>
<tr mat-row *matRowDef="let row; columns: countColumns"></tr>
</table>
@if (counts().length === 0) {
<p class="exclusions__empty">Ningún episodio fue excluido al construir esta cohorte.</p>
}
<h3>Bitácora por episodio</h3>
<table mat-table [dataSource]="detail()" class="exclusions__table">
<ng-container matColumnDef="pac_id_hospital">
<th mat-header-cell *matHeaderCellDef>Paciente</th>
<td mat-cell *matCellDef="let row">{{ row.pac_id_hospital }}</td>
</ng-container>
<ng-container matColumnDef="episodio_id">
<th mat-header-cell *matHeaderCellDef>Episodio</th>
<td mat-cell *matCellDef="let row">{{ row.episodio_id ?? '—' }}</td>
</ng-container>
<ng-container matColumnDef="criterion_code">
<th mat-header-cell *matHeaderCellDef>Criterio</th>
<td mat-cell *matCellDef="let row">{{ row.criterion_code }}</td>
</ng-container>
<ng-container matColumnDef="reason_code">
<th mat-header-cell *matHeaderCellDef>Razón</th>
<td mat-cell *matCellDef="let row">{{ row.reason_code }}</td>
</ng-container>
<ng-container matColumnDef="excluded_at">
<th mat-header-cell *matHeaderCellDef>Fecha</th>
<td mat-cell *matCellDef="let row">{{ row.excluded_at | date: 'short' }}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="detailColumns"></tr>
<tr mat-row *matRowDef="let row; columns: detailColumns"></tr>
</table>
}
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button type="button" mat-dialog-close>Cerrar</button>
</mat-dialog-actions>
@@ -1,32 +0,0 @@
.exclusions {
display: flex;
flex-direction: column;
gap: var(--space-2);
max-height: 70vh;
min-width: 560px;
h3 {
font: var(--mat-sys-title-small);
margin: var(--space-3) 0 0;
}
}
.exclusions__table {
width: 100%;
}
.exclusions__alert {
color: var(--mat-sys-error);
}
.exclusions__empty {
color: var(--mat-sys-on-surface-variant);
font: var(--mat-sys-body-small);
margin: 0;
}
@media (max-width: 720px) {
.exclusions {
min-width: 0;
}
}
@@ -1,51 +0,0 @@
import { DatePipe } from '@angular/common';
import { Component, OnInit, inject, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatTableModule } from '@angular/material/table';
import { apiErrorMessage } from '../../../connect/api/api.types';
import { GovernanceApi } from '../../api/governance.api';
import { CohortExclusionCount, CohortExclusionDetail, CohortVersion } from '../../api/governance.types';
export interface CohortExclusionsDialogData {
cohort: CohortVersion;
}
/**
* Exclusion counts per criterion for a cohort version, plus the
* per-episode log behind them. Both are written when the cohort is built;
* this dialog only displays them.
*/
@Component({
selector: 'app-cohort-exclusions-dialog',
imports: [DatePipe, MatButtonModule, MatDialogModule, MatProgressBarModule, MatTableModule],
templateUrl: './cohort-exclusions-dialog.html',
styleUrl: './cohort-exclusions-dialog.scss',
})
export class CohortExclusionsDialog implements OnInit {
readonly data = inject<CohortExclusionsDialogData>(MAT_DIALOG_DATA);
private readonly api = inject(GovernanceApi);
readonly loading = signal(true);
readonly error = signal<string | null>(null);
readonly counts = signal<CohortExclusionCount[]>([]);
readonly detail = signal<CohortExclusionDetail[]>([]);
readonly countColumns = ['criterion_code', 'reason_code', 'count'];
readonly detailColumns = ['pac_id_hospital', 'episodio_id', 'criterion_code', 'reason_code', 'excluded_at'];
ngOnInit(): void {
this.api.getCohortExclusions(this.data.cohort.cohort_version_id).subscribe({
next: ({ counts, detail }) => {
this.loading.set(false);
this.counts.set(counts);
this.detail.set(detail);
},
error: (error) => {
this.loading.set(false);
this.error.set(apiErrorMessage(error, 'No se pudieron cargar las exclusiones.'));
},
});
}
}
@@ -1,79 +0,0 @@
<div class="cohorts">
<div class="cohorts__toolbar">
<mat-button-toggle-group hideSingleSelectionIndicator [value]="domain()" (change)="setDomain($event.value)" aria-label="Dominio">
@for (option of domains; track option.id) {
<mat-button-toggle [value]="option.id">{{ option.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
<span class="cohorts__spacer"></span>
<button
mat-stroked-button
type="button"
[matMenuTriggerFor]="scenarioMenu"
[disabled]="building() || scenarios().length === 0"
[matTooltip]="scenarios().length ? '' : 'No hay escenarios con un constructor de cohorte registrado (models.cohort)'"
>
<mat-icon aria-hidden="true">add</mat-icon>Construir versión
</button>
<mat-menu #scenarioMenu="matMenu">
@for (scenario of scenarios(); track scenario.domain + scenario.scenario) {
<button mat-menu-item type="button" (click)="build(scenario)">
{{ scenario.domain }} · {{ scenario.scenario }} ({{ scenario.criteria_version }}, {{ scenario.criteria.length }} criterio(s))
</button>
}
</mat-menu>
<button mat-icon-button type="button" (click)="reload()" aria-label="Recargar" matTooltip="Recargar">
<mat-icon aria-hidden="true">refresh</mat-icon>
</button>
</div>
@if (loading() || building()) {
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
}
@if (loadError(); as error) {
<p class="cohorts__alert" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ error }}</p>
}
<table mat-table [dataSource]="cohorts()" class="cohorts__table">
<ng-container matColumnDef="scenario">
<th mat-header-cell *matHeaderCellDef>Dominio · escenario</th>
<td mat-cell *matCellDef="let c">{{ c.domain }} · {{ c.scenario }}</td>
</ng-container>
<ng-container matColumnDef="version_hash">
<th mat-header-cell *matHeaderCellDef>Hash de versión</th>
<td mat-cell *matCellDef="let c"><code class="cohorts__hash" [matTooltip]="c.version_hash">{{ c.version_hash.slice(0, 16) }}…</code></td>
</ng-container>
<ng-container matColumnDef="criteria_version">
<th mat-header-cell *matHeaderCellDef>Criterio</th>
<td mat-cell *matCellDef="let c">{{ c.criteria_version }}</td>
</ng-container>
<ng-container matColumnDef="counts">
<th mat-header-cell *matHeaderCellDef>Participantes</th>
<td mat-cell *matCellDef="let c">{{ c.n_included }} incluido(s) · {{ excludedCount(c) }} excluido(s) de {{ c.n_source }}</td>
</ng-container>
<ng-container matColumnDef="created_at">
<th mat-header-cell *matHeaderCellDef>Creada</th>
<td mat-cell *matCellDef="let c">{{ c.created_at | date: 'short' }}</td>
</ng-container>
<ng-container matColumnDef="acciones">
<th mat-header-cell *matHeaderCellDef></th>
<td mat-cell *matCellDef="let c">
<button mat-button type="button" (click)="openExclusions(c)">
<mat-icon aria-hidden="true">rule</mat-icon>Exclusiones
</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>
@if (!loading() && cohorts().length === 0) {
<p class="cohorts__empty"><mat-icon aria-hidden="true">dataset</mat-icon>Aún no hay cohortes construidas para este filtro.</p>
}
</div>
@@ -1,45 +0,0 @@
.cohorts {
display: flex;
flex-direction: column;
gap: var(--space-3);
}
.cohorts__toolbar {
align-items: center;
display: flex;
gap: var(--space-2);
}
.cohorts__spacer {
flex: 1;
}
.cohorts__alert {
align-items: center;
background: var(--mat-sys-error-container);
color: var(--mat-sys-on-error-container);
display: flex;
gap: var(--space-2);
margin: 0;
padding: var(--space-2) var(--space-3);
}
.cohorts__table {
width: 100%;
}
.cohorts__hash {
background: var(--mat-sys-surface-variant);
border-radius: 4px;
font-size: 12px;
padding: 2px 6px;
}
.cohorts__empty {
align-items: center;
color: var(--mat-sys-on-surface-variant);
display: flex;
font: var(--mat-sys-body-small);
gap: var(--space-2);
margin: 0;
}
@@ -1,110 +0,0 @@
import { DatePipe } from '@angular/common';
import { Component, DestroyRef, OnInit, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatDialog } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatTableModule } from '@angular/material/table';
import { MatTooltipModule } from '@angular/material/tooltip';
import { DOMAINS } from '../../../connect/state/connect-workspace.store';
import { apiErrorMessage } from '../../../connect/api/api.types';
import { GovernanceApi } from '../../api/governance.api';
import { CohortScenario, CohortVersion } from '../../api/governance.types';
import { CohortExclusionsDialog, CohortExclusionsDialogData } from '../cohort-exclusions-dialog/cohort-exclusions-dialog';
/**
* Frozen, hashed cohort versions with their exclusion counts and log.
* Scenarios with a registered builder can produce a
* new version from here.
*/
@Component({
selector: 'app-cohort-versions-panel',
imports: [
DatePipe,
MatButtonModule,
MatButtonToggleModule,
MatIconModule,
MatMenuModule,
MatProgressBarModule,
MatSnackBarModule,
MatTableModule,
MatTooltipModule,
],
templateUrl: './cohort-versions-panel.html',
styleUrl: './cohort-versions-panel.scss',
})
export class CohortVersionsPanel implements OnInit {
private readonly api = inject(GovernanceApi);
private readonly dialog = inject(MatDialog);
private readonly destroyRef = inject(DestroyRef);
private readonly snackBar = inject(MatSnackBar);
readonly domains = [{ id: null, label: 'Todos' }, ...DOMAINS.map((d) => ({ id: d.id as string | null, label: d.label }))];
readonly domain = signal<string | null>(null);
readonly cohorts = signal<CohortVersion[]>([]);
readonly loading = signal(false);
readonly loadError = signal<string | null>(null);
readonly scenarios = signal<CohortScenario[]>([]);
readonly building = signal(false);
readonly displayedColumns = ['scenario', 'version_hash', 'criteria_version', 'counts', 'created_at', 'acciones'];
ngOnInit(): void {
this.reload();
this.api.listCohortScenarios().subscribe({ next: ({ scenarios }) => this.scenarios.set(scenarios), error: () => this.scenarios.set([]) });
}
build(scenario: CohortScenario): void {
this.building.set(true);
this.api.buildCohortVersion(scenario.domain, scenario.scenario).subscribe({
next: (cohort) => {
this.building.set(false);
this.snackBar.open(`Cohorte ${cohort.scenario} construida: ${cohort.n_included} de ${cohort.n_source} episodios.`, 'OK', { duration: 5000 });
this.reload();
},
error: (error) => {
this.building.set(false);
this.snackBar.open(apiErrorMessage(error, 'No se pudo construir la cohorte.'), 'OK', { duration: 6000 });
},
});
}
setDomain(domain: string | null): void {
this.domain.set(domain);
this.reload();
}
reload(): void {
this.loading.set(true);
this.loadError.set(null);
this.api
.listCohortVersions(this.domain() ? { domain: this.domain()! } : {})
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({
next: ({ cohort_versions }) => {
this.loading.set(false);
this.cohorts.set(cohort_versions);
},
error: (error) => {
this.loading.set(false);
this.loadError.set(apiErrorMessage(error, 'No se pudieron cargar las versiones de cohorte.'));
},
});
}
openExclusions(cohort: CohortVersion): void {
this.dialog.open<CohortExclusionsDialog, CohortExclusionsDialogData>(CohortExclusionsDialog, {
width: '720px',
maxWidth: '96vw',
data: { cohort },
});
}
excludedCount(cohort: CohortVersion): number {
return cohort.n_source - cohort.n_included;
}
}
@@ -12,11 +12,6 @@
<app-model-versions-panel></app-model-versions-panel>
</div>
</mat-tab>
<mat-tab label="Cohortes">
<div class="governance__panel">
<app-cohort-versions-panel></app-cohort-versions-panel>
</div>
</mat-tab>
<mat-tab label="Revisión de OCR">
<div class="governance__panel">
<app-ocr-review-panel></app-ocr-review-panel>
@@ -1,18 +1,17 @@
import { Component } from '@angular/core';
import { MatTabsModule } from '@angular/material/tabs';
import { MatToolbarModule } from '@angular/material/toolbar';
import { CohortVersionsPanel } from '../cohort-versions-panel/cohort-versions-panel';
import { ModelVersionsPanel } from '../model-versions-panel/model-versions-panel';
import { OcrReviewPanel } from '../ocr-review-panel/ocr-review-panel';
/**
* The "Gobernanza de modelos" page (route `/gobernanza`): model versions,
* cohorts and the OCR review queue, one tab each. Every tab is a
* The "Gobernanza de modelos" page (route `/gobernanza`): model versions
* and the OCR review queue, one tab each. Every tab is a
* self-contained panel that loads its own data.
*/
@Component({
selector: 'app-governance-page',
imports: [CohortVersionsPanel, MatTabsModule, MatToolbarModule, ModelVersionsPanel, OcrReviewPanel],
imports: [MatTabsModule, MatToolbarModule, ModelVersionsPanel, OcrReviewPanel],
templateUrl: './governance-page.html',
styleUrl: './governance-page.scss',
})
@@ -58,18 +58,23 @@
<section aria-labelledby="cohort-title">
<h3 id="cohort-title">Cohorte de entrenamiento</h3>
@if (l.cohort_version; as cohort) {
@if (l.cohorte_armado; as armado) {
<p>
{{ cohort.domain }} · {{ cohort.scenario }} · criterio {{ cohort.criteria_version }} ·
{{ cohort.n_included | number }} de {{ cohort.n_source | number }} episodios
{{ armado.url }} · versión {{ armado.version }} · {{ armado.n_miembros | number }} miembros ·
datos al {{ armado.datos_as_of | date: 'mediumDate' }}
</p>
<p class="hash" [matTooltip]="cohort.version_hash">hash {{ cohort.version_hash.slice(0, 16) }}…</p>
@if (l.cohort_exclusions.length) {
<ul class="exclusions">
@for (count of l.cohort_exclusions; track count.cohort_exclusion_count_id) {
<li>{{ count.criterion_code }} ({{ count.reason_code }}): {{ count.count | number }} excluidos</li>
}
</ul>
<p class="hash" [matTooltip]="armado.huella">huella {{ armado.huella.slice(0, 12) }}… · armado {{ armado.armado_id }}</p>
@if (l.cohorte_exclusiones.length) {
<table class="exclusions">
<thead>
<tr><th>#</th><th>Paso</th><th>Quedan</th></tr>
</thead>
<tbody>
@for (paso of l.cohorte_exclusiones; track paso.orden) {
<tr><td>{{ paso.orden }}</td><td>{{ paso.paso }}</td><td>{{ paso.n | number }}</td></tr>
}
</tbody>
</table>
}
} @else {
<p class="muted">Sin cohorte enlazada.</p>
@@ -49,8 +49,7 @@
}
.checks,
.artifacts,
.exclusions {
.artifacts {
display: flex;
flex-direction: column;
gap: var(--space-1);
@@ -111,3 +110,19 @@
justify-self: start;
}
}
.exclusions {
border-collapse: collapse;
font-size: 0.875rem;
th,
td {
padding: var(--space-1) var(--space-2);
text-align: left;
}
td:last-child,
th:last-child {
text-align: right;
}
}
@@ -26,7 +26,7 @@ export const ARTIFACT_KINDS: { id: string; label: string }[] = [
];
/**
* One model version: what it was trained on (cohort hash and exclusions),
* One model version: what it was trained on (the kit's cohort build and its attrition),
* its artifacts and their integrity, its validation reports, and the
* checklist that must pass before it can serve predictions. Closes with
* `true` when the version changed.
@@ -45,9 +45,9 @@
</td>
</ng-container>
<ng-container matColumnDef="cohort_version_id">
<th mat-header-cell *matHeaderCellDef>Cohorte</th>
<td mat-cell *matCellDef="let v">{{ v.tags.cohort_version_id ?? '— (sin enlazar)' }}</td>
<ng-container matColumnDef="armado">
<th mat-header-cell *matHeaderCellDef>Armado de cohorte</th>
<td mat-cell *matCellDef="let v">{{ v.tags['kit.armado_id'] ?? 'Sin enlazar' }}</td>
</ng-container>
<ng-container matColumnDef="status">
@@ -51,7 +51,7 @@ export class ModelVersionsPanel implements OnInit {
readonly loading = signal(false);
readonly loadError = signal<string | null>(null);
readonly displayedColumns = ['version', 'scenario', 'environment', 'cohort_version_id', 'status', 'created_at', 'acciones'];
readonly displayedColumns = ['version', 'scenario', 'environment', 'armado', 'status', 'created_at', 'acciones'];
ngOnInit(): void {
this.reload();
+40 -40
View File
@@ -10,26 +10,26 @@
</mat-toolbar>
<div class="reportes__body">
@if (error(); as mensaje) {
<p class="reportes__error" role="alert">{{ mensaje }}</p>
@if (error(); as message) {
<p class="reportes__error" role="alert">{{ message }}</p>
}
<section aria-labelledby="estado-title">
<h2 id="estado-title">Indicadores</h2>
<p class="reportes__hint">Los indicadores se recalculan automáticamente después de cada carga de información.</p>
<div class="estado-grid">
@for (dominio of dominios; track dominio.id) {
@if (estados()?.[dominio.id]; as estado) {
<article class="estado" [attr.data-estado]="estado.estado">
<h3>{{ dominio.nombre }}</h3>
<p class="estado__valor">{{ estadoTexto(estado) }}</p>
@if (estado.fin) {
<p>Último cálculo: {{ estado.fin | date: 'dd/MM/yyyy HH:mm' }} ({{ estado.duracion_s | number: '1.0-1' }} s)</p>
@for (domain of domains; track domain.id) {
@if (statuses()?.[domain.id]; as status) {
<article class="estado" [attr.data-estado]="status.estado">
<h3>{{ domain.description }}</h3>
<p class="estado__valor">{{ statusLabel(status) }}</p>
@if (status.fin) {
<p>Último cálculo: {{ status.fin | date: 'dd/MM/yyyy HH:mm' }} ({{ status.duracion_s | number: '1.0-1' }} s)</p>
}
@if (estado.error) {
<p class="estado__error">{{ estado.error.tipo }}: {{ estado.error.mensaje }}</p>
@if (status.error) {
<p class="estado__error">{{ status.error.tipo }}: {{ status.error.mensaje }}</p>
}
<button mat-button type="button" (click)="recalcular(dominio.id)" [disabled]="estado.pendiente || estado.estado === 'en_curso'">
<button mat-button type="button" (click)="recompute(domain.id)" [disabled]="status.pendiente || status.estado === 'en_curso'">
<mat-icon aria-hidden="true">refresh</mat-icon>Recalcular
</button>
</article>
@@ -41,7 +41,7 @@
<section aria-labelledby="intentos-title">
<h2 id="intentos-title">Intentos de carga y validación</h2>
<p class="reportes__hint">La bitácora registra únicamente conteos y formatos agregados; no almacena valores de los registros.</p>
@if (intentos().length === 0) {
@if (attempts().length === 0) {
<p>No se han registrado intentos de carga o validación.</p>
} @else {
<table class="intentos">
@@ -52,33 +52,33 @@
</tr>
</thead>
<tbody>
@for (intento of intentos(); track intento.id) {
<tr [attr.data-resultado]="intento.resultado">
<td>{{ intento.fecha | date: 'dd/MM/yyyy HH:mm' }}</td>
<td>{{ intento.operacion === 'carga' ? 'Carga' : 'Validación' }}</td>
<td>{{ intento.fuentes.length ? intento.fuentes[0].destino : (intento.dominio ?? '—') }}@if (intento.fuentes.length > 1) { <span> +{{ intento.fuentes.length - 1 }}</span> }</td>
<td>{{ resultadoTexto(intento.resultado) }}</td>
<td>{{ intento.totales['leidas'] ?? 0 }}</td>
<td>{{ intento.totales['validas'] ?? 0 }}</td>
<td>{{ (intento.totales['insertadas'] ?? 0) + (intento.totales['actualizadas'] ?? 0) }}</td>
<td>{{ (intento.totales['rechazadas_en_validacion'] ?? 0) + (intento.totales['rechazadas_por_conflicto'] ?? 0) }}</td>
@for (attempt of attempts(); track attempt.id) {
<tr [attr.data-resultado]="attempt.resultado">
<td>{{ attempt.fecha | date: 'dd/MM/yyyy HH:mm' }}</td>
<td>{{ attempt.operacion === 'carga' ? 'Carga' : 'Validación' }}</td>
<td>{{ attempt.fuentes.length ? attempt.fuentes[0].destino : (attempt.dominio ?? '—') }}@if (attempt.fuentes.length > 1) { <span> +{{ attempt.fuentes.length - 1 }}</span> }</td>
<td>{{ outcomeLabel(attempt.resultado) }}</td>
<td>{{ attempt.totales['leidas'] ?? 0 }}</td>
<td>{{ attempt.totales['validas'] ?? 0 }}</td>
<td>{{ (attempt.totales['insertadas'] ?? 0) + (attempt.totales['actualizadas'] ?? 0) }}</td>
<td>{{ (attempt.totales['rechazadas_en_validacion'] ?? 0) + (attempt.totales['rechazadas_por_conflicto'] ?? 0) }}</td>
<td>
<button mat-icon-button type="button" (click)="alternar(intento.id)" [attr.aria-expanded]="abierto() === intento.id" aria-label="Ver detalle">
<mat-icon>{{ abierto() === intento.id ? 'expand_less' : 'expand_more' }}</mat-icon>
<button mat-icon-button type="button" (click)="toggle(attempt.id)" [attr.aria-expanded]="expanded() === attempt.id" aria-label="Ver detalle">
<mat-icon>{{ expanded() === attempt.id ? 'expand_less' : 'expand_more' }}</mat-icon>
</button>
</td>
</tr>
@if (abierto() === intento.id) {
@if (expanded() === attempt.id) {
<tr class="detalle">
<td colspan="9">
@if (intento.error) {
<p class="estado__error">{{ intento.error.tipo }}: {{ intento.error.mensaje }}</p>
@if (attempt.error) {
<p class="estado__error">{{ attempt.error.tipo }}: {{ attempt.error.mensaje }}</p>
}
@for (fuente of intento.fuentes; track $index) {
@for (source of attempt.fuentes; track $index) {
<p>
<strong>{{ fuente.destino }}</strong> desde {{ fuente.origen.tipo }}
@if (fuente.mapeo.requeridos_sin_mapear.length) {
· requeridos sin mapear: {{ fuente.mapeo.requeridos_sin_mapear.join(', ') }}
<strong>{{ source.destino }}</strong> desde {{ source.origen.tipo }}
@if (source.mapeo.requeridos_sin_mapear.length) {
· requeridos sin mapear: {{ source.mapeo.requeridos_sin_mapear.join(', ') }}
}
</p>
}
@@ -87,16 +87,16 @@
<tr><th scope="col">Campo</th><th scope="col">Con valor</th><th scope="col">Vacíos</th><th scope="col">Errores</th><th scope="col">Formatos o valores rechazados</th></tr>
</thead>
<tbody>
@for (fila of camposConProblemas(intento); track fila.destino + fila.nombre) {
@for (row of fieldsWithProblems(attempt); track row.target + row.name) {
<tr>
<td>{{ fila.nombre }}</td>
<td>{{ fila.campo.con_valor }}</td>
<td>{{ fila.campo.vacios }}</td>
<td>@for (e of fila.campo.errores | keyvalue; track e.key) { <span class="chip">{{ e.key }}: {{ e.value }}</span> }</td>
<td>{{ row.name }}</td>
<td>{{ row.field.con_valor }}</td>
<td>{{ row.field.vacios }}</td>
<td>@for (e of row.field.errores | keyvalue; track e.key) { <span class="chip">{{ e.key }}: {{ e.value }}</span> }</td>
<td>
@for (f of fila.campo.formatos_rechazados | keyvalue; track f.key) { <span class="chip"><code>{{ f.key }}</code> ×{{ f.value }}</span> }
@for (v of fila.campo.valores_fuera_de_catalogo | keyvalue; track v.key) { <span class="chip">{{ v.key }} ×{{ v.value }}</span> }
@if (fila.campo.valores_fuera_de_catalogo_poco_frecuentes) { <span class="chip">otros ×{{ fila.campo.valores_fuera_de_catalogo_poco_frecuentes }}</span> }
@for (f of row.field.formatos_rechazados | keyvalue; track f.key) { <span class="chip"><code>{{ f.key }}</code> ×{{ f.value }}</span> }
@for (v of row.field.valores_fuera_de_catalogo | keyvalue; track v.key) { <span class="chip">{{ v.key }} ×{{ v.value }}</span> }
@if (row.field.valores_fuera_de_catalogo_poco_frecuentes) { <span class="chip">otros ×{{ row.field.valores_fuera_de_catalogo_poco_frecuentes }}</span> }
</td>
</tr>
} @empty {
+26 -6
View File
@@ -1,14 +1,14 @@
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { ReportesPage } from './reportes-page';
import { ReportsPage } from './reportes-page';
describe('ReportesPage', () => {
describe('ReportsPage', () => {
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ReportesPage],
imports: [ReportsPage],
providers: [provideHttpClient(), provideHttpClientTesting()],
});
http = TestBed.inject(HttpTestingController);
@@ -17,7 +17,7 @@ describe('ReportesPage', () => {
afterEach(() => http.verify());
it('shows the indicator status and the aggregate attempts', () => {
const fixture = TestBed.createComponent(ReportesPage);
const fixture = TestBed.createComponent(ReportsPage);
fixture.detectChanges();
http.expectOne('/reportes/indicadores').flush({
cacu: { estado: 'ok', pendiente: false, fin: '2026-10-29T10:00:00+00:00', duracion_s: 12 },
@@ -48,9 +48,29 @@ describe('ReportesPage', () => {
expect(fixture.nativeElement.querySelector('.campos').textContent).toContain('out_of_catalog: 2');
});
it('keeps polling after a failed request', () => {
vi.useFakeTimers();
try {
const fixture = TestBed.createComponent(ReportsPage);
fixture.detectChanges();
http.expectOne('/reportes/indicadores').flush('caída', { status: 502, statusText: 'Bad Gateway' });
http.expectOne((r) => r.url === '/reportes/importaciones');
expect(fixture.componentInstance.error()).toBeTruthy();
vi.advanceTimersByTime(15000);
http.expectOne('/reportes/indicadores').flush({ cacu: { estado: 'ok', pendiente: false } });
http.expectOne((r) => r.url === '/reportes/importaciones').flush({ resumen: { intentos: {}, ultimo: null }, intentos: [] });
expect(fixture.componentInstance.error()).toBeNull();
expect(fixture.componentInstance.statuses()?.cacu.estado).toBe('ok');
fixture.destroy();
} finally {
vi.useRealTimers();
}
});
it('asks for a recomputation', () => {
const fixture = TestBed.createComponent(ReportesPage);
fixture.componentInstance.recalcular('tea');
const fixture = TestBed.createComponent(ReportsPage);
fixture.componentInstance.recompute('tea');
http.expectOne('/reportes/indicadores/tea/recalcular').flush({ pendiente: true });
});
});
+40 -44
View File
@@ -4,87 +4,83 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatToolbarModule } from '@angular/material/toolbar';
import { forkJoin, interval, startWith, switchMap } from 'rxjs';
import { apiErrorMessage } from '../connect/api/api.types';
import { Dominio, EstadoRecalculo, IntentoImportacion, ReportesApi } from './reportes.api';
import { EMPTY, catchError, forkJoin, interval, startWith, switchMap } from 'rxjs';
import { Domain, apiErrorMessage } from '../connect/api/api.types';
import { DOMAINS } from '../connect/state/connect-workspace.store';
import { ImportAttempt, RecomputeStatus, ReportsApi } from './reportes.api';
const DOMINIOS: { id: Dominio; nombre: string }[] = [
{ id: 'cacu', nombre: 'Cáncer cervicouterino' },
{ id: 'cama', nombre: 'Cáncer de mama' },
{ id: 'tea', nombre: 'Trastorno del espectro autista' },
];
const ESTADOS: Record<string, string> = {
const STATUS_LABELS: Record<string, string> = {
sin_correr: 'Pendiente de cálculo', en_curso: 'En proceso de cálculo', ok: 'Actualizado', error: 'Error en el cálculo',
};
const RESULTADOS: Record<string, string> = {
const OUTCOME_LABELS: Record<string, string> = {
completada: 'Completada', solicitud_invalida: 'Solicitud inválida',
rechazada_por_la_base: 'Rechazada por la base', fallida: 'Fallida',
};
/**
* The "Bitácora" page (route `/bitacora`): what happened to every import
* attempt, in aggregates only, and whether each domain's indicators are up
* to date with what was loaded. Refreshes itself every 15 seconds.
*/
/** The import log page (`/bitacora`): import attempts in aggregate and the indicator status per domain. */
@Component({
selector: 'app-reportes-page',
imports: [DatePipe, DecimalPipe, KeyValuePipe, MatButtonModule, MatIconModule, MatToolbarModule],
templateUrl: './reportes-page.html',
styleUrl: './reportes-page.scss',
})
export class ReportesPage implements OnInit {
private readonly api = inject(ReportesApi);
export class ReportsPage implements OnInit {
private readonly api = inject(ReportsApi);
private readonly destroyRef = inject(DestroyRef);
readonly dominios = DOMINIOS;
readonly estados = signal<Record<Dominio, EstadoRecalculo> | null>(null);
readonly intentos = signal<IntentoImportacion[]>([]);
readonly abierto = signal<string | null>(null);
readonly domains = DOMAINS;
readonly statuses = signal<Record<Domain, RecomputeStatus> | null>(null);
readonly attempts = signal<ImportAttempt[]>([]);
readonly expanded = signal<string | null>(null);
readonly error = signal<string | null>(null);
ngOnInit(): void {
interval(15000)
.pipe(
startWith(0),
switchMap(() => forkJoin({ estados: this.api.indicadores(), log: this.api.importaciones() })),
// Errors are handled per poll so one failed request doesn't stop the refresh.
switchMap(() =>
forkJoin({ statuses: this.api.indicatorStatus(), log: this.api.importLog() }).pipe(
catchError((err) => {
this.error.set(apiErrorMessage(err, 'No se pudo leer la bitácora.'));
return EMPTY;
}),
),
),
takeUntilDestroyed(this.destroyRef),
)
.subscribe({
next: ({ estados, log }) => {
this.estados.set(estados);
this.intentos.set(log.intentos);
this.error.set(null);
},
error: (err) => this.error.set(apiErrorMessage(err, 'No se pudo leer la bitácora.')),
.subscribe(({ statuses, log }) => {
this.statuses.set(statuses);
this.attempts.set(log.intentos);
this.error.set(null);
});
}
estadoTexto(estado: EstadoRecalculo): string {
return estado.pendiente && estado.estado !== 'en_curso' ? 'En espera de cálculo' : ESTADOS[estado.estado] ?? estado.estado;
statusLabel(status: RecomputeStatus): string {
return status.pendiente && status.estado !== 'en_curso' ? 'En espera de cálculo' : STATUS_LABELS[status.estado] ?? status.estado;
}
resultadoTexto(resultado: string): string {
return RESULTADOS[resultado] ?? resultado;
outcomeLabel(outcome: string): string {
return OUTCOME_LABELS[outcome] ?? outcome;
}
recalcular(dominio: Dominio): void {
this.api.recalcular(dominio).subscribe({
next: () => this.estados.update((e) => (e ? { ...e, [dominio]: { ...e[dominio], pendiente: true } } : e)),
recompute(domain: Domain): void {
this.api.recompute(domain).subscribe({
next: () => this.statuses.update((s) => (s ? { ...s, [domain]: { ...s[domain], pendiente: true } } : s)),
error: (err) => this.error.set(apiErrorMessage(err, 'No se pudo solicitar el recálculo.')),
});
}
alternar(id: string): void {
this.abierto.update((actual) => (actual === id ? null : id));
toggle(id: string): void {
this.expanded.update((current) => (current === id ? null : id));
}
camposConProblemas(intento: IntentoImportacion) {
return intento.fuentes.flatMap((fuente) =>
Object.entries(fuente.campos)
.filter(([, campo]) => campo.errores || campo.vacios)
.map(([nombre, campo]) => ({ destino: fuente.destino, nombre, campo })),
fieldsWithProblems(attempt: ImportAttempt) {
return attempt.fuentes.flatMap((source) =>
Object.entries(source.campos)
.filter(([, field]) => field.errores || field.vacios)
.map(([name, field]) => ({ target: source.destino, name, field })),
);
}
}
+20 -19
View File
@@ -1,10 +1,11 @@
import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { Domain } from '../connect/api/api.types';
export type Dominio = 'cacu' | 'cama' | 'tea';
// Field names follow the JSON the API writes to the log.
export interface CampoReporte {
export interface FieldReport {
con_valor: number;
vacios: number;
errores?: Record<string, number>;
@@ -13,33 +14,33 @@ export interface CampoReporte {
valores_fuera_de_catalogo_poco_frecuentes?: number;
}
export interface FuenteReporte {
export interface SourceReport {
destino: string;
origen: { tipo: string; extensiones?: string[]; archivos?: number; motor?: string | null };
mapeo: { requeridos_sin_mapear: string[]; campos_sin_mapear: string[]; columnas_origen: string[] };
filas: Record<string, number>;
campos: Record<string, CampoReporte>;
campos: Record<string, FieldReport>;
}
/** One line of the aggregate import log (`/reportes/importaciones`). */
export interface IntentoImportacion {
/** One line of the aggregate import log. */
export interface ImportAttempt {
id: string;
fecha: string;
operacion: 'validacion' | 'carga';
dominio: Dominio | null;
dominio: Domain | null;
resultado: string;
duracion_s: number;
totales: Record<string, number>;
fuentes: FuenteReporte[];
fuentes: SourceReport[];
error?: { tipo: string; mensaje: string };
}
export interface ReporteImportaciones {
export interface ImportLog {
resumen: { intentos: Record<string, number>; ultimo: string | null };
intentos: IntentoImportacion[];
intentos: ImportAttempt[];
}
export interface EstadoRecalculo {
export interface RecomputeStatus {
estado: 'sin_correr' | 'en_curso' | 'ok' | 'error';
pendiente: boolean;
inicio?: string;
@@ -49,20 +50,20 @@ export interface EstadoRecalculo {
error?: { tipo: string; mensaje: string };
}
/** `/reportes/*`: the aggregate import log and the live indicator recomputation. */
/** `/reportes/*`: the aggregate import log and the indicator recomputation. */
@Injectable({ providedIn: 'root' })
export class ReportesApi {
export class ReportsApi {
private readonly http = inject(HttpClient);
importaciones(limite = 100): Observable<ReporteImportaciones> {
return this.http.get<ReporteImportaciones>('/reportes/importaciones', { params: new HttpParams().set('limite', limite) });
importLog(limit = 100): Observable<ImportLog> {
return this.http.get<ImportLog>('/reportes/importaciones', { params: new HttpParams().set('limite', limit) });
}
indicadores(): Observable<Record<Dominio, EstadoRecalculo>> {
return this.http.get<Record<Dominio, EstadoRecalculo>>('/reportes/indicadores');
indicatorStatus(): Observable<Record<Domain, RecomputeStatus>> {
return this.http.get<Record<Domain, RecomputeStatus>>('/reportes/indicadores');
}
recalcular(dominio: Dominio): Observable<{ pendiente: boolean }> {
return this.http.post<{ pendiente: boolean }>(`/reportes/indicadores/${dominio}/recalcular`, {});
recompute(domain: Domain): Observable<{ pendiente: boolean }> {
return this.http.post<{ pendiente: boolean }>(`/reportes/indicadores/${domain}/recalcular`, {});
}
}
+3 -5
View File
@@ -25,9 +25,7 @@
--space-8: 48px;
--space-9: 64px;
/* Aliases for the `--issste-*` tokens the vendored `features/indicadores`
module (fork `dev`) is written against, so it can be pulled in byte-
identical rather than rewritten against our own naming. */
/* Aliases for the tokens used by `features/indicadores`. */
--issste-text: var(--color-text);
--issste-text-secondary: var(--color-text-secondary);
--issste-background: var(--color-background);
@@ -111,8 +109,8 @@ body {
}
/* Global rules of the vendored indicators dashboard (fork `dev`) that live
outside the component's own styles. */
/* Global rules of the indicators dashboard: its floating navigation trigger
and overlay live outside the component's own styles. */
:root {
--issste-header-clearance: 7rem;
}