Compare commits

...

8 Commits

68 changed files with 3542 additions and 774 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;
+7 -1
View File
@@ -23,9 +23,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}`,
+66 -2
View File
@@ -85,6 +85,8 @@ export interface PreviewResponse {
/** Sub-tables the source offers (Excel sheets...), with the options to read each. */
tables?: { name: string; options: Record<string, unknown>; kind: string }[];
source_metadata?: Record<string, unknown>;
/** Columns whose sampled cells hold files (PDF, images) that can be read as documents. */
document_columns?: string[];
}
export interface FileOptions {
@@ -134,9 +136,59 @@ export interface ImportSourcePayload extends SourceLocator {
label?: string;
column_mapping: Record<string, string>;
defaults?: Record<string, unknown>;
derived?: Record<string, DerivationRule>;
documents?: DocumentColumnsConfig;
/** Also store, on the patient, captions the documents print that the project's catalog already knows. */
catalog_fallback?: boolean;
}
// -- documents -----------------------------------------------------------------
// Derived fields and document columns
export type DerivationParamKind = 'column' | 'columns' | 'text' | 'integer' | 'mapping' | 'boolean';
export interface DerivationParam {
name: string;
kind: DerivationParamKind;
label: string;
required: boolean;
default: unknown;
}
/** One operation a derived field may use, as `/imports/derivations` lists it. */
export interface DerivationSpec {
op: string;
label: string;
description: string;
params: DerivationParam[];
}
export interface DerivationCatalog {
derivations: DerivationSpec[];
cases: string[];
}
/** `{op, ...params, case?}`: how one target field is computed from source columns. */
export type DerivationRule = { op: string; case?: string } & Record<string, unknown>;
/** A grouping or naming given as a column, a list of columns or a rule. */
export type ColumnRule = string | string[] | DerivationRule;
/** Which columns of a source hold documents, and how their records are formed. */
export interface DocumentColumnsConfig {
columns: string[];
group_by?: ColumnRule;
name_by?: ColumnRule;
file_field?: string;
segmentation?: string;
pages_per_record?: number;
ocr_mode?: OcrMode;
key_pattern?: string;
include_pattern?: string;
exclude_pattern?: string;
overrides?: Record<string, Record<string, unknown>>;
}
// Clinical documents
export type OcrMode = 'auto' | 'always' | 'never';
@@ -145,13 +197,19 @@ export interface DocumentSettings {
pages_per_record: number;
ocr_mode: OcrMode;
key_pattern: string;
/** Only documents whose text matches (regular expression, case and accents ignored). */
include_pattern?: string;
/** Documents whose text matches are left out. */
exclude_pattern?: string;
}
export interface ExtractedField {
value: unknown;
confidence: number;
/** etiqueta | patron | texto_libre | manual */
/** etiqueta | patron | texto_libre | medicion | columna_fuente | manual */
method: string;
/** What the report says about the mention: afirmado, negado, incierto, hipotetico, historico, presuntivo. */
assertion?: string | null;
raw?: string;
document?: string;
page_number?: number;
@@ -175,6 +233,10 @@ export interface ExtractedRecord {
conflicts: { field: string; kept: ExtractedField; discarded: ExtractedField }[];
sources: { document: string; page_numbers: number[] }[];
images: DocumentImage[];
/** `false` when the pages only name another kind of study than the target's; `null` when they name none. */
on_topic?: boolean | null;
/** Per field, the other values the extractors proposed, best first. */
alternatives?: Record<string, ExtractedField[]>;
}
export interface DocumentFieldSpec {
@@ -188,6 +250,8 @@ export interface DocumentExtraction extends PreviewResponse {
key_field: string | null;
fields: DocumentFieldSpec[];
records: ExtractedRecord[];
/** The extraction code's version and its ranker's, as stored with each row. */
nlp_version?: string;
}
export interface RowError {
+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);
});
}
+32 -3
View File
@@ -1,12 +1,41 @@
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { BatchResult, ConflictStrategy, ImportSourcePayload, ValidationResult } from './api.types';
import { Observable, shareReplay } from 'rxjs';
import {
BatchResult,
ConflictStrategy,
DerivationCatalog,
ImportSourcePayload,
PreviewResponse,
Row,
ValidationResult,
} from './api.types';
/** POST /imports/validate (one source, writes nothing) and POST /imports/commit (a batch, one transaction). */
/**
* POST /imports/validate (one source, writes nothing), POST /imports/commit
* (a batch, one transaction), the rows a source would write
* (POST /imports/mapped-preview), the columns documents add to a source
* (POST /imports/sources/document/columns) and the operations derived
* fields may use (GET /imports/derivations, fetched once).
*/
@Injectable({ providedIn: 'root' })
export class ImportsApi {
private readonly http = inject(HttpClient);
private catalog?: Observable<DerivationCatalog>;
derivations(): Observable<DerivationCatalog> {
this.catalog ??= this.http.get<DerivationCatalog>('/imports/derivations').pipe(shareReplay(1));
return this.catalog;
}
/** A source with document columns: its own columns plus every field and caption its documents print. */
documentColumns(source: ImportSourcePayload): Observable<PreviewResponse> {
return this.http.post<PreviewResponse>('/imports/sources/document/columns', { source });
}
mappedPreview(source: ImportSourcePayload, limit = 20): Observable<{ rows: Row[] }> {
return this.http.post<{ rows: Row[] }>('/imports/mapped-preview', { source, limit });
}
validate(source: ImportSourcePayload): Observable<ValidationResult> {
return this.http.post<ValidationResult>('/imports/validate', { source });
@@ -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') {
@@ -85,6 +85,31 @@
</mat-form-field>
</form>
} @else {
@if (savedConnections().length) {
<div class="saved-connections">
<span class="saved-connections__label">Conexiones guardadas</span>
<div class="saved-connections__list">
@for (saved of savedConnections(); track saved.id) {
<div class="saved-connection">
<button type="button" class="saved-connection__pick" matRipple (click)="applySaved(saved)">
<mat-icon aria-hidden="true">storage</mat-icon>
<span>{{ saved.label }}</span>
</button>
<button
mat-icon-button
type="button"
class="saved-connection__forget"
(click)="forgetSaved(saved, $event)"
aria-label="Olvidar esta conexión guardada"
matTooltip="Olvidar"
>
<mat-icon aria-hidden="true">close</mat-icon>
</button>
</div>
}
</div>
</div>
}
<form [formGroup]="serverForm" class="db-form" (ngSubmit)="connectDatabase()">
<mat-form-field appearance="outline" class="db-form__host">
<mat-label>Servidor</mat-label>
@@ -108,6 +133,9 @@
<input matInput type="password" formControlName="password" autocomplete="new-password" />
</mat-form-field>
</form>
<mat-checkbox [checked]="remember()" (change)="remember.set($event.checked)">
Recordar servidor, usuario y base de datos (nunca la contraseña)
</mat-checkbox>
}
@if (testing()) {
@@ -80,6 +80,62 @@
color: var(--mat-sys-on-surface-variant);
}
.saved-connections {
margin-bottom: var(--space-4);
}
.saved-connections__label {
color: var(--mat-sys-on-surface-variant);
display: block;
font: var(--mat-sys-label-small);
margin-bottom: var(--space-1);
}
.saved-connections__list {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
.saved-connection {
align-items: center;
background: var(--mat-sys-surface-variant);
border-radius: var(--mat-sys-corner-full);
display: flex;
gap: var(--space-1);
padding-right: var(--space-1);
}
.saved-connection__pick {
align-items: center;
background: none;
border: 0;
color: var(--mat-sys-on-surface-variant);
cursor: pointer;
display: flex;
font: var(--mat-sys-body-small);
gap: var(--space-1);
padding: var(--space-1) 0 var(--space-1) var(--space-3);
mat-icon {
font-size: 18px;
height: 18px;
width: 18px;
}
}
.saved-connection__forget {
--mdc-icon-button-state-layer-size: 28px;
height: 28px;
width: 28px;
mat-icon {
font-size: 16px;
height: 16px;
width: 16px;
}
}
.db-form {
display: grid;
gap: 0 var(--space-4);
@@ -1,6 +1,7 @@
import { Component, computed, inject, signal } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
@@ -17,6 +18,7 @@ import { SourceGateway } from '../../api/source-gateway';
import { connectionsFor } from '../../domain/connection-registry';
import { GALLERY_CATEGORIES, GalleryCategory, GalleryEntry, galleryEntries } from '../../domain/connector-catalog';
import { DataConnection } from '../../domain/data-source';
import { SavedSqlConnection, listSavedSqlConnections, removeSqlConnection, saveSqlConnection } from '../../domain/saved-sql-connections';
import { SqlConnection } from '../../domain/sql-source';
import { describeSqlServer, describeSqlUrl } from '../../domain/sql-url';
import { FileDropzone } from '../file-dropzone/file-dropzone';
@@ -33,6 +35,7 @@ type View = 'catalog' | 'files' | 'database';
imports: [
FileDropzone,
MatButtonModule,
MatCheckboxModule,
MatDialogModule,
MatFormFieldModule,
MatIconModule,
@@ -83,10 +86,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],
@@ -97,6 +98,7 @@ export class ConnectorGalleryDialog {
readonly urlForm = this.formBuilder.nonNullable.group({ url: ['', Validators.required] });
readonly testing = signal(false);
readonly testResult = signal<{ ok: boolean; message: string } | null>(null);
readonly remember = signal(false);
readonly engine = computed(() => this.entry()?.engine ?? null);
readonly serverEngine = computed(() => {
@@ -104,10 +106,29 @@ export class ConnectorGalleryDialog {
return engine && engine !== 'url' ? engine : null;
});
private readonly savedConnectionsAll = signal(listSavedSqlConnections());
/** Only the ones for the engine currently picked, so a saved SQL Server entry never fills a MySQL form. */
readonly savedConnections = computed(() => {
const engineId = this.serverEngine()?.id;
return engineId ? this.savedConnectionsAll().filter((saved) => saved.engine === engineId) : [];
});
applySaved(saved: SavedSqlConnection): void {
this.serverForm.patchValue({ host: saved.host, port: saved.port, database: saved.database, user: saved.user });
this.testResult.set(null);
}
forgetSaved(saved: SavedSqlConnection, event: Event): void {
event.stopPropagation();
removeSqlConnection(saved.id);
this.savedConnectionsAll.set(listSavedSqlConnections());
}
pick(entry: GalleryEntry): void {
if (!entry.available) return;
this.entry.set(entry);
this.testResult.set(null);
this.remember.set(false);
this.view.set(entry.engine ? 'database' : 'files');
}
@@ -145,6 +166,10 @@ export class ConnectorGalleryDialog {
connectDatabase(): void {
const ref = this.connectionRef();
if (!ref) return;
if (this.remember() && 'server' in ref) {
const { password: _password, ...shape } = ref.server;
saveSqlConnection({ label: this.connectionLabel(), ...shape });
}
this.dialogRef.close([new SqlConnection(ref, this.connectionLabel(), this.serverEngine()?.default_schema ?? undefined)]);
}
@@ -33,6 +33,15 @@
/>
<mat-hint>Expresión regular; ayuda a encontrar el expediente sin etiqueta.</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Solo documentos que digan</mat-label>
<input matInput [ngModel]="settings().include_pattern ?? ''" (ngModelChange)="updateSettings({ include_pattern: $event })" />
<mat-hint>Expresión regular; sin distinguir mayúsculas ni acentos.</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Omitir documentos que digan</mat-label>
<input matInput [ngModel]="settings().exclude_pattern ?? ''" (ngModelChange)="updateSettings({ exclude_pattern: $event })" />
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>OCR</mat-label>
<mat-select [value]="settings().ocr_mode" (valueChange)="updateSettings({ ocr_mode: $event })">
@@ -89,6 +98,12 @@
Confianza mínima {{ record.confidence | percent }}
</span>
</header>
@if (record.on_topic === false) {
<p class="record__off-topic" role="status">
<mat-icon aria-hidden="true">report</mat-icon>
Sus páginas mencionan otro tipo de estudio y no el de este destino; sus valores quedan vacíos para que los revise.
</p>
}
<table class="fields" aria-label="Campos extraídos">
<thead>
@@ -115,6 +130,21 @@
(change)="setValue(record, field.name, $any($event.target).value)"
[attr.aria-label]="'Valor de ' + field.name"
/>
@if (alternatives(record, field.name).length && !isOverridden(record, field.name)) {
<span class="fields__alternatives">
También:
@for (alternative of alternatives(record, field.name); track $index) {
<button
type="button"
class="fields__alternative"
(click)="pick(record, field.name, alternative)"
[matTooltip]="(methodLabels[alternative.method] ?? alternative.method) + ' · ' + (alternative.confidence | percent) + (alternative.line ? ' · “' + alternative.line + '”' : '')"
>
{{ alternative.value }}
</button>
}
</span>
}
@if (conflict) {
<span class="fields__conflict" [matTooltip]="'Otro documento dice: ' + conflict.discarded.value + ' (' + conflict.discarded.document + ' p. ' + conflict.discarded.page_number + ')'">
<mat-icon aria-hidden="true">compare_arrows</mat-icon>difiere
@@ -132,6 +162,9 @@
[attr.aria-label]="'Confianza ' + (found.confidence | percent)"
></mat-progress-bar>
<span class="method">{{ methodLabels[found.method] ?? found.method }} · {{ found.confidence | percent }}</span>
@if (found.assertion && assertionLabels[found.assertion]) {
<span class="method method--assertion">{{ assertionLabels[found.assertion] }}</span>
}
}
</td>
<td class="fields__evidence">
@@ -133,6 +133,47 @@
background: color-mix(in srgb, var(--mat-sys-primary) 8%, transparent);
}
.fields__alternatives {
align-items: center;
color: var(--mat-sys-on-surface-variant);
display: flex;
flex-wrap: wrap;
font: var(--mat-sys-label-small);
gap: 4px;
margin-top: 2px;
}
.fields__alternative {
background: var(--mat-sys-surface-container-high);
border: 0;
border-radius: 999px;
color: var(--mat-sys-on-surface);
cursor: pointer;
font: var(--mat-sys-label-small);
padding: 1px 8px;
&:hover,
&:focus-visible {
background: var(--mat-sys-secondary-container);
}
}
.method--assertion {
color: var(--mat-sys-tertiary);
display: block;
}
.record__off-topic {
align-items: center;
background: var(--mat-sys-error-container);
color: var(--mat-sys-on-error-container);
display: flex;
font: var(--mat-sys-body-small);
gap: var(--space-2);
margin: 0 0 var(--space-2);
padding: var(--space-2) var(--space-3);
}
.fields__conflict {
align-items: center;
color: var(--mat-sys-error);
@@ -0,0 +1,67 @@
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { SourceGateway } from '../../api/source-gateway';
import { DocumentExtraction, ExtractedRecord } from '../../api/api.types';
import { DocumentReviewDialog } from './document-review-dialog';
/**
* The review of extracted documents: the other readings the extractors proposed can be picked as a correction, a
* record whose pages name another kind of study asks for review, and a qualified mention shows how it was qualified.
* The table is a stub holding one extraction already made, so no request is sent; the gateway is never called.
*/
describe('DocumentReviewDialog', () => {
const record: ExtractedRecord = {
index: 0,
key: 'K-1',
confidence: 0.9,
fields: { bx_cin_grado: { value: 'LIEAG', confidence: 0.9, method: 'texto_libre', assertion: 'presuntivo' } },
missing: [],
conflicts: [],
sources: [{ document: 'a.pdf', page_numbers: [1] }],
images: [],
on_topic: true,
alternatives: { bx_cin_grado: [{ value: 'LIEBG', confidence: 0.7, method: 'etiqueta', line: 'Diagnóstico: NIC I' }] },
};
function open(records: ExtractedRecord[]) {
const extraction = { key_field: 'pac_id_hospital', fields: [{ name: 'bx_cin_grado', kind: 'choice', required: false, labels: [] }], records } as unknown as DocumentExtraction;
const table = {
settings: () => ({}),
overrides: () => ({}),
extractions: signal({ biopsia: extraction }),
configure: vi.fn(),
};
TestBed.configureTestingModule({
imports: [DocumentReviewDialog],
providers: [
{ provide: MAT_DIALOG_DATA, useValue: { table, target: { key: 'biopsia', domain: 'cacu', table: 'biopsia_cervical' }, segmentations: [] } },
{ provide: MatDialogRef, useValue: { close: vi.fn() } },
{ provide: SourceGateway, useValue: {} },
],
});
const fixture = TestBed.createComponent(DocumentReviewDialog);
fixture.detectChanges();
return fixture;
}
it('picks another reading as the correction', () => {
// Fails if the alternatives stop being offered or picking one stops recording it as an override.
const fixture = open([record]);
const dialog = fixture.componentInstance;
const [alternative] = dialog.alternatives(record, 'bx_cin_grado');
dialog.pick(record, 'bx_cin_grado', alternative);
expect(dialog.value(record, 'bx_cin_grado')).toBe('LIEBG');
expect(dialog.isOverridden(record, 'bx_cin_grado')).toBe(true);
});
it('shows how a mention was qualified and asks to review off-topic records', () => {
// Fails if the assertion label or the off-topic warning disappear from the page.
const fixture = open([record, { ...record, index: 1, on_topic: false }]);
expect(fixture.nativeElement.textContent).toContain('Presuntivo');
expect(fixture.componentInstance.needsReview()).toBe(1);
fixture.componentInstance.select(1);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('otro tipo de estudio');
});
});
@@ -33,9 +33,19 @@ const METHOD_LABELS: Record<string, string> = {
etiqueta: 'Etiqueta',
patron: 'Patrón',
texto_libre: 'Texto libre',
medicion: 'Medición',
columna_fuente: 'Columna',
manual: 'Manual',
};
/** How a value's mention is qualified, for the ones a reviewer should notice. */
const ASSERTION_LABELS: Record<string, string> = {
incierto: 'Incierto',
hipotetico: 'Hipotético',
historico: 'Antecedente',
presuntivo: 'Presuntivo',
};
const REVIEW_BELOW = 0.8;
/**
@@ -73,6 +83,7 @@ export class DocumentReviewDialog {
readonly target = this.data.target;
readonly segmentations = this.data.segmentations;
readonly methodLabels = METHOD_LABELS;
readonly assertionLabels = ASSERTION_LABELS;
readonly reviewBelow = REVIEW_BELOW;
readonly settings = signal<DocumentSettings>({ ...this.table.settings() });
@@ -101,8 +112,6 @@ export class DocumentReviewDialog {
});
}
// -- settings ------------------------------------------------------------
updateSettings(patch: Partial<DocumentSettings>): void {
this.settings.update((settings) => ({ ...settings, ...patch }));
}
@@ -128,8 +137,6 @@ export class DocumentReviewDialog {
});
}
// -- records and values ------------------------------------------------------
select(index: number): void {
this.selectedIndex.set(index);
this.page.set(null);
@@ -137,7 +144,18 @@ export class DocumentReviewDialog {
}
recordNeedsReview(record: ExtractedRecord): boolean {
return record.missing.length > 0 || record.conflicts.length > 0 || record.confidence < REVIEW_BELOW;
return (
record.missing.length > 0 || record.conflicts.length > 0 || record.confidence < REVIEW_BELOW || record.on_topic === false
);
}
alternatives(record: ExtractedRecord, field: string): ExtractedField[] {
return record.alternatives?.[field] ?? [];
}
/** Takes another reading the extractors proposed; the correction teaches the ranker once imported. */
pick(record: ExtractedRecord, field: string, alternative: ExtractedField): void {
this.setValue(record, field, alternative.value === null || alternative.value === undefined ? '' : String(alternative.value));
}
extracted(record: ExtractedRecord, field: string): ExtractedField | null {
@@ -171,8 +189,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 +215,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 {
@@ -55,6 +55,15 @@
</ng-template>
<div class="editor__panel"><app-column-mapper [flow]="f"></app-column-mapper></div>
</mat-tab>
<mat-tab>
<ng-template mat-tab-label>
<mat-icon aria-hidden="true">functions</mat-icon>Reglas
@if (f.documents() || (f.derived() | keyvalue).length) {
<span class="tab-count">{{ (f.derived() | keyvalue).length + (f.documents() ? 1 : 0) }}</span>
}
</ng-template>
<div class="editor__panel"><app-mapping-rules [flow]="f"></app-mapping-rules></div>
</mat-tab>
<mat-tab>
<ng-template mat-tab-label><mat-icon aria-hidden="true">table_view</mat-icon>Datos</ng-template>
<div class="editor__panel"><app-data-grid [flow]="f"></app-data-grid></div>
@@ -1,4 +1,4 @@
import { DecimalPipe } from '@angular/common';
import { DecimalPipe, KeyValuePipe } from '@angular/common';
import { Component, computed, inject, input, signal } from '@angular/core';
import { MatBadgeModule } from '@angular/material/badge';
import { MatButtonModule } from '@angular/material/button';
@@ -13,12 +13,13 @@ import { ConnectWorkspaceStore } from '../../state/connect-workspace.store';
import { ColumnMapper } from '../column-mapper/column-mapper';
import { DataGrid } from '../data-grid/data-grid';
import { DocumentReviewData, DocumentReviewDialog } from '../document-review-dialog/document-review-dialog';
import { MappingRules } from '../mapping-rules/mapping-rules';
import { FlowStatusChip } from '../shared/flow-status';
import { ValidationReport } from '../validation-report/validation-report';
const VALIDATION_TAB = 2;
const VALIDATION_TAB = 3;
/** Everything about the selected flow: its mapping, its data, its validation. */
/** Everything about the selected flow: its mapping, its rules, its data, its validation. */
@Component({
selector: 'app-flow-editor',
imports: [
@@ -26,6 +27,8 @@ const VALIDATION_TAB = 2;
DataGrid,
DecimalPipe,
FlowStatusChip,
KeyValuePipe,
MappingRules,
MatBadgeModule,
MatButtonModule,
MatIconModule,
@@ -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();
}
}
@@ -0,0 +1,238 @@
@let f = flow();
@let docs = documentForm();
<div class="rules">
<section class="rules__section" aria-labelledby="documents-title">
<header class="rules__header">
<h3 id="documents-title"><mat-icon aria-hidden="true">document_scanner</mat-icon>Documentos dentro de columnas</h3>
@if (f.documents()) {
<span class="rules__badge">Leyendo {{ f.documents()!.columns.length }} columna(s)</span>
}
</header>
<p class="rules__hint">
Si alguna columna guarda archivos (PDF o imágenes, como binario, hexadecimal o base64), se leen y todo lo que
imprimen (campos conocidos y cualquier otra etiqueta) aparece como columnas nuevas que puede asignar o usar en reglas.
Los valores que vienen de columnas de la fuente se respetan por encima de lo que diga el documento.
@if (f.documentColumns().length) {
Columnas con archivos detectadas: <strong>{{ f.documentColumns().join(', ') }}</strong>.
}
</p>
<div class="rules__grid">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Columnas con documentos</mat-label>
<mat-select multiple [ngModel]="docs.columns" (ngModelChange)="patchDocuments({ columns: $event })">
@for (name of columnNames(); track name) {
<mat-option [value]="name">{{ name }}@if (f.documentColumns().includes(name)) { (archivo) }</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Agrupar registros por</mat-label>
<mat-select [ngModel]="docs.group_by" (ngModelChange)="patchDocuments({ group_by: $event })">
<mat-option value="">Por el identificador del paciente</mat-option>
@for (name of columnNames(); track name) {
<mat-option [value]="name">{{ name }}</mat-option>
}
</mat-select>
<mat-hint>Las filas con el mismo valor forman un solo registro (p. ej. un número de estudio).</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Guardar el documento en</mat-label>
<mat-select [ngModel]="docs.file_field" (ngModelChange)="patchDocuments({ file_field: $event })">
<mat-option value="">No guardar</mat-option>
@for (field of fileFields(); track field.name) {
<mat-option [value]="field.name">{{ field.name }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>OCR</mat-label>
<mat-select [ngModel]="docs.ocr_mode" (ngModelChange)="patchDocuments({ ocr_mode: $event })">
<mat-option value="auto">Solo páginas escaneadas</mat-option>
<mat-option value="always">Todas las páginas</mat-option>
<mat-option value="never">Nunca (solo texto del PDF)</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Solo documentos que digan</mat-label>
<input matInput [ngModel]="docs.include_pattern" (ngModelChange)="patchDocuments({ include_pattern: $event })" />
<mat-hint>Expresión regular; sin distinguir mayúsculas ni acentos.</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Omitir documentos que digan</mat-label>
<input matInput [ngModel]="docs.exclude_pattern" (ngModelChange)="patchDocuments({ exclude_pattern: $event })" />
</mat-form-field>
</div>
<mat-checkbox [checked]="f.catalogFallback()" (change)="f.setCatalogFallback($event.checked)">
Guardar también, en el expediente de cada paciente, las etiquetas de los documentos que el catálogo del proyecto ya
conoce
</mat-checkbox>
<p class="rules__hint">
Las etiquetas que nadie usa no se guardan: aparecen, solo con su nombre y cuántos registros las traen, en la
Bitácora de cargas.
</p>
<div class="rules__actions">
<button mat-flat-button type="button" [disabled]="documentsBusy()" (click)="applyDocuments()">
<mat-icon aria-hidden="true">play_arrow</mat-icon>Leer documentos
</button>
@if (f.documents()) {
<button mat-button type="button" (click)="clearDocuments()">Dejar de leerlos</button>
}
</div>
@if (documentsBusy()) {
<mat-progress-bar mode="indeterminate" />
}
@if (documentsError(); as error) {
<p class="rules__error" role="alert">{{ error }}</p>
}
</section>
<section class="rules__section" aria-labelledby="derived-title">
<header class="rules__header">
<h3 id="derived-title"><mat-icon aria-hidden="true">functions</mat-icon>Campos calculados</h3>
</header>
<p class="rules__hint">
Para cuando las columnas no coinciden una a una con los campos: unir nombre y apellidos, separar un nombre completo,
tomar la primera columna con valor, extraer un dato de un texto o traducir códigos. Funciona igual con columnas de la
fuente y con lo leído de los documentos.
</p>
@for (item of rules(); track item.field) {
<div class="rule">
<mat-icon aria-hidden="true">arrow_forward</mat-icon>
<strong>{{ item.field }}</strong>
<span class="rule__summary">{{ item.summary }}</span>
<button mat-icon-button type="button" [attr.aria-label]="'Quitar regla de ' + item.field" (click)="removeRule(item.field)">
<mat-icon>delete</mat-icon>
</button>
</div>
}
<div class="rules__grid">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Campo</mat-label>
<mat-select [ngModel]="ruleField()" (ngModelChange)="ruleField.set($event)">
@for (field of f.target.fields; track field.name) {
<mat-option [value]="field.name">{{ field.name }}@if (field.required) { * }</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Cómo calcularlo</mat-label>
<mat-select [ngModel]="ruleOp()" (ngModelChange)="chooseOp($event)">
@for (spec of catalog()?.derivations ?? []; track spec.op) {
<mat-option [value]="spec.op" [matTooltip]="spec.description">{{ spec.label }}</mat-option>
}
</mat-select>
@if (selectedSpec(); as spec) {
<mat-hint>{{ spec.description }}</mat-hint>
}
</mat-form-field>
@for (param of selectedSpec()?.params ?? []; track param.name) {
@switch (param.kind) {
@case ('column') {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>{{ param.label }}</mat-label>
<mat-select [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)">
@for (name of columnNames(); track name) {
<mat-option [value]="name">{{ name }}</mat-option>
}
</mat-select>
</mat-form-field>
}
@case ('columns') {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>{{ param.label }} (en orden)</mat-label>
<mat-select multiple [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)">
@for (name of columnNames(); track name) {
<mat-option [value]="name">{{ name }}</mat-option>
}
</mat-select>
</mat-form-field>
}
@case ('integer') {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>{{ param.label }}</mat-label>
<input matInput type="number" [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)" />
</mat-form-field>
}
@case ('boolean') {
<mat-checkbox [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)">{{ param.label }}</mat-checkbox>
}
@case ('mapping') {
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="rules__wide">
<mat-label>{{ param.label }}</mat-label>
<textarea matInput rows="3" placeholder="M = Masculino" [ngModel]="mappingText(param.name)" (ngModelChange)="setMappingText(param.name, $event)"></textarea>
<mat-hint>Una equivalencia por línea: valor = nuevo valor.</mat-hint>
</mat-form-field>
}
@default {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>{{ param.label }}</mat-label>
<input matInput [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)" />
</mat-form-field>
}
}
}
@if (selectedSpec()) {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Mayúsculas</mat-label>
<mat-select [ngModel]="ruleCase()" (ngModelChange)="ruleCase.set($event)">
<mat-option value="">Sin cambio</mat-option>
<mat-option value="upper">MAYÚSCULAS</mat-option>
<mat-option value="lower">minúsculas</mat-option>
<mat-option value="title">Tipo Título</mat-option>
</mat-select>
</mat-form-field>
}
</div>
<div class="rules__actions">
<button mat-stroked-button type="button" [disabled]="!ruleField() || !selectedSpec()" (click)="addRule()">
<mat-icon aria-hidden="true">add</mat-icon>Agregar regla
</button>
</div>
@if (ruleError(); as error) {
<p class="rules__error" role="alert">{{ error }}</p>
}
</section>
<section class="rules__section" aria-labelledby="result-title">
<header class="rules__header">
<h3 id="result-title"><mat-icon aria-hidden="true">preview</mat-icon>Resultado</h3>
<button mat-stroked-button type="button" [disabled]="previewBusy()" (click)="preview()">
<mat-icon aria-hidden="true">visibility</mat-icon>Ver cómo quedarían las filas
</button>
</header>
@if (previewBusy()) {
<mat-progress-bar mode="indeterminate" />
}
@if (previewError(); as error) {
<p class="rules__error" role="alert">{{ error }}</p>
}
@if (previewRows(); as rows) {
<div class="rules__table-wrap">
<table class="rules__table">
<thead>
<tr>
@for (column of previewColumns(); track column) {
<th scope="col">{{ column }}</th>
}
</tr>
</thead>
<tbody>
@for (row of rows; track $index) {
<tr>
@for (column of previewColumns(); track column) {
<td>{{ cell(row[column]) }}</td>
}
</tr>
} @empty {
<tr><td>La fuente no dio filas.</td></tr>
}
</tbody>
</table>
</div>
}
</section>
</div>
@@ -0,0 +1,113 @@
:host {
display: block;
}
.rules {
display: flex;
flex-direction: column;
gap: 24px;
padding: 16px;
}
.rules__section {
display: flex;
flex-direction: column;
gap: 12px;
}
.rules__header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
h3 {
display: flex;
align-items: center;
gap: 8px;
margin: 0;
font: var(--mat-sys-title-medium);
}
}
.rules__badge {
font: var(--mat-sys-label-medium);
color: var(--mat-sys-primary);
}
.rules__hint {
margin: 0;
font: var(--mat-sys-body-small);
color: var(--mat-sys-on-surface-variant);
}
.rules__grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
gap: 12px 16px;
align-items: start;
}
.rules__wide {
grid-column: 1 / -1;
}
.rules__actions {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.rules__error {
margin: 0;
color: var(--mat-sys-error);
font: var(--mat-sys-body-medium);
}
.rule {
display: flex;
align-items: center;
gap: 8px;
padding: 4px 8px;
border-radius: 8px;
background: var(--mat-sys-surface-container);
}
.rule__summary {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--mat-sys-on-surface-variant);
}
.rules__table-wrap {
overflow-x: auto;
max-height: 360px;
border: 1px solid var(--mat-sys-outline-variant);
border-radius: 8px;
}
.rules__table {
border-collapse: collapse;
font: var(--mat-sys-body-small);
th,
td {
padding: 4px 8px;
border-bottom: 1px solid var(--mat-sys-outline-variant);
text-align: left;
white-space: nowrap;
max-width: 240px;
overflow: hidden;
text-overflow: ellipsis;
}
th {
position: sticky;
top: 0;
background: var(--mat-sys-surface-container-high);
}
}
@@ -0,0 +1,255 @@
import { Component, computed, effect, inject, input, signal } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSelectModule } from '@angular/material/select';
import { MatTooltipModule } from '@angular/material/tooltip';
import { firstValueFrom } from 'rxjs';
import {
DerivationParam,
DerivationRule,
DerivationSpec,
DocumentColumnsConfig,
OcrMode,
Row,
apiErrorMessage,
} from '../../api/api.types';
import { ImportsApi } from '../../api/imports.api';
import { ImportFlow } from '../../domain/import-flow';
interface DocumentForm {
columns: string[];
group_by: string;
file_field: string;
ocr_mode: OcrMode;
include_pattern: string;
exclude_pattern: string;
}
/**
* What a plain column-to-field mapping can't express, for any kind of
* source: columns whose cells hold documents (read for every field and
* caption they print, which then become columns of their own), target
* fields computed from several columns, and a look at the rows as they
* would be written.
*
* The operations and their parameters come from the server
* (`/imports/derivations`), so a new operation needs no change here.
*/
@Component({
selector: 'app-mapping-rules',
imports: [
FormsModule,
MatButtonModule,
MatCheckboxModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatProgressBarModule,
MatSelectModule,
MatTooltipModule,
],
templateUrl: './mapping-rules.html',
styleUrl: './mapping-rules.scss',
})
export class MappingRules {
readonly flow = input.required<ImportFlow>();
private readonly api = inject(ImportsApi);
readonly catalog = toSignal(this.api.derivations());
readonly columnNames = computed(() => this.flow().sourceColumns().map((column) => column.name));
readonly fileFields = computed(() => this.flow().target.fields.filter((field) => field.type === 'binary' || field.name.endsWith('_blob')));
readonly documentForm = signal<DocumentForm>(this.emptyDocumentForm());
readonly documentsBusy = signal(false);
readonly documentsError = signal<string | null>(null);
readonly ruleField = signal<string>('');
readonly ruleOp = signal<string>('');
readonly ruleParams = signal<Record<string, unknown>>({});
readonly ruleCase = signal<string>('');
readonly ruleError = signal<string | null>(null);
readonly previewRows = signal<Row[] | null>(null);
readonly previewBusy = signal(false);
readonly previewError = signal<string | null>(null);
readonly selectedSpec = computed<DerivationSpec | undefined>(() =>
this.catalog()?.derivations.find((spec) => spec.op === this.ruleOp()),
);
readonly rules = computed(() =>
Object.entries(this.flow().derived()).map(([field, rule]) => ({ field, rule, summary: this.describe(rule) })),
);
readonly previewColumns = computed(() => {
const rows = this.previewRows() ?? [];
return [...new Set(rows.flatMap((row) => Object.keys(row)))];
});
constructor() {
// The form follows the flow: what it has configured, or the columns the server flagged.
effect(() => {
const flow = this.flow();
const current = flow.documents();
this.documentForm.set(current ? this.formFrom(current) : { ...this.emptyDocumentForm(), columns: flow.documentColumns() });
});
}
// -- documents -----------------------------------------------------------
patchDocuments(patch: Partial<DocumentForm>): void {
this.documentForm.update((form) => ({ ...form, ...patch }));
}
async applyDocuments(): Promise<void> {
const form = this.documentForm();
const flow = this.flow();
if (!form.columns.length) {
this.clearDocuments();
return;
}
flow.setDocuments({
columns: form.columns,
group_by: form.group_by || undefined,
file_field: form.file_field || undefined,
ocr_mode: form.ocr_mode,
include_pattern: form.include_pattern.trim() || undefined,
exclude_pattern: form.exclude_pattern.trim() || undefined,
});
this.documentsBusy.set(true);
this.documentsError.set(null);
try {
flow.useDocumentPreview(await firstValueFrom(this.api.documentColumns(await flow.toPayload())));
} catch (error) {
this.documentsError.set(apiErrorMessage(error, 'No se pudieron leer los documentos.'));
} finally {
this.documentsBusy.set(false);
}
}
clearDocuments(): void {
this.flow().setDocuments(null);
this.documentsError.set(null);
}
// -- derived fields ------------------------------------------------------
chooseOp(op: string): void {
this.ruleOp.set(op);
const spec = this.catalog()?.derivations.find((candidate) => candidate.op === op);
this.ruleParams.set(Object.fromEntries((spec?.params ?? []).map((param) => [param.name, this.initial(param)])));
this.ruleError.set(null);
}
setParam(name: string, value: unknown): void {
this.ruleParams.update((params) => ({ ...params, [name]: value }));
}
/** `clave = valor` lines, the text form of a `mapping` parameter. */
mappingText(name: string): string {
const value = this.ruleParams()[name];
return value && typeof value === 'object' ? Object.entries(value).map(([k, v]) => `${k} = ${v}`).join('\n') : '';
}
setMappingText(name: string, text: string): void {
const entries = text
.split('\n')
.map((line) => line.split('='))
.filter((parts) => parts.length >= 2 && parts[0].trim())
.map(([key, ...rest]) => [key.trim(), rest.join('=').trim()]);
this.setParam(name, Object.fromEntries(entries));
}
addRule(): void {
const spec = this.selectedSpec();
const field = this.ruleField();
if (!spec || !field) return;
const params = this.ruleParams();
const missing = spec.params.filter((param) => param.required && this.blank(params[param.name]));
if (missing.length) {
this.ruleError.set(`Falta: ${missing.map((param) => param.label).join(', ')}`);
return;
}
const rule: DerivationRule = { op: spec.op };
for (const param of spec.params) {
const value = params[param.name];
if (!this.blank(value)) rule[param.name] = param.kind === 'integer' ? Number(value) : value;
}
if (this.ruleCase()) rule.case = this.ruleCase();
this.flow().setDerived(field, rule);
this.ruleField.set('');
this.ruleOp.set('');
this.ruleParams.set({});
this.ruleCase.set('');
this.ruleError.set(null);
}
removeRule(field: string): void {
this.flow().setDerived(field, null);
}
// -- preview ---------------------------------------------------------------
async preview(): Promise<void> {
this.previewBusy.set(true);
this.previewError.set(null);
try {
const { rows } = await firstValueFrom(this.api.mappedPreview(await this.flow().toPayload(), 10));
this.previewRows.set(rows);
} catch (error) {
this.previewError.set(apiErrorMessage(error, 'No se pudo armar la vista previa.'));
} finally {
this.previewBusy.set(false);
}
}
cell(value: unknown): string {
if (value === null || value === undefined) return '';
return typeof value === 'object' ? JSON.stringify(value) : String(value);
}
private describe(rule: DerivationRule): string {
const spec = this.catalog()?.derivations.find((candidate) => candidate.op === rule.op);
const parts = (spec?.params ?? [])
.filter((param) => !this.blank(rule[param.name]))
.map((param) => `${param.label}: ${this.cell(rule[param.name])}`);
return [spec?.label ?? rule.op, ...parts, ...(rule.case ? [`(${rule.case})`] : [])].join(' · ');
}
private initial(param: DerivationParam): unknown {
if (param.kind === 'columns') return [];
if (param.kind === 'mapping') return {};
return param.default ?? (param.kind === 'boolean' ? false : '');
}
private blank(value: unknown): boolean {
return (
value === null ||
value === undefined ||
(typeof value === 'string' && !value.trim()) ||
(Array.isArray(value) && !value.length) ||
(typeof value === 'object' && !Array.isArray(value) && !Object.keys(value as object).length)
);
}
private emptyDocumentForm(): DocumentForm {
return { columns: [], group_by: '', file_field: '', ocr_mode: 'auto', include_pattern: '', exclude_pattern: '' };
}
private formFrom(config: DocumentColumnsConfig): DocumentForm {
return {
columns: config.columns,
group_by: typeof config.group_by === 'string' ? config.group_by : '',
file_field: config.file_field ?? '',
ocr_mode: config.ocr_mode ?? 'auto',
include_pattern: config.include_pattern ?? '',
exclude_pattern: config.exclude_pattern ?? '',
};
}
}
@@ -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) : [];
@@ -92,4 +92,40 @@ describe('ImportFlow', () => {
expect(flow.autoMap()).toBe(1);
expect(flow.mapping.toRecord()).toEqual({ Sexo: 'pac_sexo', Clave: 'pac_id_hospital' });
});
it('counts a derived field as covered, and mapping a column onto it drops the rule', async () => {
// Fails if `missingRequired` ignores `derived`, or a field could be fed by a column and a rule at once.
const flow = loadedFlow();
flow.setDerived('pac_id_hospital', { op: 'concat', columns: ['Clave', 'Sexo'], separator: '-' });
expect(flow.missingRequired()).toEqual([]);
expect((await flow.toPayload()).derived).toEqual({ pac_id_hospital: { op: 'concat', columns: ['Clave', 'Sexo'], separator: '-' } });
flow.map('Clave', 'pac_id_hospital');
expect(flow.derived()).toEqual({});
expect((await flow.toPayload()).derived).toBeUndefined();
});
it('sends document columns without blank settings and swaps in their columns until they are dropped', async () => {
// Fails if blank document settings reach the payload, or the source's own columns are lost when documents are dropped.
const flow = loadedFlow();
const own = flow.sourceColumns();
flow.setDocuments({ columns: ['Clave'], group_by: '', include_pattern: undefined, ocr_mode: 'auto' });
expect((await flow.toPayload()).documents).toEqual({ columns: ['Clave'], ocr_mode: 'auto' });
expect(flow.missingRequired()).toEqual([]);
flow.useDocumentPreview(preview({ columns: [...own, { name: 'Tipo de persona', inferred_type: 'string' }] }));
expect(flow.sourceColumns().map((c) => c.name)).toContain('Tipo de persona');
flow.setDocuments(null);
expect(flow.sourceColumns()).toEqual(own);
expect((await flow.toPayload()).documents).toBeUndefined();
});
it('asks for the catalog fallback only when chosen', async () => {
// Fails if `catalog_fallback` is sent without the user switching it on, or not sent once they do.
const flow = loadedFlow();
expect((await flow.toPayload()).catalog_fallback).toBeUndefined();
flow.setCatalogFallback(true);
expect((await flow.toPayload()).catalog_fallback).toBe(true);
});
});
+84 -12
View File
@@ -2,6 +2,8 @@ import { Signal, computed, signal } from '@angular/core';
import { Observable, catchError, finalize, map, of, tap } from 'rxjs';
import {
CommitSourceResult,
DerivationRule,
DocumentColumnsConfig,
ImportSourcePayload,
PreviewResponse,
RowError,
@@ -47,9 +49,14 @@ export class ImportFlow {
readonly mapping = new MappingSet();
private readonly _preview = signal<PreviewResponse | null>(null);
/** The source's own preview, kept while document columns replace it. */
private _sourcePreview: PreviewResponse | null = null;
private readonly _loading = signal(false);
private readonly _error = signal<string | null>(null);
private readonly _defaults = signal<Record<string, string>>({});
private readonly _derived = signal<Record<string, DerivationRule>>({});
private readonly _documents = signal<DocumentColumnsConfig | null>(null);
private readonly _catalogFallback = signal(false);
private readonly _validation = signal<ValidationResult | null>(null);
private readonly _validating = signal(false);
private readonly _result = signal<CommitSourceResult | null>(null);
@@ -58,6 +65,12 @@ export class ImportFlow {
readonly loading: Signal<boolean> = this._loading.asReadonly();
readonly error: Signal<string | null> = this._error.asReadonly();
readonly defaults: Signal<Record<string, string>> = this._defaults.asReadonly();
/** Target fields computed from source columns (`derived`), by field. */
readonly derived: Signal<Record<string, DerivationRule>> = this._derived.asReadonly();
/** Source columns read as documents, or `null` when none are. */
readonly documents: Signal<DocumentColumnsConfig | null> = this._documents.asReadonly();
/** Whether captions the catalog knows are stored too (`catalog_fallback`); off unless chosen. */
readonly catalogFallback: Signal<boolean> = this._catalogFallback.asReadonly();
readonly validation: Signal<ValidationResult | null> = this._validation.asReadonly();
readonly validating: Signal<boolean> = this._validating.asReadonly();
readonly result: Signal<CommitSourceResult | null> = this._result.asReadonly();
@@ -65,18 +78,28 @@ export class ImportFlow {
readonly sourceColumns = computed<SourceColumn[]>(() => this._preview()?.columns ?? []);
readonly totalRows = computed(() => this._preview()?.total_rows ?? null);
/** A field is covered when a column feeds it or it has a default value. */
/**
* A field is covered when a column feeds it, a rule computes it or it has
* a default value. With document columns, extraction may fill any field,
* so nothing is reported missing before validation says so.
*/
readonly missingRequired = computed<TargetField[]>(() => {
if (this._documents()) return [];
const mapped = this.mapping.byField();
const defaults = this._defaults();
return this.target.fields.filter((f) => f.required && !mapped.has(f.name) && !defaults[f.name]?.trim());
const derived = this._derived();
return this.target.fields.filter((f) => f.required && !mapped.has(f.name) && !derived[f.name] && !defaults[f.name]?.trim());
});
/** Columns no mapping, rule or document setting reads. */
readonly unmappedColumns = computed(() => {
const used = this.mapping.bySource();
const used = new Set([...this.mapping.bySource().keys(), ...this._documents()?.columns ?? []]);
return this.sourceColumns().filter((column) => !used.has(column.name));
});
/** Columns whose sampled cells hold documents. */
readonly documentColumns = computed<string[]>(() => this._preview()?.document_columns ?? []);
readonly pendingSuggestions = computed(() => this.mapping.items().filter((m) => m.confidence !== undefined).length);
readonly status = computed<FlowStatus>(() => {
@@ -84,7 +107,8 @@ export class ImportFlow {
if (this._error() || !this._preview()) return 'error';
if (this._result()) return 'loaded';
if (this._validating()) return 'validating';
if (this.missingRequired().length > 0 || this.mapping.size() + Object.keys(this.activeDefaults()).length === 0) {
const assigned = this.mapping.size() + Object.keys(this.activeDefaults()).length + Object.keys(this._derived()).length;
if (this.missingRequired().length > 0 || (assigned === 0 && !this._documents())) {
return 'incomplete';
}
const validation = this._validation();
@@ -134,12 +158,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,10 +181,13 @@ 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);
if (this._derived()[field]) {
this._derived.update(({ [field]: _, ...rest }) => rest);
}
this.touch();
}
@@ -193,9 +215,51 @@ export class ImportFlow {
clearMapping(): void {
this.mapping.clear();
this._defaults.set({});
this._derived.set({});
this._documents.set(null);
this.touch();
}
/** Computes `field` with `rule`, replacing any column mapped to it; `null` removes the rule. */
setDerived(field: string, rule: DerivationRule | null): void {
if (rule) this.mapping.releaseField(field);
this._derived.update((derived) => {
const next = { ...derived };
if (rule) next[field] = rule;
else delete next[field];
return next;
});
this.touch();
}
setCatalogFallback(on: boolean): void {
this._catalogFallback.set(on);
this.touch();
}
/** Reads some of the source's columns as documents; `null` stops reading them. */
setDocuments(config: DocumentColumnsConfig | null): void {
this._documents.set(config && config.columns.length ? config : null);
if (!this._documents()) this.useDocumentPreview(null);
this.touch();
}
/**
* Shows, as the source's columns, its own plus every field and caption
* its documents print, so they can be mapped and used in rules; `null`
* goes back to the source's own columns.
*/
useDocumentPreview(preview: PreviewResponse | null): void {
if (preview) {
this._sourcePreview ??= this._preview();
this._preview.set({ ...preview, document_columns: this._sourcePreview?.document_columns ?? [] });
this.mapping.fillFrom(preview.suggested_mapping);
} else if (this._sourcePreview) {
this._preview.set(this._sourcePreview);
this._sourcePreview = null;
}
}
setDefault(field: string, value: string | null): void {
this._defaults.update((defaults) => {
const next = { ...defaults };
@@ -210,7 +274,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);
@@ -221,6 +284,9 @@ export class ImportFlow {
label: this.label,
column_mapping: this.mapping.toRecord(),
...(Object.keys(defaults).length ? { defaults } : {}),
...(Object.keys(this._derived()).length ? { derived: this._derived() } : {}),
...(this._documents() ? { documents: withoutBlanks(this._documents()!) } : {}),
...(this._catalogFallback() ? { catalog_fallback: true } : {}),
};
}
@@ -262,3 +328,9 @@ export class ImportFlow {
this._result.set(null);
}
}
function withoutBlanks(config: DocumentColumnsConfig): DocumentColumnsConfig {
return Object.fromEntries(
Object.entries(config).filter(([, value]) => value !== undefined && value !== null && value !== ''),
) as unknown as DocumentColumnsConfig;
}
@@ -0,0 +1,47 @@
import { listSavedSqlConnections, removeSqlConnection, saveSqlConnection } from './saved-sql-connections';
describe('saved SQL connections', () => {
beforeEach(() => localStorage.clear());
it('never stores a password field', () => {
const saved = saveSqlConnection({ label: 'HIS · lector@his.local', engine: 'mssql', host: 'his.local', port: 1433, database: 'HIS', user: 'lector' });
expect(Object.keys(saved)).not.toContain('password');
expect(JSON.parse(localStorage.getItem('isssteleon.connect.savedSqlConnections')!)[0]).not.toHaveProperty('password');
});
it('upserts by connection shape instead of growing duplicates', () => {
const entry = { label: 'HIS', engine: 'mssql', host: 'his.local', port: 1433, database: 'HIS', user: 'lector' };
saveSqlConnection(entry);
saveSqlConnection({ ...entry, label: 'HIS (renamed)' });
const all = listSavedSqlConnections();
expect(all.length).toBe(1);
expect(all[0].label).toBe('HIS (renamed)');
});
it('keeps connections to different servers separate', () => {
saveSqlConnection({ label: 'A', engine: 'mssql', host: 'a.local', port: 1433, database: 'HIS', user: 'lector' });
saveSqlConnection({ label: 'B', engine: 'mysql', host: 'b.local', port: 3306, database: 'HIS', user: 'lector' });
expect(listSavedSqlConnections().length).toBe(2);
});
it('removes a saved connection by id', () => {
const saved = saveSqlConnection({ label: 'HIS', engine: 'mssql', host: 'his.local', port: 1433, database: 'HIS', user: 'lector' });
removeSqlConnection(saved.id);
expect(listSavedSqlConnections()).toEqual([]);
});
it('caps the list so it cannot grow without bound', () => {
for (let i = 0; i < 25; i++) {
saveSqlConnection({ label: `db${i}`, engine: 'mssql', host: `host${i}`, port: 1433, database: 'HIS', user: 'lector' });
}
expect(listSavedSqlConnections().length).toBeLessThanOrEqual(20);
});
it('degrades to an empty list rather than throwing when storage is unreadable', () => {
const spy = vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
throw new Error('blocked');
});
expect(listSavedSqlConnections()).toEqual([]);
spy.mockRestore();
});
});
@@ -0,0 +1,59 @@
const STORAGE_KEY = 'isssteleon.connect.savedSqlConnections';
const MAX_SAVED = 20;
/**
* A database connection's shape, remembered across visits so the form
* doesn't need retyping. Never the password: credentials travel with every
* request and are never stored (see `sql-source.ts`), so reconnecting
* through a saved entry still asks for it.
*/
export interface SavedSqlConnection {
id: string;
label: string;
engine: string;
host: string;
port: number | null;
database: string;
user: string;
}
export type SavedSqlConnectionInput = Omit<SavedSqlConnection, 'id'>;
function connectionId(entry: SavedSqlConnectionInput): string {
return [entry.engine, entry.host, entry.port ?? '', entry.database, entry.user].join('|');
}
function readAll(): SavedSqlConnection[] {
try {
const raw = localStorage.getItem(STORAGE_KEY);
const parsed = raw ? JSON.parse(raw) : [];
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
function writeAll(entries: SavedSqlConnection[]): void {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(entries));
} catch {
// Private browsing, a cleared/blocked store, or a full quota: the form
// just won't remember anything this time, nothing to surface to the user.
}
}
export function listSavedSqlConnections(): SavedSqlConnection[] {
return readAll();
}
/** Upserts by connection shape (engine/host/port/database/user), newest first. */
export function saveSqlConnection(entry: SavedSqlConnectionInput): SavedSqlConnection {
const saved: SavedSqlConnection = { ...entry, id: connectionId(entry) };
const rest = readAll().filter((existing) => existing.id !== saved.id);
writeAll([saved, ...rest].slice(0, MAX_SAVED));
return saved;
}
export function removeSqlConnection(id: string): void {
writeAll(readAll().filter((existing) => existing.id !== id));
}
-1
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;
@@ -0,0 +1,85 @@
{
"resourceType": "Bundle",
"type": "searchset",
"total": 1,
"entry": [
{
"resource": {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary",
"measure": "cacu/CACU_DIAS_TOMA_DIAGNOSTICO|0.2.3",
"date": "2026-11-08T06:47:32.900609+00:00",
"period": {
"start": "2025-07-01",
"end": "2025-12-31"
},
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
"valueInteger": 1
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-evento",
"valueDate": "2026-11-08"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
"valueDateTime": "2026-11-08T06:47:32.766239+00:00"
}
],
"group": [
{
"id": "TOTAL",
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-observation"
}
]
},
"count": 2
}
],
"measureScore": {
"value": 100.5,
"unit": "d",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/q1",
"valueDecimal": 70.25
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/q3",
"valueDecimal": 130.75
}
]
}
}
],
"improvementNotation": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": "decrease"
}
]
}
}
}
]
}
@@ -0,0 +1,127 @@
{
"resourceType": "Bundle",
"type": "searchset",
"total": 1,
"entry": [
{
"resource": {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary",
"measure": "cacu/CACU_EU13|0.3.2",
"date": "2026-11-08T00:28:51.413089+00:00",
"period": {
"start": "2025-01-01",
"end": "2025-06-30"
},
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
"valueInteger": 1
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
"valueDateTime": "2026-11-08T00:28:51.351883+00:00"
}
],
"group": [
{
"id": "principal",
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "denominator"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "numerator"
}
]
},
"count": 0
}
],
"measureScore": {
"value": 0.0
},
"stratifier": [
{
"code": [
{
"text": "grupo_edad"
}
],
"stratum": [
{
"value": {
"text": "45-54"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "denominator"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "numerator"
}
]
},
"count": 0
}
],
"measureScore": {
"value": 0.0
}
}
]
}
]
}
]
}
}
]
}
@@ -0,0 +1,295 @@
{
"resourceType": "Bundle",
"type": "searchset",
"total": 2,
"entry": [
{
"resource": {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary",
"measure": "cacu/CACU_EU7|0.3.3",
"date": "2026-11-08T00:28:56.089006+00:00",
"period": {
"start": "2025-01-01",
"end": "2025-06-30"
},
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
"valueInteger": 1
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
"valueDateTime": "2026-11-08T00:28:56.025101+00:00"
}
],
"group": [
{
"id": "TOTAL",
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-observation"
}
]
},
"count": 4
}
],
"stratifier": [
{
"code": [
{
"text": "resultado"
}
],
"stratum": [
{
"value": {
"text": "LIEBG"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 1
}
]
},
{
"value": {
"text": "NEGATIVO"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 2
}
]
},
{
"value": {
"text": "SIN_DATO"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 1
}
]
}
]
},
{
"code": [
{
"text": "grupo_edad"
}
],
"stratum": [
{
"value": {
"text": "45-54"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
}
]
}
]
}
]
}
]
}
},
{
"resource": {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary",
"measure": "cacu/CACU_EU7|0.3.3",
"date": "2026-11-08T00:28:56.099338+00:00",
"period": {
"start": "2025-07-01",
"end": "2025-12-31"
},
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
"valueInteger": 2
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
"valueDateTime": "2026-11-08T00:28:56.025101+00:00"
}
],
"group": [
{
"id": "TOTAL",
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-observation"
}
]
},
"count": 4
}
],
"stratifier": [
{
"code": [
{
"text": "resultado"
}
],
"stratum": [
{
"value": {
"text": "LIEAG"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 1
}
]
},
{
"value": {
"text": "NEGATIVO"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 1
}
]
},
{
"value": {
"text": "SIN_DATO"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 2
}
]
}
]
},
{
"code": [
{
"text": "grupo_edad"
}
],
"stratum": [
{
"value": {
"text": "45-54"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
}
]
}
]
}
]
}
]
}
}
]
}
@@ -0,0 +1,155 @@
{
"resourceType": "Bundle",
"type": "searchset",
"total": 2,
"entry": [
{
"resource": {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary",
"measure": "cacu/IND1|0.3.2",
"date": "2026-11-08T00:28:50.038223+00:00",
"period": {
"start": "2025-01-01",
"end": "2025-06-30"
},
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
"valueInteger": 1
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
"valueDateTime": "2026-11-08T00:28:49.977023+00:00"
}
],
"group": [
{
"id": "principal",
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "denominator"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "numerator"
}
]
},
"count": 1
}
],
"measureScore": {
"value": 0.25
}
}
],
"improvementNotation": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": "decrease"
}
]
}
}
},
{
"resource": {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary",
"measure": "cacu/IND1|0.3.2",
"date": "2026-11-08T00:28:50.044435+00:00",
"period": {
"start": "2025-07-01",
"end": "2025-12-31"
},
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
"valueInteger": 2
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
"valueDateTime": "2026-11-08T00:28:49.977023+00:00"
}
],
"group": [
{
"id": "principal",
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "denominator"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "numerator"
}
]
},
"count": 1
}
],
"measureScore": {
"value": 0.25
}
}
],
"improvementNotation": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": "decrease"
}
]
}
}
}
]
}
@@ -0,0 +1,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'); },
});
}
}
+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' } },
};
}
+40 -20
View File
@@ -2,9 +2,10 @@ import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import {
CohortExclusionsResponse,
CohortScenario,
CohortVersion,
CohortBuildFile,
Experiment,
ExperimentDetail,
ExperimentRequest,
ModelLineage,
ModelVersion,
PromotionCheck,
@@ -15,7 +16,7 @@ import {
OcrRunSummary,
} from './governance.types';
/** `/governance/*`: model and cohort versions, artifacts, and the OCR review queue. */
/** `/governance/*`: model versions and their files, notebooks run on a cohort build, and the OCR review queue. */
@Injectable({ providedIn: 'root' })
export class GovernanceApi {
private readonly http = inject(HttpClient);
@@ -47,29 +48,44 @@ export class GovernanceApi {
return this.http.patch<ModelVersion>(`/governance/model-versions/${domain}/${scenario}/${version}/reports`, reports);
}
/** Logs the file to the version's MLflow run. Browsing/downloading a
* logged artifact goes through the MLflow tracking server directly. */
uploadArtifact(domain: string, scenario: string, version: string, kind: string, file: File): Observable<ModelVersion> {
/** Where a file the version's run stored downloads from; a folder comes as a zip. */
artifactUrl(domain: string, scenario: string, version: string, path: string): string {
return `/governance/model-versions/${domain}/${scenario}/${version}/artifacts/${encodePath(path)}`;
}
/** The domain's cohort builds that have their file. */
cohortFiles(domain: string): Observable<{ builds: CohortBuildFile[] }> {
return this.http.get<{ builds: CohortBuildFile[] }>('/governance/cohort-files', { params: toParams({ domain }) });
}
listExperiments(filters: { domain?: string; scenario?: string } = {}): Observable<{ experiments: Experiment[] }> {
return this.http.get<{ experiments: Experiment[] }>('/governance/experiments', { params: toParams(filters) });
}
/** Starts the notebook on the build in the background; answers with the run while it is still `en_curso`. */
runExperiment(request: ExperimentRequest): Observable<ExperimentDetail> {
const form = new FormData();
form.append('file', file);
form.append('kind', kind);
return this.http.post<ModelVersion>(`/governance/model-versions/${domain}/${scenario}/${version}/artifacts`, form);
form.append('file', request.file);
form.append('domain', request.domain);
form.append('scenario', request.scenario);
form.append('url', request.build.url);
form.append('source', request.build.source);
form.append('build', String(request.build.build));
if (request.version) form.append('version', request.version);
return this.http.post<ExperimentDetail>('/governance/experiments', form);
}
listCohortScenarios(): Observable<{ scenarios: CohortScenario[] }> {
return this.http.get<{ scenarios: CohortScenario[] }>('/governance/cohort-scenarios');
getExperiment(runId: string): Observable<ExperimentDetail> {
return this.http.get<ExperimentDetail>(`/governance/experiments/${runId}`);
}
buildCohortVersion(domain: string, scenario: string, description?: string): Observable<CohortVersion> {
return this.http.post<CohortVersion>('/governance/cohort-versions', { domain, scenario, ...(description ? { description } : {}) });
/** The rendered page, served sandboxed; opened in its own tab. */
experimentPageUrl(runId: string): string {
return `/governance/experiments/${runId}/page`;
}
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`);
experimentArtifactUrl(runId: string, path: string): string {
return `/governance/experiments/${runId}/artifacts/${encodePath(path)}`;
}
listOcrJobs(): Observable<{ jobs: OcrJob[] }> {
@@ -99,6 +115,10 @@ export class GovernanceApi {
}
}
function encodePath(path: string): string {
return path.split('/').map(encodeURIComponent).join('/');
}
function toParams(filters: Record<string, string | number | boolean | undefined>): HttpParams {
let params = new HttpParams();
for (const [key, value] of Object.entries(filters)) {
+63 -44
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;
@@ -29,61 +27,82 @@ export interface PromotionCheck {
detail: string;
}
/** A logged artifact's path within the run, e.g. `ONNX_CHECKPOINT/model.onnx`
* — browsing/downloading the file itself goes through MLflow directly. */
export type ArtifactPath = string;
/** A file a run stored, by its path within the run (`rutinas/MUESTREO.json`, `model/MLmodel`). */
export interface ArtifactFile {
path: string;
size: number | null;
}
/** The routines training records as it runs (ML-01a), each under its kind. */
export type RoutineKind = 'MUESTREO' | 'DATOS_FALTANTES' | 'METODO_ANALITICO' | 'BALANCE_CLASES' | 'CONFIANZA_SALIDA';
export interface ModelLineage {
model_version: ModelVersion;
cohort_version: CohortVersion | null;
cohort_exclusions: CohortExclusionCount[];
artifacts: ArtifactPath[];
cohorte_armado: CohorteArmado | null;
cohorte_exclusiones: CohorteExclusion[];
artifacts: ArtifactFile[];
/** What each routine did, as its run recorded it; a kind is missing when the run didn't record it. */
routines: Partial<Record<RoutineKind, Record<string, unknown>>>;
predictions: number;
checks: PromotionCheck[];
}
export interface CohortScenario {
domain: string;
/** A cohort build that has its file, the data a notebook can run on. */
export interface CohortBuildFile {
url: string;
source: 'kit' | 'dbt';
build: number;
datos_as_of: string | null;
n_members: string | null;
}
export type ExperimentStatus = 'en_curso' | 'terminado' | 'fallido' | 'interrumpido';
/** A notebook run on a cohort build, kept as an MLflow run. */
export interface Experiment {
run_id: string;
notebook: string;
domain: Domain;
scenario: string;
criteria_version: string;
criteria: { code: string; reason_code: string; applicable_in_production: boolean }[];
version: string | null;
cohort: { url: string; source: string; build: string };
notebook_sha256: string;
/** Where it ran: `contenedor` (isolated: no network, no server files) or `local` (in the API's own process). */
sandbox: 'contenedor' | 'local' | null;
status: ExperimentStatus;
started_at: string | null;
ended_at: string | null;
}
export interface CohortVersion {
cohort_version_id: number;
domain: string;
export interface ExperimentDetail extends Experiment {
artifacts: ArtifactFile[];
error: string | null;
}
export interface ExperimentRequest {
file: File;
domain: Domain;
scenario: string;
criteria_version: string;
version_hash: string;
source_table: string;
description: string | null;
n_source: number;
n_included: number;
created_at: string;
build: CohortBuildFile;
version?: string | null;
}
export interface CohortExclusionCount {
cohort_exclusion_count_id: number;
cohort_version_id: number;
criterion_code: string;
reason_code: string;
count: number;
created_at: string;
/** 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 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;
}
}
@@ -0,0 +1,107 @@
<div class="experiments">
<div class="experiments__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="experiments__spacer"></span>
<button mat-icon-button type="button" (click)="reload()" aria-label="Recargar" matTooltip="Recargar">
<mat-icon aria-hidden="true">refresh</mat-icon>
</button>
<button mat-flat-button type="button" (click)="start()">
<mat-icon aria-hidden="true">upload_file</mat-icon>Correr un notebook
</button>
</div>
@if (loading()) {
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
}
@if (loadError(); as error) {
<p class="experiments__alert" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ error }}</p>
}
<table mat-table [dataSource]="experiments()" multiTemplateDataRows class="experiments__table">
<ng-container matColumnDef="notebook">
<th mat-header-cell *matHeaderCellDef>Notebook</th>
<td mat-cell *matCellDef="let run">
<div class="experiments__name">{{ run.notebook }}</div>
@if (run.version) {
<div class="experiments__muted">con la versión {{ run.version }}</div>
}
@if (run.sandbox === 'local') {
<div class="experiments__warning" matTooltip="Corrió en el proceso de la API, sin contenedor aislado">
<mat-icon aria-hidden="true">warning</mat-icon>Sin aislar
</div>
}
</td>
</ng-container>
<ng-container matColumnDef="scenario">
<th mat-header-cell *matHeaderCellDef>Dominio · escenario</th>
<td mat-cell *matCellDef="let run">{{ run.domain }} · {{ run.scenario }}</td>
</ng-container>
<ng-container matColumnDef="cohort">
<th mat-header-cell *matHeaderCellDef>Cohorte</th>
<td mat-cell *matCellDef="let run">{{ run.cohort.url }} · {{ run.cohort.source }} {{ run.cohort.build }}</td>
</ng-container>
<ng-container matColumnDef="status">
<th mat-header-cell *matHeaderCellDef>Estatus</th>
<td mat-cell *matCellDef="let run">
<span class="experiments__status" [class]="'experiments__status experiments__status--' + run.status">
<mat-icon aria-hidden="true">{{ status(run.status).icon }}</mat-icon>{{ status(run.status).label }}
</span>
</td>
</ng-container>
<ng-container matColumnDef="started_at">
<th mat-header-cell *matHeaderCellDef>Inicio</th>
<td mat-cell *matCellDef="let run">{{ run.started_at | date: 'short' }}</td>
</ng-container>
<ng-container matColumnDef="acciones">
<th mat-header-cell *matHeaderCellDef></th>
<td mat-cell *matCellDef="let run" class="experiments__actions">
@if (run.status !== 'en_curso') {
<a mat-button [href]="api.experimentPageUrl(run.run_id)" target="_blank" rel="noopener">
<mat-icon aria-hidden="true">open_in_new</mat-icon>Ver resultados
</a>
}
<button mat-icon-button type="button" (click)="toggle(run)" [attr.aria-expanded]="!!details()[run.run_id]"
aria-label="Archivos de la corrida" matTooltip="Archivos de la corrida">
<mat-icon aria-hidden="true">{{ details()[run.run_id] ? 'expand_less' : 'expand_more' }}</mat-icon>
</button>
</td>
</ng-container>
<ng-container matColumnDef="detail">
<td mat-cell *matCellDef="let run" [attr.colspan]="displayedColumns.length" class="experiments__detail">
@if (details()[run.run_id]; as detail) {
@if (detail.error) {
<pre class="experiments__error">{{ detail.error }}</pre>
}
<ul class="experiments__files">
@for (file of detail.artifacts; track file.path) {
<li>
<a [href]="api.experimentArtifactUrl(run.run_id, file.path)" download>
<mat-icon aria-hidden="true">download</mat-icon>{{ file.path }}
</a>
</li>
}
</ul>
<p class="experiments__muted">Huella del notebook {{ detail.notebook_sha256.slice(0, 12) }}…</p>
}
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: ['detail']" class="experiments__detail-row" [class.experiments__detail-row--open]="!!details()[row.run_id]"></tr>
</table>
@if (!loading() && experiments().length === 0) {
<p class="experiments__empty"><mat-icon aria-hidden="true">science</mat-icon>Aún no se ha corrido ningún notebook.</p>
}
</div>
@@ -0,0 +1,146 @@
.experiments {
display: flex;
flex-direction: column;
gap: var(--space-3);
}
.experiments__toolbar {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
.experiments__spacer {
flex: 1;
}
.experiments__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);
}
.experiments__table {
width: 100%;
}
.experiments__name {
font-weight: 600;
}
.experiments__muted {
color: var(--mat-sys-on-surface-variant);
font: var(--mat-sys-body-small);
margin: 0;
}
.experiments__actions {
text-align: end;
white-space: nowrap;
}
.experiments__status {
align-items: center;
border-radius: 999px;
display: inline-flex;
font: var(--mat-sys-label-medium);
gap: 4px;
padding: 2px 10px 2px 6px;
mat-icon {
font-size: 16px;
height: 16px;
width: 16px;
}
}
.experiments__status--en_curso,
.experiments__status--interrumpido {
background: var(--mat-sys-surface-container-high);
color: var(--mat-sys-on-surface-variant);
}
.experiments__status--terminado {
background: var(--mat-sys-primary-container);
color: var(--mat-sys-on-primary-container);
}
.experiments__status--fallido {
background: var(--mat-sys-error-container);
color: var(--mat-sys-on-error-container);
}
.experiments__detail-row {
height: 0;
td {
border-bottom-width: 0;
padding: 0;
}
}
.experiments__detail-row--open td {
border-bottom-width: 1px;
padding: var(--space-2) var(--space-3) var(--space-3);
}
.experiments__error {
background: var(--mat-sys-error-container);
color: var(--mat-sys-on-error-container);
font: var(--mat-sys-body-small);
margin: 0 0 var(--space-2);
max-height: 240px;
overflow: auto;
padding: var(--space-2);
white-space: pre-wrap;
}
.experiments__files {
display: flex;
flex-wrap: wrap;
gap: var(--space-2) var(--space-4);
list-style: none;
margin: 0 0 var(--space-2);
padding: 0;
a {
align-items: center;
display: inline-flex;
gap: 4px;
overflow-wrap: anywhere;
}
mat-icon {
font-size: 18px;
height: 18px;
width: 18px;
}
}
.experiments__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;
}
.experiments__warning {
align-items: center;
color: var(--mat-sys-error);
display: inline-flex;
font: var(--mat-sys-label-small);
gap: 2px;
mat-icon {
font-size: 14px;
height: 14px;
width: 14px;
}
}
@@ -0,0 +1,115 @@
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 { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatTableModule } from '@angular/material/table';
import { MatTooltipModule } from '@angular/material/tooltip';
import { Subscription, timer } from 'rxjs';
import { apiErrorMessage } from '../../../connect/api/api.types';
import { DOMAINS } from '../../../connect/state/connect-workspace.store';
import { GovernanceApi } from '../../api/governance.api';
import { Experiment, ExperimentDetail, ExperimentStatus } from '../../api/governance.types';
import { NotebookRunDefaults, NotebookRunDialog } from '../notebook-run-dialog/notebook-run-dialog';
const STATUS: Record<ExperimentStatus, { label: string; icon: string }> = {
en_curso: { label: 'En curso', icon: 'hourglass_top' },
terminado: { label: 'Terminado', icon: 'check_circle' },
fallido: { label: 'Falló', icon: 'error' },
interrumpido: { label: 'Interrumpido', icon: 'block' },
};
const POLL_MS = 5000;
/**
* Notebooks run on cohort builds: upload one, follow it while it runs, and
* open its page or download its files. The list refreshes on its own while
* a run is in progress.
*/
@Component({
selector: 'app-experiments-panel',
imports: [DatePipe, MatButtonModule, MatButtonToggleModule, MatIconModule, MatProgressBarModule, MatTableModule, MatTooltipModule],
templateUrl: './experiments-panel.html',
styleUrl: './experiments-panel.scss',
})
export class ExperimentsPanel implements OnInit {
readonly api = inject(GovernanceApi);
private readonly dialog = inject(MatDialog);
private readonly destroyRef = inject(DestroyRef);
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 experiments = signal<Experiment[]>([]);
readonly details = signal<Record<string, ExperimentDetail>>({});
readonly loading = signal(false);
readonly loadError = signal<string | null>(null);
readonly displayedColumns = ['notebook', 'scenario', 'cohort', 'status', 'started_at', 'acciones'];
private poll?: Subscription;
ngOnInit(): void {
this.reload();
}
status(status: ExperimentStatus): { label: string; icon: string } {
return STATUS[status] ?? { label: status, icon: 'help' };
}
setDomain(domain: string | null): void {
this.domain.set(domain);
this.reload();
}
start(defaults: NotebookRunDefaults = {}): void {
this.dialog
.open<NotebookRunDialog, NotebookRunDefaults, ExperimentDetail>(NotebookRunDialog, {
data: defaults,
width: '640px',
maxWidth: '96vw',
autoFocus: false,
})
.afterClosed()
.subscribe((run) => {
if (run) this.reload();
});
}
/** Loads a run's files and error the first time it's expanded. */
toggle(run: Experiment): void {
const current = { ...this.details() };
if (current[run.run_id]) {
delete current[run.run_id];
this.details.set(current);
return;
}
this.api.getExperiment(run.run_id).subscribe((detail) => this.details.set({ ...this.details(), [run.run_id]: detail }));
}
reload(quiet = false): void {
if (!quiet) this.loading.set(true);
this.loadError.set(null);
this.api
.listExperiments(this.domain() ? { domain: this.domain()! } : {})
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({
next: ({ experiments }) => {
this.loading.set(false);
this.experiments.set(experiments);
this.schedule(experiments.some((run) => run.status === 'en_curso'));
},
error: (error) => {
this.loading.set(false);
this.loadError.set(apiErrorMessage(error, 'No se pudieron cargar los notebooks.'));
},
});
}
private schedule(running: boolean): void {
this.poll?.unsubscribe();
if (!running) return;
this.poll = timer(POLL_MS)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => this.reload(true));
}
}
@@ -12,9 +12,9 @@
<app-model-versions-panel></app-model-versions-panel>
</div>
</mat-tab>
<mat-tab label="Cohortes">
<mat-tab label="Notebooks">
<div class="governance__panel">
<app-cohort-versions-panel></app-cohort-versions-panel>
<app-experiments-panel></app-experiments-panel>
</div>
</mat-tab>
<mat-tab label="Revisión de OCR">
@@ -1,18 +1,18 @@
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 { ExperimentsPanel } from '../experiments-panel/experiments-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
* notebooks run on cohort builds 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: [ExperimentsPanel, MatTabsModule, MatToolbarModule, ModelVersionsPanel, OcrReviewPanel],
templateUrl: './governance-page.html',
styleUrl: './governance-page.scss',
})
@@ -58,51 +58,71 @@
<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>
}
</section>
<section aria-labelledby="artifacts-title">
<h3 id="artifacts-title">Artefactos</h3>
<p class="muted">Guardados en la corrida de MLflow; ábrelos desde el servidor de MLflow.</p>
<section aria-labelledby="routines-title">
<h3 id="routines-title">Rutinas del entrenamiento</h3>
<p class="muted">Lo que cada rutina hizo, registrado por la corrida mientras entrenaba (ML-01a).</p>
<ul class="artifacts">
@for (artifact of l.artifacts; track artifact) {
@for (routine of routineKinds; track routine.kind) {
@let record = l.routines[routine.kind];
<li [class.checks__fail]="!record">
<mat-icon aria-hidden="true">{{ record ? 'check_circle' : 'cancel' }}</mat-icon>
<span class="artifacts__kind">{{ routine.label }}</span>
@if (record) {
<details class="routine">
<summary>{{ record['method'] ?? 'Ver registro' }}</summary>
<pre>{{ record | json }}</pre>
</details>
} @else {
<span class="muted">La corrida no la registró.</span>
}
</li>
}
</ul>
</section>
<section aria-labelledby="artifacts-title">
<h3 id="artifacts-title">Archivos de la corrida</h3>
<ul class="artifacts">
@for (file of files(l.artifacts); track file.path) {
<li>
<mat-icon aria-hidden="true">description</mat-icon>
<span class="artifacts__kind">{{ artifactKindOf(artifact) }}</span>
<span class="artifacts__name">{{ artifactName(artifact) }}</span>
<a class="artifacts__name" [href]="artifactUrl(file.path)" download>{{ file.label }}</a>
@if (file.size !== null) {
<span class="muted">{{ file.size | number }} B</span>
}
</li>
} @empty {
<li class="muted">Sin artefactos.</li>
<li class="muted">Sin archivos.</li>
}
</ul>
<div class="upload">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Tipo</mat-label>
<mat-select [value]="artifactKind()" (valueChange)="artifactKind.set($event)">
@for (kind of artifactKinds; track kind.id) {
<mat-option [value]="kind.id">{{ kind.label }}</mat-option>
}
</mat-select>
</mat-form-field>
<button mat-stroked-button type="button" [disabled]="busy()" (click)="fileInput.click()">
<mat-icon aria-hidden="true">upload_file</mat-icon>Subir artefacto
<button mat-stroked-button type="button" (click)="tryInNotebook()">
<mat-icon aria-hidden="true">science</mat-icon>Probar en un notebook
</button>
<input #fileInput type="file" hidden (change)="uploadArtifact($event)" />
<span class="muted">Corre un notebook propio sobre una cohorte, con esta versión cargada.</span>
</div>
</section>
@@ -49,8 +49,7 @@
}
.checks,
.artifacts,
.exclusions {
.artifacts {
display: flex;
flex-direction: column;
gap: var(--space-1);
@@ -98,6 +97,7 @@
.upload {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
margin-top: var(--space-2);
}
@@ -111,3 +111,37 @@
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;
}
}
.routine {
flex: 1;
min-width: 0;
summary {
cursor: pointer;
}
pre {
background: var(--mat-sys-surface-container);
font: var(--mat-sys-body-small);
margin: 4px 0 0;
max-height: 240px;
overflow: auto;
padding: 8px;
}
}
@@ -1,48 +1,47 @@
import { DatePipe, DecimalPipe } from '@angular/common';
import { DatePipe, DecimalPipe, JsonPipe } from '@angular/common';
import { Component, inject, signal } from '@angular/core';
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MAT_DIALOG_DATA, MatDialog, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSelectModule } from '@angular/material/select';
import { MatTooltipModule } from '@angular/material/tooltip';
import { Observable } from 'rxjs';
import { apiErrorMessage } from '../../../connect/api/api.types';
import { GovernanceApi } from '../../api/governance.api';
import { ModelLineage, ModelVersion, PromotionCheck } from '../../api/governance.types';
import { ArtifactFile, ModelLineage, ModelVersion, PromotionCheck, RoutineKind } from '../../api/governance.types';
import { ModelStatusChip } from '../model-status-chip/model-status-chip';
import { NotebookRunDefaults, NotebookRunDialog } from '../notebook-run-dialog/notebook-run-dialog';
export const ARTIFACT_KINDS: { id: string; label: string }[] = [
{ id: 'ONNX_CHECKPOINT', label: 'Checkpoint ONNX' },
{ id: 'MUESTREO', label: 'Muestreo' },
{ id: 'DATOS_FALTANTES', label: 'Datos faltantes' },
{ id: 'METODO_ANALITICO', label: 'Método analítico' },
{ id: 'BALANCE_CLASES', label: 'Balance de clases' },
{ id: 'CONFIANZA_SALIDA', label: 'Confianza de la salida' },
{ id: 'OTRO', label: 'Otro' },
/** The routines training records as it runs (ML-01a), in the order they happen. */
export const ROUTINES: { kind: RoutineKind; label: string }[] = [
{ kind: 'MUESTREO', label: 'Muestreo' },
{ kind: 'DATOS_FALTANTES', label: 'Datos faltantes' },
{ kind: 'METODO_ANALITICO', label: 'Método analítico' },
{ kind: 'BALANCE_CLASES', label: 'Balance de clases' },
{ kind: 'CONFIANZA_SALIDA', label: 'Confianza de la salida' },
];
/**
* One model version: what it was trained on (cohort hash and exclusions),
* 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.
* One model version: what it was trained on (the kit's cohort build and its attrition),
* what each routine did as it trained, the files its run stored, its validation
* reports, and the checklist that must pass before it can serve predictions.
* Closes with `true` when the version changed.
*/
@Component({
selector: 'app-model-version-dialog',
imports: [
DatePipe,
DecimalPipe,
JsonPipe,
MatButtonModule,
MatDialogModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatProgressBarModule,
MatSelectModule,
MatTooltipModule,
ModelStatusChip,
ReactiveFormsModule,
@@ -54,8 +53,9 @@ export class ModelVersionDialog {
private readonly api = inject(GovernanceApi);
private readonly dialogRef = inject<MatDialogRef<ModelVersionDialog, boolean>>(MatDialogRef);
private readonly version = inject<ModelVersion>(MAT_DIALOG_DATA);
private readonly dialog = inject(MatDialog);
readonly artifactKinds = ARTIFACT_KINDS;
readonly routineKinds = ROUTINES;
readonly lineage = signal<ModelLineage | null>(null);
readonly busy = signal(false);
readonly error = signal<string | null>(null);
@@ -66,7 +66,6 @@ export class ModelVersionDialog {
clinical_validation_report_uri: [''],
interpretability_report_uri: [''],
});
readonly artifactKind = signal('ONNX_CHECKPOINT');
constructor() {
this.load();
@@ -93,12 +92,25 @@ export class ModelVersionDialog {
return Object.entries(version.metrics ?? {});
}
artifactName(path: string): string {
return path.split('/').pop() ?? path;
/** The run's files, with the saved model as one folder (it downloads as a zip). */
files(artifacts: ArtifactFile[]): { path: string; label: string; size: number | null }[] {
const model = artifacts.filter((file) => file.path.startsWith('model/'));
const rest = artifacts.filter((file) => !file.path.startsWith('model/'));
const folder = model.length ? [{ path: 'model', label: 'model (modelo guardado, .zip)', size: null }] : [];
return [...folder, ...rest.map((file) => ({ ...file, label: file.path }))];
}
artifactKindOf(path: string): string {
return path.split('/')[0] ?? path;
artifactUrl(path: string): string {
return this.api.artifactUrl(this.domain, this.scenario, this.version.version, path);
}
tryInNotebook(): void {
this.dialog.open<NotebookRunDialog, NotebookRunDefaults>(NotebookRunDialog, {
data: { domain: this.domain as NotebookRunDefaults['domain'], scenario: this.scenario, version: this.version.version },
width: '640px',
maxWidth: '96vw',
autoFocus: false,
});
}
saveReports(): void {
@@ -110,13 +122,6 @@ export class ModelVersionDialog {
}));
}
uploadArtifact(event: Event): void {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
input.value = '';
if (file) this.run(this.api.uploadArtifact(this.domain, this.scenario, this.version.version, this.artifactKind(), file));
}
promote(): void {
this.run(this.api.promoteModelVersion(this.domain, this.scenario, this.version.version));
}
@@ -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();
@@ -0,0 +1,76 @@
<h2 mat-dialog-title>Correr un notebook</h2>
<mat-dialog-content class="content">
<p class="hint">
El notebook corre aislado en el servidor, sin red y con los datos de la cohorte que elija como única información: no
ve las bases de datos ni los demás archivos. Dentro usa <code>from models.notebook import experiment</code> para leer
la cohorte, cargar la versión elegida o entrenar; lo que entrene se registra como versión de desarrollo al terminar.
La corrida guarda el notebook, la página con sus resultados y con qué datos se corrió.
</p>
<div class="file">
<button mat-stroked-button type="button" [disabled]="busy()" (click)="fileInput.click()">
<mat-icon aria-hidden="true">upload_file</mat-icon>Elegir notebook
</button>
<span class="file__name">{{ file()?.name ?? 'Ningún archivo (.ipynb)' }}</span>
<input #fileInput type="file" accept=".ipynb,application/x-ipynb+json" hidden (change)="pick($event)" />
</div>
<div class="grid">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Dominio</mat-label>
<mat-select [ngModel]="domain()" (ngModelChange)="setDomain($event)">
@for (option of domains; track option.id) {
<mat-option [value]="option.id">{{ option.label }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Escenario</mat-label>
<input matInput [ngModel]="scenario()" (ngModelChange)="setScenario($event)" placeholder="cin2_logistic" />
@if (scenario() && !scenarioValid()) {
<mat-error>Solo letras, números, guion y guion bajo.</mat-error>
} @else {
<mat-hint>El de un modelo existente o uno nuevo para el experimento.</mat-hint>
}
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="grid__wide">
<mat-label>Cohorte</mat-label>
<mat-select [ngModel]="build()" (ngModelChange)="build.set($event)" [compareWith]="sameBuild">
@for (option of builds(); track option.url + option.source + option.build) {
<mat-option [value]="option">{{ buildLabel(option) }}</mat-option>
}
</mat-select>
@if (!builds().length) {
<mat-hint>Este dominio no tiene cohortes exportadas a archivo.</mat-hint>
}
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="grid__wide">
<mat-label>Versión de modelo (opcional)</mat-label>
<mat-select [ngModel]="version()" (ngModelChange)="version.set($event)">
<mat-option value="">Ninguna</mat-option>
@for (option of versions(); track option.version) {
<mat-option [value]="option.version">{{ option.name }}:{{ option.version }} · {{ option.status }}</mat-option>
}
</mat-select>
<mat-hint>El notebook la carga con <code>experiment().model()</code>.</mat-hint>
</mat-form-field>
</div>
@if (busy()) {
<mat-progress-bar mode="indeterminate" aria-label="Iniciando"></mat-progress-bar>
}
@if (error(); as message) {
<p class="alert" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ message }}</p>
}
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button type="button" mat-dialog-close>Cancelar</button>
<button mat-flat-button type="button" [disabled]="!ready()" (click)="run()">
<mat-icon aria-hidden="true">play_arrow</mat-icon>Correr
</button>
</mat-dialog-actions>
@@ -0,0 +1,41 @@
.content {
display: grid;
gap: 16px;
}
.hint {
color: var(--mat-sys-on-surface-variant);
font: var(--mat-sys-body-medium);
margin: 0;
}
.file {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: 12px;
}
.file__name {
color: var(--mat-sys-on-surface-variant);
font: var(--mat-sys-body-medium);
overflow-wrap: anywhere;
}
.grid {
display: grid;
gap: 16px;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
}
.grid__wide {
grid-column: 1 / -1;
}
.alert {
align-items: center;
color: var(--mat-sys-error);
display: flex;
gap: 8px;
margin: 0;
}
@@ -0,0 +1,72 @@
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { NotebookRunDialog } from './notebook-run-dialog';
/**
* The dialog that uploads a notebook and runs it on a cohort build: it starts
* from a version's defaults, offers the domain's exported builds, and sends
* the build the person chose. The API is `HttpTestingController`; the dialog
* reference is a stub that records how it closed.
*/
describe('NotebookRunDialog', () => {
let http: HttpTestingController;
const close = vi.fn();
const build = { url: 'cacu/cohorte_vigilancia', source: 'dbt', build: 4, datos_as_of: '2025-12-31', n_members: '10' };
function open(data: object) {
TestBed.configureTestingModule({
imports: [NotebookRunDialog],
providers: [
provideHttpClient(),
provideHttpClientTesting(),
{ provide: MAT_DIALOG_DATA, useValue: data },
{ provide: MatDialogRef, useValue: { close } },
],
});
http = TestBed.inject(HttpTestingController);
const fixture = TestBed.createComponent(NotebookRunDialog);
fixture.detectChanges();
return fixture;
}
afterEach(() => {
http.verify();
close.mockReset();
});
it('sends the chosen build and version with the notebook, and closes with the run', () => {
// Fails if the form stops carrying the build's url, source and number, or drops the version it was opened with.
const fixture = open({ domain: 'cacu', scenario: 'cin2_logistic', version: '3' });
http.expectOne((r) => r.url === '/governance/cohort-files' && r.params.get('domain') === 'cacu').flush({ builds: [build] });
http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] });
const dialog = fixture.componentInstance;
expect(dialog.ready()).toBe(false);
dialog.file.set(new File(['{}'], 'analisis.ipynb'));
expect(dialog.ready()).toBe(true);
dialog.run();
const request = http.expectOne('/governance/experiments');
const form = request.request.body as FormData;
expect([form.get('url'), form.get('source'), form.get('build'), form.get('version')]).toEqual([
'cacu/cohorte_vigilancia', 'dbt', '4', '3',
]);
request.flush({ run_id: 'r1', status: 'en_curso' });
expect(close).toHaveBeenCalledWith(expect.objectContaining({ run_id: 'r1' }));
});
it('refuses a scenario that the API would reject', () => {
// Fails if `ready` stops checking the scenario's characters before uploading.
const fixture = open({});
http.expectOne((r) => r.url === '/governance/cohort-files').flush({ builds: [build] });
const dialog = fixture.componentInstance;
dialog.file.set(new File(['{}'], 'a.ipynb'));
dialog.setScenario("x' OR 1=1");
expect(dialog.ready()).toBe(false);
dialog.setScenario('exploracion');
http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] });
expect(dialog.ready()).toBe(true);
});
});
@@ -0,0 +1,133 @@
import { Component, computed, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSelectModule } from '@angular/material/select';
import { Domain, apiErrorMessage } from '../../../connect/api/api.types';
import { DOMAINS } from '../../../connect/state/connect-workspace.store';
import { GovernanceApi } from '../../api/governance.api';
import { CohortBuildFile, ExperimentDetail, ModelVersion } from '../../api/governance.types';
/** What the dialog starts with: a version's dialog passes its own domain, scenario and version. */
export interface NotebookRunDefaults {
domain?: Domain;
scenario?: string;
version?: string;
}
const SCENARIO = /^[\w-]{1,100}$/;
/**
* Uploads a Jupyter notebook and runs it on a cohort build's file, optionally
* with a registered version to try. Closes with the run once it has started.
*/
@Component({
selector: 'app-notebook-run-dialog',
imports: [
FormsModule,
MatButtonModule,
MatDialogModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatProgressBarModule,
MatSelectModule,
],
templateUrl: './notebook-run-dialog.html',
styleUrl: './notebook-run-dialog.scss',
})
export class NotebookRunDialog {
private readonly api = inject(GovernanceApi);
private readonly dialogRef = inject<MatDialogRef<NotebookRunDialog, ExperimentDetail>>(MatDialogRef);
private readonly defaults = inject<NotebookRunDefaults | null>(MAT_DIALOG_DATA, { optional: true }) ?? {};
readonly domains = DOMAINS;
readonly domain = signal<Domain>(this.defaults.domain ?? 'cacu');
readonly scenario = signal(this.defaults.scenario ?? '');
readonly version = signal<string>(this.defaults.version ?? '');
readonly file = signal<File | null>(null);
readonly builds = signal<CohortBuildFile[]>([]);
readonly build = signal<CohortBuildFile | null>(null);
readonly versions = signal<ModelVersion[]>([]);
readonly busy = signal(false);
readonly error = signal<string | null>(null);
readonly scenarioValid = computed(() => SCENARIO.test(this.scenario()));
readonly ready = computed(() => !!this.file() && !!this.build() && this.scenarioValid() && !this.busy());
constructor() {
this.loadBuilds();
this.loadVersions();
}
buildLabel(build: CohortBuildFile): string {
const members = build.n_members ? ` · ${build.n_members} miembros` : '';
const asOf = build.datos_as_of ? ` · datos al ${build.datos_as_of}` : '';
return `${build.url} · ${build.source} ${build.build}${members}${asOf}`;
}
sameBuild(a: CohortBuildFile | null, b: CohortBuildFile | null): boolean {
return !!a && !!b && a.url === b.url && a.source === b.source && a.build === b.build;
}
setDomain(domain: Domain): void {
this.domain.set(domain);
this.version.set('');
this.loadBuilds();
this.loadVersions();
}
setScenario(scenario: string): void {
this.scenario.set(scenario.trim());
this.version.set('');
this.loadVersions();
}
pick(event: Event): void {
const input = event.target as HTMLInputElement;
this.file.set(input.files?.[0] ?? null);
input.value = '';
}
run(): void {
const file = this.file();
const build = this.build();
if (!file || !build || !this.ready()) return;
this.busy.set(true);
this.error.set(null);
this.api
.runExperiment({ file, domain: this.domain(), scenario: this.scenario(), build, version: this.version() || null })
.subscribe({
next: (run) => this.dialogRef.close(run),
error: (error) => {
this.busy.set(false);
this.error.set(apiErrorMessage(error, 'No se pudo iniciar el notebook.'));
},
});
}
private loadBuilds(): void {
this.builds.set([]);
this.build.set(null);
this.api.cohortFiles(this.domain()).subscribe({
next: ({ builds }) => {
this.builds.set(builds);
this.build.set(builds[0] ?? null);
},
error: (error) => this.error.set(apiErrorMessage(error, 'No se pudieron cargar las cohortes exportadas.')),
});
}
private loadVersions(): void {
this.versions.set([]);
if (!this.scenarioValid()) return;
this.api.listModelVersions({ domain: this.domain(), scenario: this.scenario() }).subscribe({
next: ({ model_versions }) => this.versions.set(model_versions),
error: () => this.versions.set([]),
});
}
}
+51 -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,51 +52,62 @@
</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>
@if ((source.etiquetas_sin_usar | keyvalue)?.length || source.etiquetas_sin_usar_poco_frecuentes) {
<p class="reportes__hint">
Etiquetas que los documentos traen y no se usaron (puede asignarlas en la siguiente carga):
@for (caption of source.etiquetas_sin_usar | keyvalue; track caption.key) {
<span class="chip">{{ caption.key }} ×{{ caption.value }}</span>
}
@if (source.etiquetas_sin_usar_poco_frecuentes) {
<span class="chip">otras {{ source.etiquetas_sin_usar_poco_frecuentes }} poco frecuentes</span>
}
</p>
}
}
<table class="campos">
<thead>
<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 })),
);
}
}
+24 -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,37 @@ 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>;
/** Captions the source's documents print that the import didn't use, with how many records print each. */
etiquetas_sin_usar?: Record<string, number>;
/** How many more such captions too few records print to be listed. */
etiquetas_sin_usar_poco_frecuentes?: number;
}
/** 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 +54,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 -6
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,9 +109,8 @@ body {
}
/* Global rules of the vendored indicators dashboard (fork `dev`): the
floating "navegación gráfica" trigger and its overlay 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;
}