Compare commits

..

7 Commits

111 changed files with 3346 additions and 4416 deletions
-10
View File
@@ -2,21 +2,11 @@ import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { IndicadoresService } from './features/indicadores/indicadores.service';
import { IndicadoresPeriodos } from './features/indicadores/indicadores-periodos';
import { TeaSeguimientoService } from './features/indicadores/tea-seguimiento.service';
import { FhirIndicadoresPeriodos, FhirIndicadoresService } from './features/indicadores/indicadores-fhir';
import { FhirTeaSeguimientoService } from './features/indicadores/tea-seguimiento-fhir';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
provideHttpClient(),
// The indicator page reads the WebApi's FHIR endpoint; without these lines it reads the indicator JSON contract
// (`/<domain>/indicadores/<id>/datos`, `/tea/seguimiento`).
{ provide: IndicadoresService, useClass: FhirIndicadoresService },
{ provide: IndicadoresPeriodos, useClass: FhirIndicadoresPeriodos },
{ provide: TeaSeguimientoService, useClass: FhirTeaSeguimientoService },
]
};
-6
View File
@@ -6,12 +6,6 @@ const loadIndicadores = () => import('./features/indicadores/indicadores-page').
export const routes: Routes = [
{ path: '', component: Home, title: 'Análisis de información | ISSSTELEON' },
{
path: 'indicadores/tea-estatus',
title: 'Casos por estatus | ISSSTELEON',
loadComponent: () => import('./features/indicadores/tea-status-page').then(m => m.TeaStatusPage),
data: { workspace: true, breadcrumb: 'Casos por estatus' },
},
{
path: 'conectar',
title: 'Conectar datos | ISSSTELEON',
+65 -1
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,6 +136,56 @@ 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;
}
// 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
@@ -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 {
+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 });
@@ -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,
@@ -95,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(() => {
@@ -102,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');
}
@@ -143,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() });
@@ -133,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 {
@@ -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,
@@ -0,0 +1,238 @@
@let f = flow();
@let docs = documentForm();
<div class="rules">
<section class="rules__section" aria-labelledby="documents-title">
<header class="rules__header">
<h3 id="documents-title"><mat-icon aria-hidden="true">document_scanner</mat-icon>Documentos dentro de columnas</h3>
@if (f.documents()) {
<span class="rules__badge">Leyendo {{ f.documents()!.columns.length }} columna(s)</span>
}
</header>
<p class="rules__hint">
Si alguna columna guarda archivos (PDF o imágenes, como binario, hexadecimal o base64), se leen y todo lo que
imprimen (campos conocidos y cualquier otra etiqueta) aparece como columnas nuevas que puede asignar o usar en reglas.
Los valores que vienen de columnas de la fuente se respetan por encima de lo que diga el documento.
@if (f.documentColumns().length) {
Columnas con archivos detectadas: <strong>{{ f.documentColumns().join(', ') }}</strong>.
}
</p>
<div class="rules__grid">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Columnas con documentos</mat-label>
<mat-select multiple [ngModel]="docs.columns" (ngModelChange)="patchDocuments({ columns: $event })">
@for (name of columnNames(); track name) {
<mat-option [value]="name">{{ name }}@if (f.documentColumns().includes(name)) { (archivo) }</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Agrupar registros por</mat-label>
<mat-select [ngModel]="docs.group_by" (ngModelChange)="patchDocuments({ group_by: $event })">
<mat-option value="">Por el identificador del paciente</mat-option>
@for (name of columnNames(); track name) {
<mat-option [value]="name">{{ name }}</mat-option>
}
</mat-select>
<mat-hint>Las filas con el mismo valor forman un solo registro (p. ej. un número de estudio).</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Guardar el documento en</mat-label>
<mat-select [ngModel]="docs.file_field" (ngModelChange)="patchDocuments({ file_field: $event })">
<mat-option value="">No guardar</mat-option>
@for (field of fileFields(); track field.name) {
<mat-option [value]="field.name">{{ field.name }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>OCR</mat-label>
<mat-select [ngModel]="docs.ocr_mode" (ngModelChange)="patchDocuments({ ocr_mode: $event })">
<mat-option value="auto">Solo páginas escaneadas</mat-option>
<mat-option value="always">Todas las páginas</mat-option>
<mat-option value="never">Nunca (solo texto del PDF)</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Solo documentos que digan</mat-label>
<input matInput [ngModel]="docs.include_pattern" (ngModelChange)="patchDocuments({ include_pattern: $event })" />
<mat-hint>Expresión regular; sin distinguir mayúsculas ni acentos.</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Omitir documentos que digan</mat-label>
<input matInput [ngModel]="docs.exclude_pattern" (ngModelChange)="patchDocuments({ exclude_pattern: $event })" />
</mat-form-field>
</div>
<mat-checkbox [checked]="f.catalogFallback()" (change)="f.setCatalogFallback($event.checked)">
Guardar también, en el expediente de cada paciente, las etiquetas de los documentos que el catálogo del proyecto ya
conoce
</mat-checkbox>
<p class="rules__hint">
Las etiquetas que nadie usa no se guardan: aparecen, solo con su nombre y cuántos registros las traen, en la
Bitácora de cargas.
</p>
<div class="rules__actions">
<button mat-flat-button type="button" [disabled]="documentsBusy()" (click)="applyDocuments()">
<mat-icon aria-hidden="true">play_arrow</mat-icon>Leer documentos
</button>
@if (f.documents()) {
<button mat-button type="button" (click)="clearDocuments()">Dejar de leerlos</button>
}
</div>
@if (documentsBusy()) {
<mat-progress-bar mode="indeterminate" />
}
@if (documentsError(); as error) {
<p class="rules__error" role="alert">{{ error }}</p>
}
</section>
<section class="rules__section" aria-labelledby="derived-title">
<header class="rules__header">
<h3 id="derived-title"><mat-icon aria-hidden="true">functions</mat-icon>Campos calculados</h3>
</header>
<p class="rules__hint">
Para cuando las columnas no coinciden una a una con los campos: unir nombre y apellidos, separar un nombre completo,
tomar la primera columna con valor, extraer un dato de un texto o traducir códigos. Funciona igual con columnas de la
fuente y con lo leído de los documentos.
</p>
@for (item of rules(); track item.field) {
<div class="rule">
<mat-icon aria-hidden="true">arrow_forward</mat-icon>
<strong>{{ item.field }}</strong>
<span class="rule__summary">{{ item.summary }}</span>
<button mat-icon-button type="button" [attr.aria-label]="'Quitar regla de ' + item.field" (click)="removeRule(item.field)">
<mat-icon>delete</mat-icon>
</button>
</div>
}
<div class="rules__grid">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Campo</mat-label>
<mat-select [ngModel]="ruleField()" (ngModelChange)="ruleField.set($event)">
@for (field of f.target.fields; track field.name) {
<mat-option [value]="field.name">{{ field.name }}@if (field.required) { * }</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Cómo calcularlo</mat-label>
<mat-select [ngModel]="ruleOp()" (ngModelChange)="chooseOp($event)">
@for (spec of catalog()?.derivations ?? []; track spec.op) {
<mat-option [value]="spec.op" [matTooltip]="spec.description">{{ spec.label }}</mat-option>
}
</mat-select>
@if (selectedSpec(); as spec) {
<mat-hint>{{ spec.description }}</mat-hint>
}
</mat-form-field>
@for (param of selectedSpec()?.params ?? []; track param.name) {
@switch (param.kind) {
@case ('column') {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>{{ param.label }}</mat-label>
<mat-select [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)">
@for (name of columnNames(); track name) {
<mat-option [value]="name">{{ name }}</mat-option>
}
</mat-select>
</mat-form-field>
}
@case ('columns') {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>{{ param.label }} (en orden)</mat-label>
<mat-select multiple [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)">
@for (name of columnNames(); track name) {
<mat-option [value]="name">{{ name }}</mat-option>
}
</mat-select>
</mat-form-field>
}
@case ('integer') {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>{{ param.label }}</mat-label>
<input matInput type="number" [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)" />
</mat-form-field>
}
@case ('boolean') {
<mat-checkbox [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)">{{ param.label }}</mat-checkbox>
}
@case ('mapping') {
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="rules__wide">
<mat-label>{{ param.label }}</mat-label>
<textarea matInput rows="3" placeholder="M = Masculino" [ngModel]="mappingText(param.name)" (ngModelChange)="setMappingText(param.name, $event)"></textarea>
<mat-hint>Una equivalencia por línea: valor = nuevo valor.</mat-hint>
</mat-form-field>
}
@default {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>{{ param.label }}</mat-label>
<input matInput [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)" />
</mat-form-field>
}
}
}
@if (selectedSpec()) {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Mayúsculas</mat-label>
<mat-select [ngModel]="ruleCase()" (ngModelChange)="ruleCase.set($event)">
<mat-option value="">Sin cambio</mat-option>
<mat-option value="upper">MAYÚSCULAS</mat-option>
<mat-option value="lower">minúsculas</mat-option>
<mat-option value="title">Tipo Título</mat-option>
</mat-select>
</mat-form-field>
}
</div>
<div class="rules__actions">
<button mat-stroked-button type="button" [disabled]="!ruleField() || !selectedSpec()" (click)="addRule()">
<mat-icon aria-hidden="true">add</mat-icon>Agregar regla
</button>
</div>
@if (ruleError(); as error) {
<p class="rules__error" role="alert">{{ error }}</p>
}
</section>
<section class="rules__section" aria-labelledby="result-title">
<header class="rules__header">
<h3 id="result-title"><mat-icon aria-hidden="true">preview</mat-icon>Resultado</h3>
<button mat-stroked-button type="button" [disabled]="previewBusy()" (click)="preview()">
<mat-icon aria-hidden="true">visibility</mat-icon>Ver cómo quedarían las filas
</button>
</header>
@if (previewBusy()) {
<mat-progress-bar mode="indeterminate" />
}
@if (previewError(); as error) {
<p class="rules__error" role="alert">{{ error }}</p>
}
@if (previewRows(); as rows) {
<div class="rules__table-wrap">
<table class="rules__table">
<thead>
<tr>
@for (column of previewColumns(); track column) {
<th scope="col">{{ column }}</th>
}
</tr>
</thead>
<tbody>
@for (row of rows; track $index) {
<tr>
@for (column of previewColumns(); track column) {
<td>{{ cell(row[column]) }}</td>
}
</tr>
} @empty {
<tr><td>La fuente no dio filas.</td></tr>
}
</tbody>
</table>
</div>
}
</section>
</div>
@@ -0,0 +1,113 @@
:host {
display: block;
}
.rules {
display: flex;
flex-direction: column;
gap: 24px;
padding: 16px;
}
.rules__section {
display: flex;
flex-direction: column;
gap: 12px;
}
.rules__header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
h3 {
display: flex;
align-items: center;
gap: 8px;
margin: 0;
font: var(--mat-sys-title-medium);
}
}
.rules__badge {
font: var(--mat-sys-label-medium);
color: var(--mat-sys-primary);
}
.rules__hint {
margin: 0;
font: var(--mat-sys-body-small);
color: var(--mat-sys-on-surface-variant);
}
.rules__grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
gap: 12px 16px;
align-items: start;
}
.rules__wide {
grid-column: 1 / -1;
}
.rules__actions {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.rules__error {
margin: 0;
color: var(--mat-sys-error);
font: var(--mat-sys-body-medium);
}
.rule {
display: flex;
align-items: center;
gap: 8px;
padding: 4px 8px;
border-radius: 8px;
background: var(--mat-sys-surface-container);
}
.rule__summary {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--mat-sys-on-surface-variant);
}
.rules__table-wrap {
overflow-x: auto;
max-height: 360px;
border: 1px solid var(--mat-sys-outline-variant);
border-radius: 8px;
}
.rules__table {
border-collapse: collapse;
font: var(--mat-sys-body-small);
th,
td {
padding: 4px 8px;
border-bottom: 1px solid var(--mat-sys-outline-variant);
text-align: left;
white-space: nowrap;
max-width: 240px;
overflow: hidden;
text-overflow: ellipsis;
}
th {
position: sticky;
top: 0;
background: var(--mat-sys-surface-container-high);
}
}
@@ -0,0 +1,255 @@
import { Component, computed, effect, inject, input, signal } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSelectModule } from '@angular/material/select';
import { MatTooltipModule } from '@angular/material/tooltip';
import { firstValueFrom } from 'rxjs';
import {
DerivationParam,
DerivationRule,
DerivationSpec,
DocumentColumnsConfig,
OcrMode,
Row,
apiErrorMessage,
} from '../../api/api.types';
import { ImportsApi } from '../../api/imports.api';
import { ImportFlow } from '../../domain/import-flow';
interface DocumentForm {
columns: string[];
group_by: string;
file_field: string;
ocr_mode: OcrMode;
include_pattern: string;
exclude_pattern: string;
}
/**
* What a plain column-to-field mapping can't express, for any kind of
* source: columns whose cells hold documents (read for every field and
* caption they print, which then become columns of their own), target
* fields computed from several columns, and a look at the rows as they
* would be written.
*
* The operations and their parameters come from the server
* (`/imports/derivations`), so a new operation needs no change here.
*/
@Component({
selector: 'app-mapping-rules',
imports: [
FormsModule,
MatButtonModule,
MatCheckboxModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatProgressBarModule,
MatSelectModule,
MatTooltipModule,
],
templateUrl: './mapping-rules.html',
styleUrl: './mapping-rules.scss',
})
export class MappingRules {
readonly flow = input.required<ImportFlow>();
private readonly api = inject(ImportsApi);
readonly catalog = toSignal(this.api.derivations());
readonly columnNames = computed(() => this.flow().sourceColumns().map((column) => column.name));
readonly fileFields = computed(() => this.flow().target.fields.filter((field) => field.type === 'binary' || field.name.endsWith('_blob')));
readonly documentForm = signal<DocumentForm>(this.emptyDocumentForm());
readonly documentsBusy = signal(false);
readonly documentsError = signal<string | null>(null);
readonly ruleField = signal<string>('');
readonly ruleOp = signal<string>('');
readonly ruleParams = signal<Record<string, unknown>>({});
readonly ruleCase = signal<string>('');
readonly ruleError = signal<string | null>(null);
readonly previewRows = signal<Row[] | null>(null);
readonly previewBusy = signal(false);
readonly previewError = signal<string | null>(null);
readonly selectedSpec = computed<DerivationSpec | undefined>(() =>
this.catalog()?.derivations.find((spec) => spec.op === this.ruleOp()),
);
readonly rules = computed(() =>
Object.entries(this.flow().derived()).map(([field, rule]) => ({ field, rule, summary: this.describe(rule) })),
);
readonly previewColumns = computed(() => {
const rows = this.previewRows() ?? [];
return [...new Set(rows.flatMap((row) => Object.keys(row)))];
});
constructor() {
// The form follows the flow: what it has configured, or the columns the server flagged.
effect(() => {
const flow = this.flow();
const current = flow.documents();
this.documentForm.set(current ? this.formFrom(current) : { ...this.emptyDocumentForm(), columns: flow.documentColumns() });
});
}
// -- documents -----------------------------------------------------------
patchDocuments(patch: Partial<DocumentForm>): void {
this.documentForm.update((form) => ({ ...form, ...patch }));
}
async applyDocuments(): Promise<void> {
const form = this.documentForm();
const flow = this.flow();
if (!form.columns.length) {
this.clearDocuments();
return;
}
flow.setDocuments({
columns: form.columns,
group_by: form.group_by || undefined,
file_field: form.file_field || undefined,
ocr_mode: form.ocr_mode,
include_pattern: form.include_pattern.trim() || undefined,
exclude_pattern: form.exclude_pattern.trim() || undefined,
});
this.documentsBusy.set(true);
this.documentsError.set(null);
try {
flow.useDocumentPreview(await firstValueFrom(this.api.documentColumns(await flow.toPayload())));
} catch (error) {
this.documentsError.set(apiErrorMessage(error, 'No se pudieron leer los documentos.'));
} finally {
this.documentsBusy.set(false);
}
}
clearDocuments(): void {
this.flow().setDocuments(null);
this.documentsError.set(null);
}
// -- derived fields ------------------------------------------------------
chooseOp(op: string): void {
this.ruleOp.set(op);
const spec = this.catalog()?.derivations.find((candidate) => candidate.op === op);
this.ruleParams.set(Object.fromEntries((spec?.params ?? []).map((param) => [param.name, this.initial(param)])));
this.ruleError.set(null);
}
setParam(name: string, value: unknown): void {
this.ruleParams.update((params) => ({ ...params, [name]: value }));
}
/** `clave = valor` lines, the text form of a `mapping` parameter. */
mappingText(name: string): string {
const value = this.ruleParams()[name];
return value && typeof value === 'object' ? Object.entries(value).map(([k, v]) => `${k} = ${v}`).join('\n') : '';
}
setMappingText(name: string, text: string): void {
const entries = text
.split('\n')
.map((line) => line.split('='))
.filter((parts) => parts.length >= 2 && parts[0].trim())
.map(([key, ...rest]) => [key.trim(), rest.join('=').trim()]);
this.setParam(name, Object.fromEntries(entries));
}
addRule(): void {
const spec = this.selectedSpec();
const field = this.ruleField();
if (!spec || !field) return;
const params = this.ruleParams();
const missing = spec.params.filter((param) => param.required && this.blank(params[param.name]));
if (missing.length) {
this.ruleError.set(`Falta: ${missing.map((param) => param.label).join(', ')}`);
return;
}
const rule: DerivationRule = { op: spec.op };
for (const param of spec.params) {
const value = params[param.name];
if (!this.blank(value)) rule[param.name] = param.kind === 'integer' ? Number(value) : value;
}
if (this.ruleCase()) rule.case = this.ruleCase();
this.flow().setDerived(field, rule);
this.ruleField.set('');
this.ruleOp.set('');
this.ruleParams.set({});
this.ruleCase.set('');
this.ruleError.set(null);
}
removeRule(field: string): void {
this.flow().setDerived(field, null);
}
// -- preview ---------------------------------------------------------------
async preview(): Promise<void> {
this.previewBusy.set(true);
this.previewError.set(null);
try {
const { rows } = await firstValueFrom(this.api.mappedPreview(await this.flow().toPayload(), 10));
this.previewRows.set(rows);
} catch (error) {
this.previewError.set(apiErrorMessage(error, 'No se pudo armar la vista previa.'));
} finally {
this.previewBusy.set(false);
}
}
cell(value: unknown): string {
if (value === null || value === undefined) return '';
return typeof value === 'object' ? JSON.stringify(value) : String(value);
}
private describe(rule: DerivationRule): string {
const spec = this.catalog()?.derivations.find((candidate) => candidate.op === rule.op);
const parts = (spec?.params ?? [])
.filter((param) => !this.blank(rule[param.name]))
.map((param) => `${param.label}: ${this.cell(rule[param.name])}`);
return [spec?.label ?? rule.op, ...parts, ...(rule.case ? [`(${rule.case})`] : [])].join(' · ');
}
private initial(param: DerivationParam): unknown {
if (param.kind === 'columns') return [];
if (param.kind === 'mapping') return {};
return param.default ?? (param.kind === 'boolean' ? false : '');
}
private blank(value: unknown): boolean {
return (
value === null ||
value === undefined ||
(typeof value === 'string' && !value.trim()) ||
(Array.isArray(value) && !value.length) ||
(typeof value === 'object' && !Array.isArray(value) && !Object.keys(value as object).length)
);
}
private emptyDocumentForm(): DocumentForm {
return { columns: [], group_by: '', file_field: '', ocr_mode: 'auto', include_pattern: '', exclude_pattern: '' };
}
private formFrom(config: DocumentColumnsConfig): DocumentForm {
return {
columns: config.columns,
group_by: typeof config.group_by === 'string' ? config.group_by : '',
file_field: config.file_field ?? '',
ocr_mode: config.ocr_mode ?? 'auto',
include_pattern: config.include_pattern ?? '',
exclude_pattern: config.exclude_pattern ?? '',
};
}
}
@@ -92,4 +92,40 @@ describe('ImportFlow', () => {
expect(flow.autoMap()).toBe(1);
expect(flow.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);
});
});
+82 -4
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();
@@ -161,6 +185,9 @@ export class ImportFlow {
map(source: string, field: string): void {
this.mapping.assign(source, field);
if (this._derived()[field]) {
this._derived.update(({ [field]: _, ...rest }) => rest);
}
this.touch();
}
@@ -188,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 };
@@ -215,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 } : {}),
};
}
@@ -256,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,4 +1,4 @@
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; }
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; page: number; page_size: number; }
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
export interface SeguimientoPaciente {
id_seudonimo: string;
@@ -16,10 +16,11 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
afterEach(()=>{ fixture.destroy(); http.verify(); });
function open() { fixture.componentRef.setInput('active',true); fixture.detectChanges(); return http.expectOne(r=>r.url==='/cacu/seguimiento'); }
function respond() { open().flush(fixtureData); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({categorias:{NORMAL:{etiqueta:'Normal'}}}); fixture.detectChanges(); }
it('sin selector de prioridad ni filtros de TEA, y sin parámetros nuevos al consultar o paginar', () => {
it('prioridad deshabilitada con una sola opción y sin parámetros nuevos al consultar o paginar', () => {
respond();
expect(fixture.nativeElement.querySelector('select[name="prioridad"]')).toBeNull();
expect(fixture.nativeElement.querySelector('select[name="mchat"]')).toBeNull();
const select = fixture.nativeElement.querySelector('select[name="prioridad"]') as HTMLSelectElement;
expect(select.disabled).toBe(true); expect(select.labels?.[0].textContent).toContain('Ordenar por prioridad');
expect(Array.from(select.options).map(o => o.text)).toEqual(['No disponible']);
const order = fixture.componentInstance.data!.items.map(i => i.id_seudonimo);
expect(Array.from(fixture.nativeElement.querySelectorAll('tbody tr td:first-child')).map(e => (e as HTMLElement).textContent)).toEqual(order);
fixture.componentInstance.apply();
@@ -91,7 +92,7 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow();
open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull();
});
it.each(['cama'])('%s conserva su estado pendiente sin consultas de pacientes', dominio => {
it.each(['tea','cama'])('%s conserva su estado pendiente sin consultas de pacientes', dominio => {
fixture.componentRef.setInput('dominio',dominio); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true);
expect(fixture.nativeElement.textContent).toContain('El seguimiento aún no está disponible');
expect(fixture.nativeElement.textContent).not.toContain('Columnas propuestas para revisión.');
-54
View File
@@ -1,54 +0,0 @@
// The parts of FHIR R4 the WebApi's `/<domain>/fhir/` endpoints serve, read loosely: every field is optional and the
// readers below decide what a missing one means.
export interface Coding { system?: string; code?: string; display?: string }
export interface Concept { coding?: Coding[]; text?: string }
export interface Quantity { value?: number; unit?: string }
export interface Extension {
url: string;
valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number;
valueDate?: string; valueDateTime?: string; valueCoding?: Coding; valueReference?: { reference?: string };
extension?: Extension[];
}
export interface Resource {
resourceType: string;
id?: string;
meta?: { tag?: Coding[] };
extension?: Extension[];
[field: string]: unknown;
}
export interface Bundle extends Resource {
total?: number;
entry?: { fullUrl?: string; resource: Resource; search?: { mode?: string } }[];
}
export const CODE_SYSTEM = 'https://isssteleon.org/fhir/CodeSystem/';
export function code(concept: Concept | undefined): string | undefined {
return concept?.coding?.[0]?.code;
}
export function display(concept: Concept | undefined): string | undefined {
return concept?.coding?.[0]?.display ?? concept?.text;
}
// The code of a concept from `system` (a name under the project's CodeSystem base, or a full URL).
export function codeIn(concept: Concept | undefined, system: string): string | undefined {
const url = system.includes('://') ? system : CODE_SYSTEM + system;
return concept?.coding?.find(c => c.system === url)?.code;
}
// The extensions named `name` (the last segment of their URL).
export function extensions(owner: { extension?: Extension[] } | undefined, name: string): Extension[] {
return (owner?.extension ?? []).filter(e => e.url === name || e.url.endsWith('/' + name));
}
export function extension(owner: { extension?: Extension[] } | undefined, name: string): Extension | undefined {
return extensions(owner, name)[0];
}
export function resources(bundle: Bundle | undefined, type?: string): Resource[] {
return (bundle?.entry ?? []).map(e => e.resource).filter(r => !type || r.resourceType === type);
}
export function isSimulated(resource: Resource): boolean {
return !!resource.meta?.tag?.some(t => t.code === 'simulado');
}
// `Patient/P-1` -> `P-1`.
export function referenceId(reference: { reference?: string } | undefined): string | undefined {
return reference?.reference?.split('/').pop();
}
@@ -3,6 +3,7 @@ import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { By } from '@angular/platform-browser';
import { MatSelect } from '@angular/material/select';
import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigureCard } from './indicador-figure-card';
import { IndicadorFigurePanel } from './indicador-figure-panel';
@@ -27,6 +28,7 @@ describe('UX-06E.D.2.1 selector de representación', () => {
fixture.componentRef.setInput('indicador', { id: 'i', titulo: 'I', contrato: 'C2', figuras, tipos_periodo: ['semestre'] });
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges();
}
function select() { return fixture.debugElement.query(By.directive(MatSelect)).componentInstance as MatSelect; }
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).filter(e => e.componentInstance.result().status !== 'deferred'); }
function request(id: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + id)); }
function open() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); }
@@ -45,9 +47,13 @@ describe('UX-06E.D.2.1 selector de representación', () => {
expect(fixture.componentInstance.indicador.contrato).toBe(contrato);
http.expectNone(() => true);
});
it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para consulta y memoria', () => {
it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para selector, consulta y memoria', () => {
fixture.destroy(); create(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c2_barras', 'fig_c2_donas', 'fig_c9_futura']);
fixture.componentRef.setInput('indicador', { ...fixture.componentInstance.indicador, contrato: 'C1' }); fixture.detectChanges();
expect(select().options.map(option => [option.value, option.viewValue])).toEqual([
['fig_c1_grupos', 'Grupos'], ['fig_c2_apiladas', 'Barras apiladas'],
['fig_c2_barras', 'Barras'], ['fig_c2_donas', 'Donas'], ['fig_c9_futura', 'Representación 5'],
]);
http.expectNone(() => true);
open(); request('fig_c1_grupos').flush({ data: [], layout: {} });
for (const [id, label] of [
@@ -56,7 +62,7 @@ describe('UX-06E.D.2.1 selector de representación', () => {
['fig_c2_donas', 'Donas'],
['fig_c9_futura', 'Representación 5'],
]) {
fixture.componentInstance.selectFigure(id); fixture.detectChanges();
select().selectionChange.emit({ source: select(), value: id }); fixture.detectChanges();
const pending = request(id);
expect(pending.request.url).toBe('/cacu/indicadores/i/figuras/' + id);
expect(pending.request.params.get('tema')).toBe('claro');
@@ -68,9 +74,9 @@ describe('UX-06E.D.2.1 selector de representación', () => {
}
http.expectNone(() => true);
});
it('no ofrece selector de representación y sólo consulta la figura mostrada', () => {
fixture.destroy(); create(['f', 'g']); open(); expect(fixture.nativeElement.querySelector('mat-select')).toBeNull();
request('f').flush({ data: [], layout: {} }); http.expectNone(() => true);
it('una opción publicada está deshabilitada y sólo consulta esa figura', () => {
fixture.destroy(); create(['f']); open(); expect(select().disabled).toBe(true);
expect(select().options.map(o => o.value)).toEqual(['f']); request('f').flush({ data: [], layout: {} }); http.expectNone(() => true);
});
it('comparte una sola solicitud de metadatos entre las dos figuras y asocia por ID exacto', () => {
fixture.componentRef.setInput('indicador', { id: 'cacu_eu13', titulo: 'EU13', contrato: 'C2',
@@ -92,8 +98,9 @@ describe('UX-06E.D.2.1 selector de representación', () => {
expect(cards.every(card => card.interpretation.every(line => line !== 'No debe asignarse.'))).toBe(true);
});
it('múltiples opciones habilitan el selector, mantienen una representación y cancelan cambios rápidos', () => {
open(); const first = request('f'); expect(panels()).toHaveLength(1);
fixture.componentInstance.selectFigure('g'); fixture.detectChanges();
open(); const first = request('f'); expect(select().disabled).toBe(false);
expect(select().options.map(o => o.value)).toEqual(['f', 'g']); expect(panels()).toHaveLength(1);
select().selectionChange.emit({ source: select(), value: 'g' }); fixture.detectChanges();
const next = request('g'); expect(first.cancelled).toBe(true); expect(panels()).toHaveLength(1);
expect(next.request.params.get('periodos')).toBe('2025-S1');
fixture.componentInstance.selectFigure('f'); fixture.detectChanges(); expect(next.cancelled).toBe(true);
@@ -2,6 +2,8 @@ import { ChangeDetectorRef, Component, effect, ElementRef, inject, Input, OnChan
import { catchError, of, Subscription } from 'rxjs';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
import { MatIconModule } from '@angular/material/icon';
import { Dominio, Indicador, IndicadorMetadatos, Tema } from './indicadores.models';
import { GlobalApplied, IndicadoresMemory } from './indicadores-memory';
@@ -23,7 +25,7 @@ import { parTiempos } from './indicadores-tiempos-pareados';
@Component({
selector: 'app-indicador-catalog-card',
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || !!tiempos' },
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia],
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia],
template: `
<mat-card>
<header>
@@ -51,6 +53,16 @@ import { parTiempos } from './indicadores-tiempos-pareados';
<app-indicador-tiempos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
</div>
} @else if (selectedFigure) {
@if (!pair.length || otherFigures.length) {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Representación gráfica</mat-label>
<mat-select [value]="selectedFigure" [disabled]="indicador.figuras.length === 1"
[attr.aria-label]="'Representación gráfica de ' + indicador.titulo" (selectionChange)="selectFigure($event.value)">
@if (pair.length) { <mat-option [value]="pair[0]">Dona y barras</mat-option> }
@for (figure of (pair.length ? otherFigures : indicador.figuras); track figure) { <mat-option [value]="figure">{{ figureDisplayName(figure, indicador.figuras) }}</mat-option> }
</mat-select>
</mat-form-field>
}
<div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual">
@for (figure of displayFigures; track panelIdentity(figure)) {
<div class="representation-panel">
@@ -124,6 +136,7 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
// Connected time pairs replace the diagnosis card with one coordinated box plot.
get tiempos() { return parTiempos(this.dominio, this.indicador.id); }
get otherFigures() { return this.indicador.figuras.filter(id => !this.pair.includes(id)); }
get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; }
private updateNumeric() {
@@ -83,23 +83,7 @@
</div>
</div>
}
@if (state.status === 'ready' && state.highlight; as h) {
<div class="highlight-legend" role="group" aria-label="Resaltar partes de la figura">
<p class="highlight-status" role="status" aria-live="polite">Selección: {{ highlightStatus }}</p>
<button type="button" class="highlight-back" (click)="highlightBack()" [disabled]="!highlightSelection.group && !highlightSelection.item">Volver</button>
@for (row of highlightRows(h); track row.group?.id ?? '') {
<div class="highlight-keys" role="group" [attr.aria-label]="row.group ? row.group.label + ' y sus categorías' : 'Categorías'">
@if (row.group; as g) {
<button type="button" class="highlight-group" [attr.aria-pressed]="highlightSelection.group === g.id" (click)="highlight('group', g.id)"><span class="legend-swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.label }}</button>
}
@for (c of row.items; track c.id) {
<button type="button" [attr.aria-pressed]="highlightSelection.item === c.id" [disabled]="!!highlightSelection.group && c.group !== highlightSelection.group"
[attr.aria-label]="c.short ? c.label : null" (click)="highlight('item', c.id)"><span class="legend-swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.short ?? c.label }}</button>
}
</div>
}
</div>
} @else if (state.status === 'ready' && state.donutLegend?.length) {
@if (state.status === 'ready' && state.donutLegend?.length) {
<div class="donut-static-legend" role="list" aria-label="Leyenda de la dona">
@for (entry of state.donutLegend; track entry.label) {
<span class="donut-static-legend__item" role="listitem">
@@ -110,7 +94,7 @@
}
</div>
<div class="plot-slot" [hidden]="state.status !== 'ready'">
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend || state.highlight ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ', ' + selected?.id + ', ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ', ' + selected?.id + ', ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
</div>
}
<div class="figure-footer" [hidden]="state.status !== 'ready'">
@@ -113,16 +113,3 @@
@media (prefers-reduced-motion: reduce) {
.donut-children-region, .donut-children-region.expanded { transition: none; transform: none; }
}
// Highlight buttons, as in CaCu's «Distribución de resultados citológicos».
.highlight-legend { display: grid; gap: .5rem; padding: .5rem .75rem .75rem; color: var(--issste-text); }
.dark .highlight-legend { color: #eef1f7; }
.highlight-status { margin: 0; font-weight: 600; }
.highlight-back { justify-self: start; }
.highlight-keys { display: flex; flex-wrap: wrap; gap: .5rem; }
.highlight-legend button { display: inline-flex; align-items: center; gap: .4rem; min-height: 36px; padding: .3rem .75rem; text-align: start;
overflow-wrap: anywhere; color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 999px; font: inherit; cursor: pointer; }
.highlight-legend button:disabled { opacity: .45; cursor: default; }
.highlight-legend button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
.highlight-legend button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
.highlight-legend .legend-swatch { border-radius: 50%; }
.highlight-legend .highlight-group { font-weight: 600; }
@@ -12,7 +12,6 @@ import { figureIdentity, identityElementId } from './indicadores-identities';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, HighlightSelection, toggleHighlight } from './indicadores-highlight';
// The panel owns requests; the card receives the original and its presentation copy.
export interface FigureState {
@@ -23,10 +22,6 @@ export interface FigureState {
categoryLabels?: readonly CategoryLabel[];
minimumPlotWidth?: number;
donutLegend?: readonly DonutLegendEntry[];
// The figure already lays out its own rings (C1 double donut): show the legend, keep the figure as is.
ownLayout?: boolean;
// Legend buttons that highlight one part of the figure (CaCu style).
highlight?: FigureHighlight;
plotWidth?: number;
plotHeight?: number;
message?: string;
@@ -69,7 +64,7 @@ export class IndicadorFigureCard implements OnChanges {
}
@Input({ required: true }) set state(value: FigureState) {
if (value.status !== 'ready' || value.figure !== this.currentState?.figure
|| JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; this.highlightSelection = {}; }
|| JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; }
this.currentState = value;
if (value.status === 'ready') {
this.updateDonut();
@@ -92,8 +87,7 @@ export class IndicadorFigureCard implements OnChanges {
? { ...presentationFigure, layout: { ...presentationFigure.layout, height: this.state.plotHeight } } : presentationFigure;
this.chartFigure = source && hierarchy
? donutView(source, hierarchy, this.activeParent, this.state.plotWidth)
: source && this.state.highlight ? highlightFigure(source, this.state.highlight, this.highlightSelection)
: source && this.state.donutLegend && !this.state.ownLayout ? donutSimpleView(source) : source;
: source && this.state.donutLegend ? donutSimpleView(source) : source;
}
expandParent(parent: string) {
if (this.state.status !== 'ready' || !this.state.hierarchy?.parents.includes(parent)
@@ -115,28 +109,9 @@ export class IndicadorFigureCard implements OnChanges {
target?.focus();
}
}
highlightSelection: HighlightSelection = {};
readonly highlightRows = highlightRows;
get highlightStatus() { return this.state.highlight ? highlightLabel(this.state.highlight, this.highlightSelection) : ''; }
highlight(kind: 'group' | 'item', id: string) {
if (!this.state.highlight) return;
this.highlightSelection = toggleHighlight(this.state.highlight, this.highlightSelection, kind, id);
this.updateDonut();
}
highlightBack() {
const sel = this.highlightSelection;
this.highlightSelection = sel.item && sel.group ? { group: sel.group } : {};
this.updateDonut();
}
plotClicked(event: unknown) {
if (!event || typeof event !== 'object' || !('points' in event) || !Array.isArray(event.points)) return;
const point = event.points[0];
if (this.state.highlight) {
const hit = typeof point?.curveNumber === 'number' && typeof point.pointNumber === 'number'
? highlightAt(this.state.highlight, { trace: point.curveNumber, index: point.pointNumber }) : undefined;
if (hit) this.highlight(hit.kind, hit.id);
return;
}
if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label);
else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label);
}
@@ -215,10 +215,10 @@ describe('IndicadorFigurePanel', () => {
expect(JSON.stringify(page.result().figure)).toBe(original);
expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno');
});
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita', () => {
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita o Todos', () => {
load(); figure().flush({ data: [], layout: {} });
const control = filters();
control.select([]);
control.changeMode('manual');
expect(control.canApply).toBe(false);
apply();
http.expectNone(req => req.url.includes('/figuras/'));
@@ -228,13 +228,18 @@ describe('IndicadorFigurePanel', () => {
expect(state?.applied?.selection.mode).toBe('todos');
apply();
const manual = figure();
expect(manual.request.params.get('periodos')).toBe('2025-S2');
expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2');
control.select([]);
expect(manual.cancelled).toBe(false);
expect(control.canApply).toBe(false);
apply();
http.expectNone(req => req.url.includes('/figuras/'));
manual.flush({ data: [], layout: {} });
control.changeMode('todos');
apply();
expect(manual.cancelled).toBe(true);
const all = figure();
expect(all.request.params.has('periodos')).toBe(false);
all.flush({ data: [], layout: {} });
});
it('UX-07B cambia perfil y restaura desde el original sin HTTP ni pérdida de host o revisión', () => {
load(); const received = { data: [{ y: [0, null], marker: { color: 'gray' } }], layout: { paper_bgcolor: 'white' }, future: 42 };
@@ -295,7 +300,7 @@ describe('IndicadorFigurePanel', () => {
});
it('mantiene resultado y referencia aplicada mientras se edita un borrador', () => {
load(); figure().flush({ data: [{ y: [0, null] }], layout: {} });
const control = filters(); control.select([]);
const control = filters(); control.changeMode('manual');
control.year = '2025'; control.unit = 'S1'; control.add();
fixture.detectChanges();
expect(page.result().figure?.data[0]['y']).toEqual([0, null]);
@@ -303,9 +308,9 @@ describe('IndicadorFigurePanel', () => {
expect(fixture.nativeElement.textContent).toContain('Filtro general aplicado: Todos con reporte');
http.expectNone(r => r.url.includes('/figuras/'));
});
it.each([{ periodos: ['2025-S1'] }])('404 de un periodo conserva borrador y reintenta la última aplicación', ({ periodos }) => {
it.each([{ periodos: ['2025-S1'] }, { periodos: ['2025-S1', '2025-S2'] }])('404 de conjunto conserva borrador y reintenta la última aplicación', ({ periodos }) => {
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
const control = filters(); control.select([]); control.year = '2025';
const control = filters(); control.changeMode('manual'); control.year = '2025';
for (const period of periodos) { control.unit = period.slice(-2); control.add(); }
apply();
const req = figure();
@@ -315,6 +320,7 @@ describe('IndicadorFigurePanel', () => {
expect(page.result().figure).toBeUndefined();
expect(page.result().message).toContain('esta selección');
expect(page.result().message).not.toContain('2025');
if (periodos.length > 1) expect(page.result().message).toContain('conjunto de periodos');
expect(control.selectedPeriods).toEqual(periodos);
control.select([]);
page.requestFigure();
@@ -327,7 +333,7 @@ describe('IndicadorFigurePanel', () => {
});
it('reintento y tema utilizan la selección aplicada aunque el borrador sea diferente', () => {
load(); figure().flush({ data: [], layout: {} });
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
apply(); figure().flush({ data: [{ y: [20] }], layout: {} });
control.unit = 'S2'; control.add();
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
@@ -338,17 +344,17 @@ describe('IndicadorFigurePanel', () => {
page.requestFigure();
const retry = figure(); expect(retry.request.params.get('periodos')).toBe('2025-S1');
retry.flush({ data: [], layout: {} });
expect(control.selectedPeriods).toEqual(['2025-S2']);
expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
});
it('descarta respuestas obsoletas de aplicaciones sucesivas', () => {
load(); figure().flush({ data: [], layout: {} });
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
apply(); const old = figure();
control.unit = 'S2'; control.add();
expect(old.cancelled).toBe(false);
apply(); const current = figure();
expect(old.cancelled).toBe(true);
expect(current.request.params.get('periodos')).toBe('2025-S2');
expect(current.request.params.get('periodos')).toBe('2025-S1,2025-S2');
current.flush({ data: [{ y: [12] }], layout: {} });
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
expect(page.result().figure?.data[0]['y']).toEqual([12]);
@@ -356,7 +362,7 @@ describe('IndicadorFigurePanel', () => {
it('UX-06E.B1 alterna ayuda sin HTTP y conserva filtros, borrador, memoria y panel', () => {
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
fixture.detectChanges();
const result = page.result(), filterState = state, snapshot = JSON.stringify(filterState);
const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance;
@@ -13,9 +13,6 @@ import { figureIdentity, identityElementId } from './indicadores-identities';
import { DonutHierarchy, DonutSelection, donutHierarchy, donutLegend, donutPeriod } from './indicadores-donut-drilldown';
import { IndicadoresSnapshots } from './indicadores-snapshots';
import { c2Capability, c2Figure } from './indicadores-c2-adapter';
import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2';
import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut';
import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones';
import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
import { c2GeneralSelection } from './indicadores-c2-general-selection';
@@ -248,26 +245,6 @@ export class IndicadorFigurePanel implements OnChanges {
const state = this.presentStratified(data); this.stratifiedData = data; return state;
}));
}
if (c1DonutCapability(this.indicador.contrato, selection.figura)) {
if (selection.tipoPeriodo !== 'semestre' || selection.periodos?.length !== 1)
return of({ status: 'incompatible', message: 'Esta figura muestra un solo semestre. Elige el intervalo semestral y un periodo.' } as FigureState);
return this.snapshots.datos(selection.dominio!, selection.indicador, 'semestre', selection.periodos, this.indicador.version, { estrato: C1_DONUT_ESTRATO }).pipe(map(data => {
const adapted = c1DonutFigure(data, selection);
if (adapted.status !== 'supported') return { status: 'incompatible', message: adapted.reason } as FigureState;
return { ...this.present(adapted.figure, selection), source: 'datos' as const, footnotes: adapted.notes,
highlight: adapted.highlight, ownLayout: true, plotHeight: selection.figura === C1_AGE_BARS ? 400 : undefined,
emptyMessage: adapted.total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined };
}));
}
if (c1AlterationCapability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) {
return this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo, selection.periodos, this.indicador.version).pipe(map(data => {
const adapted = c1AlterationFigure(data, selection);
if (adapted.status !== 'supported') return { status: 'incompatible', message: adapted.reason } as FigureState;
return { ...this.present(adapted.figure, selection), source: 'datos' as const, footnotes: adapted.notes,
highlight: adapted.highlight, ownLayout: true, plotHeight: 400,
emptyMessage: adapted.total === 0 ? 'Ningún niño tiene su primer EEG de buena calidad en la selección; no hay un porcentaje que representar.' : undefined };
}));
}
if (c2Capability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) {
// Both panels, KPI and numeric table share the exact same transport key.
// Do not catch /datos errors here: a backend failure is a real error state.
@@ -288,13 +265,6 @@ export class IndicadorFigurePanel implements OnChanges {
return this.publishedFigure(selection, 'Partición multiperiodo no verificable', data);
}
const adapted = c2Figure(data, selection);
if (adapted.status === 'supported' && selection.dominio === 'tea') {
const base = { source: 'datos' as const, footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage };
if (selection.figura === 'fig_c2_donas') {
const tea = teaC2Donut(adapted.model, selection.tema, adapted.figure.layout['title']);
if (tea) return of({ ...this.present(tea.figure, selection), ...base, highlight: tea.highlight, ownLayout: true });
} else return of({ ...this.present(adapted.figure, selection), ...base, highlight: c2BarsHighlight(adapted.model) });
}
return adapted.status === 'supported'
? of({ ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const,
footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage })
@@ -27,14 +27,9 @@ describe('KPI integración con autoridad global', () => {
if (!initial) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
http.expectOne('/' + domain + '/indicadores').flush(KPI_BY_DOMAIN[domain].slice(missing ? 1 : 0).map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] })));
flushPeriodos(() => periods.map(periodo => ({ tipo: 'semestre', periodo })));
for (const request of http.match(r => r.url.endsWith('/periodos'))) request.flush({ id: request.request.url.split('/').at(-2), periodos: periods.map(periodo => ({ tipo: 'semestre', periodo })) });
fixture.detectChanges();
}
// Availability runs four requests at a time; flushing one batch starts the next.
function flushPeriodos(periodos: () => unknown[]) {
for (let pending = http.match(r => r.url.endsWith('/periodos')); pending.length; pending = http.match(r => r.url.endsWith('/periodos')))
pending.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: periodos() }));
}
// Regression assertions below target the original KPI contracts. The added lab
// consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts.
// Satisfy its independent request with an explicit empty response, never diagnosis data.
@@ -61,7 +56,7 @@ describe('KPI integración con autoridad global', () => {
expect(panels().map(p => p.definition.id)).toEqual([]);
expect(panels().every(p => p.result().state === 'Esperando filtro aplicado')).toBe(true); http.expectNone(r => r.url.endsWith('/datos'));
});
it('TEA consulta sus cinco destacados y muestra conteo, porcentajes y mediana', () => {
it('TEA consulta sus tres destacados y muestra conteo, porcentaje y mediana', () => {
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); http.expectOne('/cacu/indicadores').flush([]);
load('tea'); const initial = requests();
expect(initial.map(r => r.request.url)).toEqual(['/tea/indicadores/' + KPI_BY_DOMAIN.tea[0].id + '/datos']);
@@ -69,10 +64,8 @@ describe('KPI integración con autoridad global', () => {
const req = requests();
expect(req.map(r => r.request.url)).toEqual(KPI_BY_DOMAIN.tea.slice(1).map(d => '/tea/indicadores/' + d.id + '/datos'));
req.forEach((r, i) => r.flush(response(i + 1, 'tea'))); fixture.detectChanges();
expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7], ['Disponible', '40.0'], ['Disponible', '40.0']]);
expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7]]);
expect(panels()[1].result().info).toContain('2 de 5 pacientes con nota médica con diagnóstico CIE-10 F84.0.');
expect(panels()[3].result().info).toBe('2 de 5 pacientes con diagnóstico confirmado tienen un EEG de buena calidad.');
expect(panels()[4].result().info).toBe('2 de 5 pacientes con diagnóstico confirmado no tienen todavía un EEG de buena calidad.');
});
it('dos KPI reales y un placeholder manejan 404, error y éxito sin cifras anteriores', () => {
load('cacu'); const req = requests(); expect(req).toHaveLength(2); expect(panels().every(p => p.result().loading)).toBe(true);
@@ -87,7 +80,7 @@ describe('KPI integración con autoridad global', () => {
it('borrador no consulta; aplicar equivalente tampoco; revisión distinta cancela las tres anteriores', () => {
load('cacu'); const initial = requests(); initial.forEach((r,i) => r.flush(response(i)));
const editor = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
editor.select([]); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
editor.changeMode('manual'); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(0);
expect(panels().map(p => p.result().value)).toEqual([5, 7]);
expect(single.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
@@ -171,7 +164,7 @@ describe('KPI integración con autoridad global', () => {
TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cacu');
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges();
http.expectOne('/cacu/indicadores').flush(KPI_BY_DOMAIN.cacu.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre'] })));
flushPeriodos(() => []); fixture.detectChanges();
http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [] })); fixture.detectChanges();
expect(panels()).toHaveLength(2); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true);
http.expectNone(r => r.url.endsWith('/datos'));
});
@@ -1,31 +1,45 @@
<section aria-label="Editor de filtros generales del proyecto">
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> }
@if (state.tipo === 'mes') { <p class="filter-help">Para consultar meses debes elegir periodos explícitos. Todos con reporte utiliza semestres.</p> }
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de tiempo del borrador ya no está publicado para este proyecto. Elige un intervalo de tiempo disponible.</p> }
<div class="fields">
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de análisis</mat-label>
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mensual' : 'Semestral' }}</mat-option> }
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
@for (period of options; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
@if (availability) {
@for (period of unavailableSelection; track period) { <mat-option [value]="period" disabled>{{ period }}, disponibilidad no confirmada</mat-option> }
}
</mat-select>
<mat-hint>{{ availability ? 'Existe reporte en al menos un indicador del dominio; la cobertura puede variar.' : 'Disponibilidad desconocida hasta consultar.' }}</mat-hint>
</mat-form-field>
@if (types.length > 1 || !types.includes(state.tipo)) {
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de tiempo</mat-label>
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mes' : 'Semestre' }}</mat-option> }
</mat-select>
</mat-form-field>
}
@if (state.tipo === 'semestre' && state.tipo === types[0]) {
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Modalidad</mat-label>
<mat-select [ngModel]="entry.draft.mode === 'todos' ? 'todos' : 'manual'" (ngModelChange)="changeMode($event)">
<mat-select-trigger><span class="select-value">{{ entry.draft.mode === 'todos' ? 'Todos con reporte' : 'Elegir periodos' }}</span></mat-select-trigger>
<mat-option value="todos">Todos con reporte</mat-option>
<mat-option value="manual">Elegir periodos</mat-option>
</mat-select>
</mat-form-field>
}
@if (entry.draft.mode !== 'todos') {
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodos seleccionados</mat-label>
<mat-select multiple [ngModel]="selectedPeriods" (ngModelChange)="select($event)">
<mat-select-trigger><span class="select-value">{{ selectedPeriods.join(', ') }}</span></mat-select-trigger>
@for (period of options; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
@if (availability) {
@for (period of unavailableSelection; track period) { <mat-option [value]="period" disabled>{{ period }}, disponibilidad no confirmada</mat-option> }
}
</mat-select>
<mat-hint>{{ availability ? 'Existe reporte en al menos un indicador del dominio; la cobertura puede variar.' : 'Disponibilidad desconocida hasta consultar.' }}</mat-hint>
</mat-form-field>
}
</div>
@if (availability) {
@if (availability.status === 'loading') { <p role="status">Consultando periodos disponibles…</p> }
@else if (availability.status === 'error') {
<p role="alert">No se pudo completar la consulta de periodos disponibles.</p>
<button type="button" mat-stroked-button (click)="retryAvailability.emit()">Reintentar disponibilidad</button>
} @else if (!options.length) { <p role="status">Sin reportes disponibles para este intervalo de análisis.</p> }
} @else if (!options.length) { <p role="status">Sin reportes disponibles para este intervalo de tiempo.</p> }
@if (entry.draft.mode === 'explicit' && unavailableSelection.length) { <p role="status">La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.</p> }
}
@if (!availability) {
@if (!availability && entry.draft.mode !== 'todos') {
<p class="filter-help">Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.</p>
<div class="fields period-builder">
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Año</mat-label><input matInput [(ngModel)]="year" inputmode="numeric" maxlength="4" /></mat-form-field>
@@ -44,7 +58,7 @@
}
@if (error) { <p class="error" role="alert">{{ error }}</p> }
<p class="draft-summary">Selección en edición: {{ summary }}</p>
@if (!canApply) { <p role="status">Selecciona un periodo válido para aplicar.</p> }
@if (!canApply) { <p role="status">Selecciona al menos un periodo válido para aplicar.</p> }
@if (!hasPending) { <p class="pending">Sin cambios pendientes.</p> }
@if (hasPending) { <p class="pending" role="status">Hay cambios sin aplicar.</p> }
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply || (!hasPending && !initialPresentation)" (click)="apply.emit()">Aplicar</button>
@@ -18,19 +18,18 @@ describe('UX-04 control asistido', () => {
control = fixture.componentInstance;
});
afterEach(() => fixture.destroy());
function periodSelect() {
return fixture.debugElement.queryAll(By.css('mat-form-field'))
.find(f => f.nativeElement.textContent.includes('Periodo seleccionado'))!.query(By.directive(MatSelect));
}
it('UX-06C: el trigger muestra el periodo explícito y el borrador vacío no se aplica', async () => {
it('UX-06C: valores largos del trigger preservan Todos, selección explícita y borrador vacío', async () => {
await fixture.whenStable(); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.select-value')?.textContent).toContain('Todos con reporte');
fixture.componentRef.setInput('state', {
...control.state, editors: { ...control.state.editors, semestre: {
added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S2'] },
added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] },
} },
});
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
const values = Array.from(fixture.nativeElement.querySelectorAll('.select-value') as NodeListOf<HTMLElement>);
expect(values.map(e => e.textContent)).toContain('2025-S2');
expect(values.map(e => e.textContent)).toContain('2025-S1, 2025-S2');
expect(values.map(e => e.textContent)).toContain('Elegir periodos');
fixture.componentRef.setInput('state', {
...control.state, editors: { ...control.state.editors, semestre: {
added: ['2025-S1', '2025-S2'], draft: { mode: 'empty' },
@@ -44,11 +43,10 @@ describe('UX-04 control asistido', () => {
it('UX-04A: el selector vacío no reescribe el FormControl en cada detección', async () => {
// Bound the pre-fix reproduction: do not wait for an unstable fixture forever.
fixture.changeDetectorRef.detach();
control.select([]);
control.changeMode('manual');
fixture.detectChanges();
await Promise.resolve();
const select = periodSelect();
expect(select.componentInstance.multiple).toBe(false);
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
const model = select.injector.get(NgModel);
const writes = vi.spyOn(model.control, 'setValue');
const edits = vi.spyOn(control.edited, 'emit');
@@ -56,16 +54,16 @@ describe('UX-04 control asistido', () => {
fixture.detectChanges();
await Promise.resolve();
}
expect(model.control.value).toBeNull();
expect(model.control.value).toEqual([]);
expect(writes).not.toHaveBeenCalled();
expect(edits).not.toHaveBeenCalled();
expect(control.state.applied?.selection.mode).toBe('todos');
});
it('UX-04A: meses vacíos se estabilizan al abrir y cerrar el selector', async () => {
it('UX-04A: meses vacíos se estabilizan al abrir y cerrar selección múltiple', async () => {
control.changeTipo('mes');
control.year = '2025'; control.unit = '01'; control.add(); control.select([]);
fixture.detectChanges(); await fixture.whenStable();
const select = periodSelect();
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
const model = select.injector.get(NgModel);
const writes = vi.spyOn(model.control, 'setValue');
for (let i = 0; i < 3; i++) {
@@ -80,7 +78,7 @@ describe('UX-04 control asistido', () => {
expect(control.canApply).toBe(false);
});
it('normaliza el año y rechaza agregar duplicados', () => {
control.select([]);
control.changeMode('manual');
control.year = '1'; control.unit = 'S1'; control.add();
expect(control.selectedPeriods).toEqual(['0001-S1']);
control.add();
@@ -88,7 +86,7 @@ describe('UX-04 control asistido', () => {
expect(control.entry.added).toEqual(['0001-S1']);
});
it.each([['0', 'S1'], ['10000', 'S1'], ['2025', 'S3'], ['abc', 'S1'], ['', 'S1']])('rechaza año/unidad %s %s', (year, unit) => {
control.select([]); control.year = year; control.unit = unit; control.add();
control.changeMode('manual'); control.year = year; control.unit = unit; control.add();
expect(control.error).toContain('unidad válida'); expect(control.canApply).toBe(false);
});
it.each(['00', '13', 'S1'])('rechaza unidad mensual %s', unit => {
@@ -96,22 +94,21 @@ describe('UX-04 control asistido', () => {
expect(control.entry.added).toEqual([]); expect(control.canApply).toBe(false);
});
it('conserva borradores independientes sin convertir periodos', () => {
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
control.changeTipo('mes'); control.year = '2026'; control.unit = '12'; control.add();
control.changeTipo('semestre'); expect(control.selectedPeriods).toEqual(['2025-S1']);
control.changeTipo('mes'); expect(control.selectedPeriods).toEqual(['2026-12']);
expect(control.state.applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' } });
});
it('un solo periodo: agregar otro lo reemplaza y varios se rechazan; elimina sin botones dentro de opciones', () => {
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
it('deselecciona sin eliminar opciones y elimina sin botones dentro de opciones', () => {
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
control.unit = 'S2'; control.add();
expect(control.selectedPeriods).toEqual(['2025-S2']);
control.select(['2025-S1', '2025-S2']); expect(control.selectedPeriods).toEqual(['2025-S2']);
control.select(['2025-S2']);
expect(control.entry.added).toEqual(['2025-S1', '2025-S2']);
control.remove('2025-S1'); expect(control.selectedPeriods).toEqual(['2025-S2']);
fixture.detectChanges();
const select = periodSelect();
expect(select.componentInstance.multiple).toBe(false);
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
expect(select).toBeTruthy();
expect(select.nativeElement.querySelector('button')).toBeNull();
expect(fixture.nativeElement.textContent).toContain('Eliminar 2025-S2');
fixture.nativeElement.querySelector('.remove button').click();
@@ -122,7 +119,7 @@ describe('UX-04 control asistido', () => {
it('emite edición y aplicación por separado y explica la disponibilidad desconocida', () => {
const edited = vi.spyOn(control.edited, 'emit');
const apply = vi.spyOn(control.apply, 'emit');
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
expect(edited).toHaveBeenCalledTimes(2); expect(apply).not.toHaveBeenCalled();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar');
@@ -131,25 +128,11 @@ describe('UX-04 control asistido', () => {
fixture.nativeElement.querySelector('button[mat-flat-button]').click();
expect(apply).toHaveBeenCalledTimes(1);
});
it('ofrece el intervalo de análisis mensual o semestral, sin Modalidad', async () => {
const labels = Array.from(fixture.nativeElement.querySelectorAll('mat-label') as NodeListOf<HTMLElement>).map(l => l.textContent);
expect(labels).toContain('Intervalo de análisis');
expect(labels).not.toContain('Modalidad');
const select = fixture.debugElement.queryAll(By.css('mat-form-field'))
.find(f => f.nativeElement.textContent.includes('Intervalo de análisis'))!.query(By.directive(MatSelect));
select.componentInstance.open(); fixture.detectChanges(); await fixture.whenStable();
const options = Array.from(document.querySelectorAll('mat-option')).map(o => o.textContent?.trim());
expect(options).toEqual(['Semestral', 'Mensual']);
select.componentInstance.close();
});
it('al cambiar de intervalo elige el periodo más reciente con reporte', () => {
fixture.componentRef.setInput('availability', { status: 'ready', byIndicator: {}, errors: {},
options: { semestre: ['2025-S2', '2025-S1'], mes: ['2025-12', '2025-11'] } });
fixture.detectChanges();
control.changeTipo('mes');
expect(control.selectedPeriods).toEqual(['2025-12']);
control.select(['2025-11']); control.changeTipo('semestre'); control.changeTipo('mes');
// A period already chosen for that interval is kept.
expect(control.selectedPeriods).toEqual(['2025-11']);
it('no ofrece Todos en meses cuando el primero es semestre', () => {
control.changeTipo('mes'); fixture.detectChanges();
expect(fixture.nativeElement.textContent).not.toContain('Todos los meses');
control.changeMode('todos'); expect(control.entry.draft.mode).toBe('empty');
control.changeTipo('semestre'); control.changeTipo('mes');
expect(control.entry.draft.mode).toBe('empty');
});
});
@@ -29,7 +29,7 @@ export class IndicadorPeriodFilters implements OnChanges {
ngOnChanges() { this.year = this.unit = this.error = ''; }
get entry() { return this.state.editors[this.state.tipo]!; }
// NgModel schedules a microtask and markForCheck when its input reference changes.
// Keep the empty selection stable so an unchanged draft can settle.
// Keep the empty multiple-select value stable so an unchanged draft can settle.
private readonly emptyPeriods: string[] = [];
get selectedPeriods() { return this.entry.draft.mode === 'explicit' ? this.entry.draft.periodos : this.emptyPeriods; }
get options() { return this.availability ? this.availability.options[this.state.tipo] : this.entry.added; }
@@ -42,21 +42,21 @@ export class IndicadorPeriodFilters implements OnChanges {
get hasPending() { return pending(this.state); }
get summary() { return describePeriods(this.state.tipo, this.entry.draft); }
get appliedSummary() { return this.state.applied ? describePeriods(this.state.applied.tipo, this.state.applied.selection) : 'Todavía no hay selección aplicada'; }
// There is no "every period" choice in the editor: a new interval starts on its most recent
// period with a report (options are sorted newest first).
changeTipo(tipo: TipoPeriodo) {
if (!this.types.includes(tipo)) return;
this.state.tipo = tipo;
this.state.editors[tipo] ??= newEditor(tipo, this.types[0]);
this.year = this.unit = this.error = '';
if (this.entry.draft.mode !== 'explicit' && this.availability?.status === 'ready' && this.options.length)
this.entry.draft = { mode: 'explicit', periodos: [this.options[0]] };
this.edited.emit();
}
// Only one period can be chosen: cards and figures never combine periods.
changeMode(mode: 'todos' | 'manual') {
if (mode === 'todos' && (this.state.tipo !== 'semestre' || this.state.tipo !== this.types[0])) return;
this.entry.draft = mode === 'todos' ? { mode: 'todos' } : { mode: 'empty' };
this.error = '';
this.edited.emit();
}
select(values: string[]) {
const unique = [...new Set(values)];
if (unique.length > 1) return;
if (unique.some(p => !this.options.includes(p) || parsePeriodos(p, this.state.tipo)?.[0] !== p)) return;
this.entry.draft = unique.length ? { mode: 'explicit', periodos: unique as [string, ...string[]] } : { mode: 'empty' };
this.edited.emit();
@@ -70,11 +70,13 @@ export class IndicadorPeriodFilters implements OnChanges {
return;
}
if (this.entry.added.includes(period)) { this.error = 'Este periodo ya está agregado.'; return; }
const selected = this.selectedPeriods;
this.entry.added.push(period);
this.select([period]);
this.select([...selected, period]);
}
remove(period: string) {
this.entry.added = this.entry.added.filter(p => p !== period);
// Removing an unselected option must not change the Todos mode.
if (this.entry.draft.mode === 'explicit') this.select(this.selectedPeriods.filter(p => p !== period));
else this.edited.emit();
}
@@ -1,63 +0,0 @@
import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones';
import { FigureSelection, IndicadorDatos } from './indicadores.models';
const fila = (grupo: string, numerador: number, denominador: number, extra: object = {}) => ({
periodo: '2025-S2', grupo, estrato: null, suprimido: 0, numerador, denominador, valor: 0, ic_bajo: null, ic_alto: null,
n_sin_evento: denominador - numerador, n_excluido: 0, ...extra,
});
const datos = (filas: Record<string, unknown>[] = [fila('TOTAL', 11, 20), fila('ritmo_posterior', 5, 20), fila('picos_paroxisticos', 0, 20)]): IndicadorDatos => ({
id: 'M30_resultado_eeg', titulo: 'Porcentaje de EEG normal y anormal', contrato: 'C1', unidad: 'paciente',
tipo_periodo: 'semestre', periodos: ['2025-S2'], estrato: null, valores_estrato: [],
grupos: { TOTAL: 'Total', ritmo_posterior: 'Ritmo posterior', picos_paroxisticos: 'Picos paroxísticos' },
grupos_de_categoria: {}, notas: ['Datos ficticios.'], filas,
});
const selection: FigureSelection = { dominio: 'tea', indicador: 'M30_resultado_eeg', figura: 'fig_c1_barras_alteracion', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] };
describe('Barras por alteración para C1', () => {
it('solo aplica a C1 con la figura por alteración', () => {
expect(c1AlterationCapability('C1', 'fig_c1_barras_alteracion')).toBe(true);
expect(c1AlterationCapability('C2', 'fig_c1_barras_alteracion')).toBe(false);
expect(c1AlterationCapability('C1', 'fig_c1_barras_edad')).toBe(false);
});
it('una barra por alteración tras la de alguna alteración, con su porcentaje y sus conteos', () => {
const result = c1AlterationFigure(datos(), selection);
if (result.status !== 'supported') throw new Error(result.reason);
const [trace] = result.figure.data as Record<string, unknown>[];
expect(result.figure.data.length).toBe(1);
expect(trace['x']).toEqual(['Alguna alteración', 'Ritmo posterior', 'Picos paroxísticos']);
expect(trace['y']).toEqual([55, 25, 0]);
expect(trace['text']).toEqual(['55.0 %', '25.0 %', '0.0 %']);
expect(trace['customdata']).toEqual([[11, 20], [5, 20], [0, 20]]);
expect(result.total).toBe(20);
expect(result.notes).toEqual(['Datos ficticios.']);
expect(result.highlight.items.map(i => i.id)).toEqual(['TOTAL', 'ritmo_posterior', 'picos_paroxisticos']);
expect((result.figure.layout['title'] as { text: string }).text).toBe('Porcentaje de EEG normal y anormal, 2025-S2');
});
it('varios periodos se dibujan lado a lado, uno por serie', () => {
const otro = (grupo: string, n: number, d: number) => fila(grupo, n, d, { periodo: '2025-S1' });
const data = { ...datos([otro('TOTAL', 2, 8), otro('ritmo_posterior', 1, 8), otro('picos_paroxisticos', 1, 8), ...datos().filas]), periodos: ['2025-S1', '2025-S2'] };
const result = c1AlterationFigure(data, { ...selection, periodos: ['2025-S1', '2025-S2'] });
if (result.status !== 'supported') throw new Error(result.reason);
const traces = result.figure.data as Record<string, unknown>[];
expect(traces.map(t => t['name'])).toEqual(['2025-S1', '2025-S2']);
expect(traces[0]['y']).toEqual([25, 12.5, 12.5]);
expect(result.figure.layout['showlegend']).toBe(true);
expect(result.total).toBe(28);
expect(result.highlight.items[1].points).toEqual([{ trace: 0, index: 1 }, { trace: 1, index: 1 }]);
});
it('un periodo sin niños con EEG bueno no dibuja ceros', () => {
const result = c1AlterationFigure(datos([fila('TOTAL', 0, 0), fila('ritmo_posterior', 0, 0), fila('picos_paroxisticos', 0, 0)]), selection);
if (result.status !== 'supported') throw new Error(result.reason);
expect((result.figure.data[0] as Record<string, unknown>)['y']).toEqual([null, null, null]);
expect(result.total).toBe(0);
});
it('rechaza datos que no son los grupos por alteración de la selección', () => {
expect(c1AlterationFigure({ ...datos(), grupos: { TOTAL: 'Total' } }, selection).status).toBe('unsupported');
expect(c1AlterationFigure({ ...datos(), estrato: 'grupo_edad' }, selection).status).toBe('unsupported');
expect(c1AlterationFigure(datos([fila('TOTAL', 11, 20), fila('ritmo_posterior', 5, 20)]), selection).status).toBe('unsupported');
expect(c1AlterationFigure(datos([fila('TOTAL', 11, 20), fila('ritmo_posterior', 25, 20), fila('picos_paroxisticos', 0, 20)]), selection).status).toBe('unsupported');
expect(c1AlterationFigure(datos([fila('TOTAL', 11, 20), fila('ritmo_posterior', 5, 20, { suprimido: 1 }), fila('picos_paroxisticos', 0, 20)]), selection).status).toBe('unsupported');
expect(c1AlterationFigure(datos(), { ...selection, periodos: ['2025-S1'] }).status).toBe('unsupported');
expect(c1AlterationFigure(datos(), { ...selection, figura: 'fig_c1_barras_edad' }).status).toBe('unsupported');
});
});
@@ -1,71 +0,0 @@
import { percentNumber } from './indicadores-format';
import { FigureHighlight } from './indicadores-highlight';
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
import { FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models';
// fig_c1_barras_alteracion: a C1 proportion whose groups are the alterations of the EEG. One bar per alteration with
// the share of the period's children that have it, after a first bar for the children with any of them (the TOTAL
// group). A child counts in every alteration it has, so the bars don't add up. Several periods draw side by side.
export const C1_ALTERATION_BARS = 'fig_c1_barras_alteracion';
const TOTAL = 'TOTAL';
const ANY_LABEL = 'Alguna alteración';
export type C1AlterationResult = { status: 'unsupported'; reason: string }
| { status: 'supported'; figure: PlotlyFigure; highlight: FigureHighlight; total: number; notes: string[] };
export function c1AlterationCapability(contract: string, representation: string): boolean {
return contract === 'C1' && representation === C1_ALTERATION_BARS;
}
const count = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// The any-alteration bar keeps the red of the event; each alteration takes its own colour.
const COLORS = [C2_PALETTE.series[1], ...C2_PALETTE.edades, C2_PALETTE.series[2], C2_PALETTE.series[3], C2_PALETTE.series[0]];
const color = (i: number) => COLORS[i % COLORS.length];
export function c1AlterationFigure(data: IndicadorDatos, selection: FigureSelection): C1AlterationResult {
const unsupported = (reason: string): C1AlterationResult => ({ status: 'unsupported', reason });
if (!c1AlterationCapability(data.contrato, selection.figura)) return unsupported('Representación no soportada');
if (data['estrato'] != null) return unsupported('Esta figura no admite una dimensión');
const periods = selection.periodos ? data.periodos.filter(p => selection.periodos!.includes(p)) : data.periodos;
if (!periods.length) return unsupported('No hay periodos publicados para esta selección');
const published = data['grupos'];
const groups = Object.entries(published && typeof published === 'object' ? published : {}).filter(([id]) => id !== TOTAL);
if (!groups.length) return unsupported('El indicador no publica grupos por alteración');
const bars = [{ id: TOTAL, label: ANY_LABEL }, ...groups.map(([id, label]) => ({ id, label: String(label) }))];
const cells = periods.map(period => bars.map(bar =>
data.filas.filter(r => r['periodo'] === period && r['grupo'] === bar.id && r['estrato'] == null)));
if (cells.some(row => row.some(found => found.length !== 1))) return unsupported('Grupos por alteración incompletos');
const rows = cells.map(row => row.map(([r]) => r));
if (rows.some(row => row.some(r => (r['suprimido'] !== 0 && r['suprimido'] !== false)
|| !count(r['numerador']) || !count(r['denominador']) || r['numerador'] > r['denominador'])))
return unsupported('Conteos por alteración suprimidos o no verificables');
const theme = c2Theme(selection.tema);
const x = bars.map(b => escape(b.label));
const single = periods.length === 1;
const traces = rows.map((row, p) => {
const y = row.map(r => (r['denominador'] as number) ? 100 * (r['numerador'] as number) / (r['denominador'] as number) : null);
return { type: 'bar', name: periods[p], x, y,
marker: { color: single ? bars.map((_, i) => color(i)) : color(p), line: { color: theme.background, width: 1 } },
text: y.map(v => v === null ? '' : percentNumber(v) + ' %'), textposition: 'outside', cliponaxis: false,
customdata: row.map(r => [r['numerador'], r['denominador']]),
hovertemplate: '%{x}' + (single ? '' : ', %{fullData.name}') + '<br>%{y:.1f} % (%{customdata[0]} de %{customdata[1]} niños)<extra></extra>' };
});
const figure: PlotlyFigure = {
data: traces,
layout: { autosize: true, height: 400, barmode: 'group', margin: { t: 56, l: 72, r: 24, b: single ? 64 : 96 }, showlegend: !single,
legend: { orientation: 'h', y: -0.3, itemclick: false, itemdoubleclick: false },
title: { text: escape(String(data['titulo'] ?? data.id)) + (single ? ', ' + periods[0] : '') },
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text },
xaxis: { type: 'category', title: { text: 'Alteración del EEG' }, automargin: true },
yaxis: { title: { text: '% de niños con EEG de buena calidad' }, range: [0, 100], ticksuffix: ' %', gridcolor: theme.grid, zeroline: false } },
config: { displayModeBar: false },
};
const highlight: FigureHighlight = { groups: [], traces: traces.map((_, t) => t), allLabel: 'Todas las alteraciones',
items: bars.map((b, i) => ({ id: b.id, label: b.label, color: single ? color(i) : theme.line,
points: traces.map((_, t) => ({ trace: t, index: i })) })) };
// Children with a first good EEG over the periods drawn: zero means there is nothing to draw a share of.
const total = rows.reduce((sum, row) => sum + (row[0]['denominador'] as number), 0);
return { status: 'supported', figure, highlight, total, notes: Array.isArray(data.notas) ? [...data.notas] : [] };
}
@@ -1,109 +0,0 @@
import { c1DonutCapability, c1DonutFigure, c1DonutLabels } from './indicadores-c1-donut';
import { FigureSelection, IndicadorDatos } from './indicadores.models';
const fila = (estrato: string, numerador: number, denominador: number, extra: object = {}) => ({
periodo: '2025-S2', grupo: 'TOTAL', estrato, suprimido: 0, numerador, denominador, valor: 0, ic_bajo: null, ic_alto: null,
n_sin_evento: denominador - numerador, n_excluido: 0, ...extra,
});
const datos = (filas = [fila('16-23', 16, 24), fila('24-29', 13, 18), fila('30-36', 17, 22)]): IndicadorDatos => ({
id: 'M21_diagnosticados_con_eeg', titulo: 'Porcentaje de pacientes con diagnóstico de TEA con EEG', contrato: 'C1', unidad: 'paciente',
tipo_periodo: 'semestre', periodos: ['2025-S2'], estrato: 'grupo_edad', valores_estrato: ['16-23', '24-29', '30-36'],
etiquetas_estrato: { '16-23': '16 a 23 meses', '24-29': '24 a 29 meses', '30-36': '30 a 36 meses' },
grupos: { TOTAL: 'Total' }, grupos_de_categoria: {}, notas: ['Datos ficticios.'], filas,
});
const selection: FigureSelection = { dominio: 'tea', indicador: 'M21_diagnosticados_con_eeg', figura: 'fig_c1_donas', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] };
describe('Dona de dos anillos para C1', () => {
it('solo aplica a C1 con las figuras por grupo de edad', () => {
expect(c1DonutCapability('C1', 'fig_c1_donas')).toBe(true);
expect(c1DonutCapability('C1', 'fig_c1_dona_edad')).toBe(true);
expect(c1DonutCapability('C1', 'fig_c1_barras_edad')).toBe(true);
expect(c1DonutCapability('C2', 'fig_c1_donas')).toBe(false);
expect(c1DonutCapability('C1', 'fig_c1_grupos')).toBe(false);
});
it('anillo interior con y sin el evento; exterior por grupo de edad, con el total al centro', () => {
const result = c1DonutFigure(datos(), selection);
expect(result.status).toBe('supported');
if (result.status !== 'supported') return;
const [center, inner, outer] = result.figure.data as { labels: string[]; values: number[]; text: string[] }[];
expect(center.text[0]).toContain('<b>64</b>');
expect(inner.labels).toEqual(['Con EEG', 'Sin EEG']);
expect(inner.values).toEqual([46, 18]);
expect(inner.text).toEqual(['Con EEG<br>71.9 %', 'Sin EEG<br>28.1 %']);
expect(outer.labels).toEqual(['Con EEG · 16 a 23 meses', 'Con EEG · 24 a 29 meses', 'Con EEG · 30 a 36 meses',
'Sin EEG · 16 a 23 meses', 'Sin EEG · 24 a 29 meses', 'Sin EEG · 30 a 36 meses']);
expect(outer.values).toEqual([16, 13, 17, 8, 5, 5]);
// Inside the outer ring only the age group; slices under 5 % stay unlabeled.
expect(outer.text[0]).toMatch(/^16 a 23 meses<br>/);
expect(outer.text[4]).toMatch(/^24 a 29 meses<br>7.8/);
const small = c1DonutFigure(datos([fila('16-23', 16, 24), fila('24-29', 13, 14), fila('30-36', 17, 40)]), selection);
if (small.status === 'supported') expect((small.figure.data[2] as { text: string[] }).text[4]).toBe('');
expect(result.total).toBe(64);
expect(result.notes).toEqual(['Datos ficticios.']);
expect(result.highlight.groups.map(g => g.label)).toEqual(['Con EEG', 'Sin EEG']);
expect(result.highlight.items.map(i => i.short)).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses', '16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
expect(result.highlight.groups[1].center).toBe('<b>18</b><br>Sin EEG');
expect(result.figure.layout['title']).toEqual({ text: 'Porcentaje de pacientes con diagnóstico de TEA con EEG, 2025-S2' });
});
it('dona por grupo de edad: solo los pacientes con el evento, con el porcentaje total al centro', () => {
const result = c1DonutFigure(datos(), { ...selection, figura: 'fig_c1_dona_edad' });
if (result.status !== 'supported') throw new Error(result.reason);
expect(result.figure.data).toHaveLength(1);
// Only the patients with EEG, by age group; each slice is its share of those 46 patients.
const [ring] = result.figure.data as { labels: string[]; values: number[]; text: string[] }[];
expect(ring.labels).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
expect(ring.values).toEqual([16, 13, 17]);
expect(ring.text[0]).toMatch(/^16 a 23 meses<br>34.8/);
expect((result.figure.layout['annotations'] as { text: string }[])[0].text).toBe('<b>71.9 %</b>');
expect(result.highlight.groups).toEqual([]);
expect(result.highlight.items.map(i => i.label)).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
expect(result.highlight.items[0].center).toBe('<b>34.8 %</b><br>16 a 23 meses');
});
it('cada grupo de edad tiene el mismo color en la dona de M21 y las barras de M22, sin verde ni rojo', () => {
const colores = ['#2F6DB3', '#E0A526', '#A23E8C'];
const dona = c1DonutFigure(datos(), { ...selection, figura: 'fig_c1_dona_edad' });
if (dona.status !== 'supported') throw new Error('sin figura');
expect((dona.figure.data[0] as { marker: { colors: string[] } }).marker.colors).toEqual(colores);
expect(dona.highlight.items.map(i => i.color)).toEqual(colores);
const barras = c1DonutFigure({ ...datos(), id: 'M22_diagnosticados_sin_eeg' }, { ...selection, indicador: 'M22_diagnosticados_sin_eeg', figura: 'fig_c1_barras_edad' });
if (barras.status !== 'supported') throw new Error('sin figura');
expect((barras.figure.data[0] as { marker: { color: string[] } }).marker.color).toEqual(colores);
expect(barras.highlight.items.map(i => i.color)).toEqual(colores);
});
it('barras apiladas por grupo de edad: confirmados y en proceso, con un botón por estado', () => {
const result = c1DonutFigure({ ...datos(), id: 'M24_confirmacion_diagnostico' }, { ...selection, indicador: 'M24_confirmacion_diagnostico', figura: 'fig_c1_barras_apiladas_edad' });
if (result.status !== 'supported') throw new Error('sin figura');
expect(result.figure.layout['barmode']).toBe('stack');
expect(result.figure.data.map(t => [t['name'], t['y']])).toEqual([['Diagnóstico confirmado', [16, 13, 17]], ['En proceso', [8, 5, 5]]]);
expect(result.figure.data[1]['text']).toEqual(['8 (33.3 %)', '5 (27.8 %)', '5 (22.7 %)']);
expect(result.highlight.items.map(i => i.label)).toEqual(['Diagnóstico confirmado', 'En proceso']);
});
it('barras por grupo de edad: una barra por grupo con su porcentaje', () => {
const result = c1DonutFigure({ ...datos([fila('16-23', 8, 24), fila('24-29', 5, 18), fila('30-36', 5, 22)]), id: 'M22_diagnosticados_sin_eeg' },
{ ...selection, indicador: 'M22_diagnosticados_sin_eeg', figura: 'fig_c1_barras_edad' });
if (result.status !== 'supported') throw new Error(result.reason);
const [bars] = result.figure.data as { type: string; x: string[]; y: number[]; text: string[] }[];
expect(bars.type).toBe('bar');
expect(bars.x).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
expect(bars.text).toEqual(['33.3 %', '27.8 %', '22.7 %']);
expect(JSON.stringify(result.figure.layout['yaxis'])).toContain('% de pacientes sin EEG');
expect(result.highlight.items.map(i => i.points)).toEqual([[{ trace: 0, index: 0 }], [{ trace: 0, index: 1 }], [{ trace: 0, index: 2 }]]);
});
it('usa etiquetas propias por indicador y neutrales para otros', () => {
expect(c1DonutLabels('M24_confirmacion_diagnostico')).toEqual(['Diagnóstico confirmado', 'En proceso']);
expect(c1DonutLabels('M22_diagnosticados_sin_eeg')).toEqual(['Sin EEG', 'Con EEG']);
expect(c1DonutLabels('otro')).toEqual(['Con el evento', 'Sin el evento']);
});
it('solo un semestre', () => {
expect(c1DonutFigure({ ...datos(), tipo_periodo: 'mes', periodos: ['2025-12'] }, { ...selection, tipoPeriodo: 'mes', periodos: ['2025-12'] }))
.toEqual({ status: 'unsupported', reason: 'Esta figura solo está disponible para un semestre.' });
expect(c1DonutFigure({ ...datos(), periodos: ['2025-S1', '2025-S2'] }, { ...selection, periodos: ['2025-S1', '2025-S2'] }).status).toBe('unsupported');
expect(c1DonutFigure(datos(), { ...selection, periodos: ['2025-S1'] }).status).toBe('unsupported');
});
it('rechaza estratos incompletos, suprimidos o imposibles', () => {
expect(c1DonutFigure({ ...datos(), estrato: null }, selection).status).toBe('unsupported');
expect(c1DonutFigure(datos([fila('16-23', 16, 24), fila('24-29', 13, 18)]), selection).status).toBe('unsupported');
expect(c1DonutFigure(datos([fila('16-23', 16, 24), fila('24-29', 13, 18), fila('30-36', null as unknown as number, 22, { suprimido: 1 })]), selection).status).toBe('unsupported');
expect(c1DonutFigure(datos([fila('16-23', 30, 24), fila('24-29', 13, 18), fila('30-36', 17, 22)]), selection).status).toBe('unsupported');
});
});
@@ -1,161 +0,0 @@
import { Categoria, dona, Grupo, Modelo } from './indicadores-eu7-escenario';
import { percentNumber, shareText } from './indicadores-format';
import { donaHighlight, FigureHighlight } from './indicadores-highlight';
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
import { FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models';
// Figures by age group for a C1 proportion over one semester, built from the age-stratified C1 rows:
// - fig_c1_donas: double donut drawn like CaCu's «Distribución de resultados citológicos»; the inner ring
// splits the denominator into patients with and without the event, the outer ring each of them by age group.
// - fig_c1_dona_edad: only the patients with the event, by age group, with the overall percentage in the centre.
// - fig_c1_barras_edad: one bar per age group with its percentage.
export const C1_DONUT = 'fig_c1_donas';
export const C1_RING = 'fig_c1_dona_edad';
export const C1_AGE_BARS = 'fig_c1_barras_edad';
export const C1_AGE_STACK = 'fig_c1_barras_apiladas_edad';
const C1_AGE_FIGURES = [C1_DONUT, C1_RING, C1_AGE_BARS, C1_AGE_STACK];
export const C1_DONUT_ESTRATO = 'grupo_edad';
// Mock (TEA): ring labels per indicator; any other C1 indicator falls back to a neutral wording.
const EVENT_LABELS: Readonly<Record<string, readonly [string, string]>> = {
M21_diagnosticados_con_eeg: ['Con EEG', 'Sin EEG'],
M22_diagnosticados_sin_eeg: ['Sin EEG', 'Con EEG'],
M24_confirmacion_diagnostico: ['Diagnóstico confirmado', 'En proceso'],
};
// Green for the event, red for its complement; age groups get lighter shades.
const RING_COLORS = [C2_PALETTE.series[0], C2_PALETTE.series[1]] as const;
// One colour per age group, the same in the donut (M21) and the bars (M22).
const ageColor = (i: number) => C2_PALETTE.edades[i % C2_PALETTE.edades.length];
export type C1DonutResult = { status: 'unsupported'; reason: string }
| { status: 'supported'; figure: PlotlyFigure; highlight: FigureHighlight; total: number; notes: string[] };
export function c1DonutCapability(contract: string, representation: string): boolean {
return contract === 'C1' && C1_AGE_FIGURES.includes(representation);
}
export function c1DonutLabels(indicador: string): readonly [string, string] {
return EVENT_LABELS[indicador] ?? ['Con el evento', 'Sin el evento'];
}
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const count = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
function shade(hex: string, step: number, steps: number): string {
const t = steps > 1 ? 0.65 * step / (steps - 1) : 0;
const rgb = [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16)).map(c => Math.round(c + (255 - c) * t));
return '#' + rgb.map(c => c.toString(16).padStart(2, '0')).join('').toUpperCase();
}
export function c1DonutFigure(data: IndicadorDatos, selection: FigureSelection): C1DonutResult {
const unsupported = (reason: string): C1DonutResult => ({ status: 'unsupported', reason });
if (!c1DonutCapability(data.contrato, selection.figura)) return unsupported('Representación no soportada');
if (selection.tipoPeriodo !== 'semestre' || data.tipo_periodo !== 'semestre') return unsupported('Esta figura solo está disponible para un semestre.');
if (data.periodos.length !== 1 || (selection.periodos && (selection.periodos.length !== 1 || selection.periodos[0] !== data.periodos[0])))
return unsupported('Se requiere un semestre único concordante');
const values = data['valores_estrato'], names = data['etiquetas_estrato'];
if (data['estrato'] !== C1_DONUT_ESTRATO || !Array.isArray(values) || !values.length || !values.every(v => typeof v === 'string')
|| new Set(values).size !== values.length || (names != null && !record(names))) return unsupported('Estratificación por grupo de edad no verificable');
const period = data.periodos[0];
const rows = values.map(v => data.filas.filter(r => r['periodo'] === period && r['estrato'] === v));
if (rows.some(r => r.length !== 1) || data.filas.length !== values.length) return unsupported('Partición por grupo de edad incompleta');
const strata = rows.map(([r], i) => ({ id: values[i] as string, label: typeof names?.[values[i]] === 'string' ? names[values[i]] as string : values[i] as string,
numerador: r['numerador'], denominador: r['denominador'], suprimido: r['suprimido'], grupo: r['grupo'] }));
if (strata.some(s => s.grupo !== 'TOTAL' || (s.suprimido !== 0 && s.suprimido !== false)
|| !count(s.numerador) || !count(s.denominador) || s.numerador > s.denominador)) return unsupported('Conteos por grupo de edad suprimidos o no verificables');
const labels = c1DonutLabels(data.id);
const notes = Array.isArray(data.notas) ? [...data.notas] : [];
const title = { text: escape(String(data['titulo'] ?? data.id)) + ', ' + period };
const total = strata.reduce((sum, s) => sum + (s.denominador as number), 0);
if (selection.figura === C1_AGE_STACK) {
const figure = ageStack(strata, labels, selection);
figure.layout = { ...figure.layout, title };
const highlight: FigureHighlight = { groups: [], traces: [0, 1], allLabel: 'Todos los pacientes',
items: labels.map((label, g) => ({ id: g ? 'SIN' : 'CON', label, color: RING_COLORS[g], points: strata.map((_, i) => ({ trace: g, index: i })) })) };
return { status: 'supported', figure, highlight, total, notes };
}
if (selection.figura === C1_AGE_BARS) {
const figure = ageBars(strata, labels[0], selection);
figure.layout = { ...figure.layout, title };
const highlight: FigureHighlight = { groups: [], traces: [0], allLabel: 'Todos los grupos de edad',
items: strata.map((s, i) => ({ id: s.id, label: s.label, color: ageColor(i), points: [{ trace: 0, index: i }] })) };
return { status: 'supported', figure, highlight, total, notes };
}
const grupos: Grupo[] = labels.map((etiqueta, g) => ({ id: g ? 'SIN' : 'CON', etiqueta, color: RING_COLORS[g] }));
const categorias: Categoria[] = [], celdas: Modelo['celdas'] = {};
grupos.forEach((g, gi) => strata.forEach((s, i) => {
const id = g.id + ':' + s.id, n = gi ? (s.denominador as number) - (s.numerador as number) : s.numerador as number;
// Unique labels: Plotly merges pie slices that share one.
categorias.push({ id, etiqueta: g.etiqueta + ' · ' + s.label, color: shade(g.color, i, strata.length), grupo: g.id });
celdas[id] = { n, estado: 'Publicado' };
}));
const modelo: Modelo = { periodo: period, categorias, grupos, celdas, total, sinDato: { n: 0, estado: 'Publicado' },
escenarios: [], vacio: total === 0, notas: notes, sinDatoEtiqueta: '' };
const figure = dona(modelo, {}, selection.tema);
if (figure.data.length === 3) {
const [, inner, outer] = figure.data as Record<string, unknown>[];
const hover = '%{label}<br>%{customdata[0]} pacientes, %{customdata[1]} % de ' + total + '<extra></extra>';
inner['hovertemplate'] = outer['hovertemplate'] = hover;
// Inside the outer ring the colour already tells the group: show only the age group and its share.
const outerValues = outer['values'] as number[];
outer['text'] = categorias.map((c, i) => outerValues[i] / total < .05 ? ''
: escape(strata[i % strata.length].label) + '<br>' + shareText(outerValues[i], total));
inner['text'] = grupos.map((g, i) => {
const n = (inner['values'] as number[])[i];
return n / total < .05 ? '' : escape(g.etiqueta) + '<br>' + percentNumber(100 * n / total) + ' %';
});
if (selection.figura === C1_RING) {
// Only the patients with the event, by age group, around the overall percentage of the event.
// Each slice is its age group's share of those patients.
const numerador = strata.reduce((sum, s) => sum + (s.numerador as number), 0);
const values = strata.map(s => s.numerador as number);
figure.data = [{ ...outer, hole: .6, values, labels: strata.map(s => escape(s.label)),
marker: { ...(outer['marker'] as object), colors: strata.map((_, i) => ageColor(i)) },
text: values.map((n, i) => !numerador || n / numerador < .05 ? '' : escape(strata[i].label) + '<br>' + shareText(n, numerador)),
customdata: values.map(n => [n, numerador ? percentNumber(100 * n / numerador) : '0']),
hovertemplate: '%{label}<br>%{customdata[0]} pacientes, %{customdata[1]} % de los ' + numerador + ' ' + escape(what(labels[0])) + '<extra></extra>' }];
figure.layout = { ...figure.layout, title, annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false,
text: '<b>' + percentNumber(100 * numerador / total) + ' %</b>', font: { size: 26, color: c2Theme(selection.tema).text } }] };
const highlight: FigureHighlight = { groups: [], traces: [0], center: { annotation: 0 }, allLabel: labels[0],
items: strata.map((s, i) => ({ id: s.id, label: s.label, color: ageColor(i), points: [{ trace: 0, index: i }],
center: '<b>' + (numerador ? percentNumber(100 * values[i] / numerador) : '0') + ' %</b><br>' + escape(s.label) })) };
return { status: 'supported', figure, highlight, total, notes };
}
}
figure.layout = { ...figure.layout, title };
// Next to its group's button, a category only needs its age group.
const highlight = donaHighlight(modelo, id => strata.find(s => id.endsWith(':' + s.id))?.label);
return { status: 'supported', figure, highlight, total, notes };
}
// "Con EEG" -> "con EEG", to follow «pacientes».
const what = (label: string) => label.charAt(0).toLowerCase() + label.slice(1);
// One stacked bar per age group: how many of its patients have the event and how many don't.
function ageStack(strata: readonly { label: string; numerador: unknown; denominador: unknown }[], labels: readonly [string, string], selection: FigureSelection): PlotlyFigure {
const theme = c2Theme(selection.tema);
const x = strata.map(s => escape(s.label));
const conEvento = strata.map(s => s.numerador as number), sinEvento = strata.map(s => (s.denominador as number) - (s.numerador as number));
return { data: [conEvento, sinEvento].map((y, g) => ({ type: 'bar', name: escape(labels[g]), x, y, marker: { color: RING_COLORS[g], line: { color: theme.background, width: 1 } },
text: y.map((n, i) => (strata[i].denominador as number) ? n + ' (' + percentNumber(100 * n / (strata[i].denominador as number)) + ' %)' : ''),
textposition: 'inside', insidetextanchor: 'middle', hovertemplate: '%{x}<br>%{fullData.name}: %{y} pacientes<extra></extra>' })),
layout: { autosize: true, height: 400, barmode: 'stack', margin: { t: 24, l: 72, r: 24, b: 80 }, showlegend: true,
legend: { orientation: 'h', y: -0.28, itemclick: false, itemdoubleclick: false },
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text },
xaxis: { type: 'category', title: { text: 'Grupo de edad' }, automargin: true },
yaxis: { title: { text: 'Pacientes' }, rangemode: 'tozero', gridcolor: theme.grid, zeroline: false } },
config: { displayModeBar: false } };
}
// One bar per age group: the share of its patients with the event.
function ageBars(strata: readonly { label: string; numerador: unknown; denominador: unknown }[], event: string, selection: FigureSelection): PlotlyFigure {
const theme = c2Theme(selection.tema);
const x = strata.map(s => escape(s.label));
const y = strata.map(s => (s.denominador as number) ? 100 * (s.numerador as number) / (s.denominador as number) : null);
return { data: [{ type: 'bar', x, y, marker: { color: strata.map((_, i) => ageColor(i)), line: { color: theme.background, width: 1 } },
text: y.map(v => v === null ? '' : percentNumber(v) + ' %'), textposition: 'outside', cliponaxis: false,
customdata: strata.map(s => [s.numerador, s.denominador]),
hovertemplate: '%{x}<br>%{y:.1f} % (%{customdata[0]} de %{customdata[1]} pacientes)<extra></extra>' }],
layout: { autosize: true, height: 400, margin: { t: 24, l: 72, r: 24, b: 64 }, showlegend: false,
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text },
xaxis: { type: 'category', title: { text: 'Grupo de edad' }, automargin: true },
yaxis: { title: { text: '% de pacientes ' + escape(what(event)) }, range: [0, 100], ticksuffix: ' %', gridcolor: theme.grid, zeroline: false } },
config: { displayModeBar: false } };
}
@@ -43,7 +43,7 @@ describe('C2: datos publicados a Plotly', () => {
const final = figurePresentation(result.figure, selection).figure, before = structuredClone(final);
const legend = donutLegend(final), view = donutSimpleView(final);
expect(legend).toEqual([
{ label: 'A', color: '#A8C243' }, { label: 'B', color: '#B8433A' }, { label: 'C', color: '#7184A2' },
{ label: 'A', color: '#7184A2' }, { label: 'B', color: '#A4B88A' }, { label: 'C', color: '#D0B778' },
]);
expect(view.layout).toMatchObject({ showlegend: false, height: 440, margin: { l: 16, r: 16, t: 16, b: 16, pad: 0 } });
expect(view.data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] });
@@ -161,12 +161,12 @@ describe('paleta C2 institucional y semántica', () => {
it.each(['claro','oscuro'] as const)('conserva colores publicados en %s y separa interfaz, series y estados', tema => {
const data = c2Fixture(); (data['categorias'] as Record<string, Record<string, unknown>>)['A']['color'] = '#D98E4A';
const figure = supported(data, { ...selection, tema }).figure;
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual(['#D98E4A', '#B8433A', '#7184A2']);
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual(['#D98E4A', '#A4B88A', '#D0B778']);
expect(figure.layout['paper_bgcolor']).toBe(C2_PALETTE[tema].background);
expect(figure.layout['font']).toMatchObject({ color: C2_PALETTE[tema].text });
expect(C2_PALETTE.states.noData).toBe('#C9CDD2'); expect(c2Color('#C9CDD2',0)).toBe('#C9CDD2');
expect(c2Color(undefined, 0)).toBe('#A8C243'); expect(c2Color(undefined, 1)).toBe('#B8433A');
expect(c2Color(undefined, 2)).toBe('#7184A2'); expect(c2Color(undefined, 3)).toBe('#D0B778');
expect(c2Color(undefined, 0)).toBe('#7184A2'); expect(c2Color(undefined, 1)).toBe('#A4B88A');
expect(c2Color(undefined, 2)).toBe('#D0B778'); expect(c2Color(undefined, 3)).toBe('#B78B8E');
expect(figure.config?.['responsive']).not.toBe(false); expect(figure.layout['width']).toBeUndefined();
});
it('mantiene contraste de texto legible y separadores suaves en ambos temas', () => {
@@ -19,7 +19,7 @@ describe('selección local segura de barras generales C2', () => {
it('grupo conserva hijos, etiquetas, orden, colores y unidad sin cambiar el denominador', () => {
const data = c2Fixture(), source = bars(data), before = structuredClone({ data, source });
const view = c2GeneralSelection(source, data, selection, local)!;
expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'], marker: { color: ['#B8433A', '#7184A2'] } });
expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'], marker: { color: ['#A4B88A', '#D0B778'] } });
expect(view.figure.layout['yaxis']).toMatchObject({ categoryarray: ['C', 'B'] });
expect(view.figure.layout['meta']).toMatchObject({ denominator: 10, period: local.period, unit: 'paciente' });
expect(view.context).toContain('G2, 2025-S2');
@@ -3,14 +3,10 @@ import { Tema } from './indicadores.models';
// Matches src/styles.scss: interface tokens are the source of these candidates,
// not a certified brand guide. Published semantic colours always take priority.
export const C2_PALETTE = Object.freeze({
// ISSSTELEON green and a brick red dark enough to stay apart from it with red-green colour blindness.
series: Object.freeze(['#A8C243', '#B8433A', '#7184A2', '#D0B778']),
// Age groups of the EEG indicators (M21, M22), which avoid the green and red of the rest.
edades: Object.freeze(['#2F6DB3', '#E0A526', '#A23E8C']),
series: Object.freeze(['#7184A2', '#A4B88A', '#D0B778', '#B78B8E']),
states: Object.freeze({ null: '#8A9199', noData: '#C9CDD2', suppressed: '#4B4949' }),
// line: the green for thin marks; the brand green itself is too light to read as a line on white.
claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1', line: '#6A8000' }),
oscuro: Object.freeze({ background: '#081839', text: '#FFFFFF', grid: '#53647F', outline: '#53647F', line: '#A8C243' }),
claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1' }),
oscuro: Object.freeze({ background: '#081839', text: '#FFFFFF', grid: '#53647F', outline: '#53647F' }),
});
export function c2Theme(tema: Tema) { return C2_PALETTE[tema]; }
export function c2Color(published: string | undefined, index: number): string {
@@ -59,18 +59,7 @@ describe('estrategia C2 /datos y respaldo /figuras', () => {
http.expectOne(r => r.url.includes('/figuras/')).flush({}, {status:503,statusText:'Failure'});
expect(fixture.componentInstance.result().status).toBe('error');
});
it('TEA: dona de un periodo con ambos anillos y botones para resaltar grupos y categorías', () => {
fixture.detectChanges(); dataRequest().flush(c2Fixture());
const result = fixture.componentInstance.result();
expect(result.status).toBe('ready');
expect(result.hierarchy).toBeUndefined();
expect(result.figure?.data.map(t => t['name'])).toEqual(['centro', 'grupos', 'categorias']);
expect(result.highlight?.groups.length).toBeGreaterThan(0);
expect(result.highlight?.items.every(i => i.group)).toBe(true);
});
it('cambio de periodo cancela lectura, limpia selección y no expone snapshot previo', () => {
// TEA draws single-period C2 donuts with highlight buttons instead (indicadores-tea-c2.ts).
fixture.componentRef.setInput('dominio', 'cama');
fixture.detectChanges(); const old = dataRequest();
fixture.componentRef.setInput('applied', { ...applied, revision:2,selection:{mode:'explicit',periodos:['2026-S1']} }); fixture.detectChanges();
expect(old.cancelled).toBe(true); const current = dataRequest(); expect(current.request.params.get('periodos')).toBe('2026-S1');
@@ -96,17 +96,17 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', (
expect(card('cacu_eu13')).toBeDefined();
http.expectNone(() => true);
});
it('EU7 primero sin alterar catálogo; selección y fijación prevalecen y conservan identidades y memoria', () => {
it('EU7 primero sin alterar catálogo; búsqueda y fijación prevalecen y conservan identidades y memoria', () => {
const original = page.catalog(), before = cards();
expect(original.map(i => i.id)).toEqual(catalog.map(i => i.id));
expect(before[0].indicador.id).toBe('cacu_eu7');
page.togglePinned(original[0]); fixture.detectChanges();
expect(cards()[0]).toBe(card('cacu_eu13'));
page.changeIndicatorSelection(['ind1', 'cacu_eu13']); fixture.detectChanges();
expect(cards().map(c => c.indicador.id)).toEqual(['cacu_eu13', 'ind1']);
for (const id of ['ind1', 'cacu_eu13']) expect(card(id)).toBe(before.find(c => c.indicador.id === id));
page.showAllIndicators(); fixture.detectChanges();
page.changeSearchQuery('anómala'); fixture.detectChanges();
expect(cards()[0].indicador.id).toBe('ind1');
page.changeSearchQuery(''); fixture.detectChanges();
expect(cards()[0].indicador.id).toBe('cacu_eu13');
for (const c of before) expect(card(c.indicador.id)).toBe(c);
expect(page.catalog()).toBe(original);
expect(TestBed.inject(IndicadoresMemory).isPinned('cacu', 'cacu_eu13')).toBe(true);
http.expectNone(() => true);
@@ -176,8 +176,6 @@ describe('navegación multiperiodo en el panel común', () => {
expect(JSON.stringify(source)).toBe(before); http.expectNone(() => true);
});
it('un periodo no presenta navegación y una selección vacía es incompatible sin HTTP', () => {
// TEA draws single-period C2 donuts with highlight buttons instead (indicadores-tea-c2.ts).
fixture.componentRef.setInput('dominio', 'cama');
apply([periods[0]]); dataRequest().flush(c2Fixture()); fixture.detectChanges();
expect(buttons()).toHaveLength(0); expect(card().state.hierarchy).toBeTruthy();
apply([], 2); fixture.detectChanges(); expect(panel().result().status).toBe('incompatible'); expect(buttons()).toHaveLength(0); http.expectNone(() => true);
File diff suppressed because one or more lines are too long
@@ -1,208 +0,0 @@
// What this module covers: the indicator page and TEA's follow-up over the WebApi's FHIR endpoint. The catalog and
// technical sheet from `Measure`, the data rows from `MeasureReport`, the periods from two one-report searches, the
// C3r box plot, and the follow-up list and patient summary from `EpisodeOfCare` and `$resumen-tea`; each mapped into
// the shapes the page reads and passed through the same checks.
// Fixtures: `indicadores-fhir.fixtures.ts`, real responses of the WebApi over its TEA fixture database.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { firstValueFrom } from 'rxjs';
import { Bundle, resources } from './fhir';
import {
cajaDeDatos, datosDeReportes, FhirIndicadoresPeriodos, FhirIndicadoresService, indicadorDeMeasure, Measure, periodoIniciado,
periodosDesde, Report,
} from './indicadores-fhir';
import * as fx from './indicadores-fhir.fixtures';
import { c1AlterationFigure } from './indicadores-c1-alteraciones';
import { c2Figure } from './indicadores-c2-adapter';
import { datosValidos } from './indicadores.service';
import { FhirTeaSeguimientoService, mapaDeElectrodos } from './tea-seguimiento-fhir';
import { IndicadorDatos } from './indicadores.models';
const measure = (id: string) => resources(fx.measures).find(m => m.id === id) as Measure;
const reports = (bundle: Bundle) => resources(bundle, 'MeasureReport') as Report[];
describe('Indicadores sobre FHIR', () => {
it('el catálogo sale de cada Measure con los ids, contratos, figuras y estratos de la página', () => {
// Pins down: ids with underscores, the contract and figures from the extensions, the age stratum of a C1 and none
// for a C2 (its stratifier holds the categories). Fails if the catalog stops matching the page's TEA ids.
const catalog = resources(fx.measures).map(m => indicadorDeMeasure(m as Measure));
const m21 = catalog.find(i => i.id === 'M21_diagnosticados_con_eeg')!;
expect(m21).toMatchObject({ contrato: 'C1', figuras: ['fig_c1_barras_edad'], tipos_periodo: ['semestre', 'mes'], estratos: ['grupo_edad'], sentido: 'mayor_mejor' });
expect(catalog.find(i => i.id === 'M28_casos_por_estado')).toMatchObject({ contrato: 'C2', estratos: [] });
expect(catalog.find(i => i.id === 'M25_dias_mchat_diagnostico')).toMatchObject({ contrato: 'C3r', sentido: 'menor_mejor' });
});
it('los grupos de M30 llegan como filas por alteración y dibujan sus barras', () => {
// Pins down: a report's extra groups become one row each under the group's code, labelled by the Measure, and
// that is what `fig_c1_barras_alteracion` draws. The report is written here in the WebApi's shape (the fixtures
// hold none for M30). Fails if the groups are dropped or renamed on the way, or the figure stops reading them.
const m30 = measure('M30-resultado-eeg');
const pop = (code: string, count: number) => ({ code: { coding: [{ code }] }, count });
const group = (code: string, n: number) => ({ code: { coding: [{ code }] }, population: [pop('denominator', 8), pop('numerator', n)],
measureScore: { value: n / 8 } });
const codes = (m30.group ?? []).map(g => g.code?.coding?.[0]?.code as string);
const report = { resourceType: 'MeasureReport', id: 'M30-resultado-eeg-1', period: { start: '2025-07-01', end: '2025-12-31' },
group: codes.map((c, i) => group(c, c === 'TOTAL' ? 4 : i % 3)) } as unknown as Report;
const datos = datosValidos(datosDeReportes(m30, [report], 'semestre'), 'M30_resultado_eeg', 'semestre', ['2025-S2']);
expect(datos.filas.map(f => f['grupo'])).toEqual(codes);
expect(codes).toContain('ritmo_posterior');
const result = c1AlterationFigure(datos, { dominio: 'tea', indicador: 'M30_resultado_eeg', figura: 'fig_c1_barras_alteracion',
tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] });
if (result.status !== 'supported') throw new Error(result.reason);
const [trace] = result.figure.data as Record<string, unknown>[];
expect(trace['x']).toEqual(['Alguna alteración', 'Ritmo posterior', 'Husos de sueño N2', 'Husos de sueño N3', 'Picos paroxísticos',
'Gradiente anteroposterior']);
expect((trace['y'] as number[])[0]).toBe(50);
});
it('una proporción da numerador, denominador y porcentaje, y por grupo de edad los códigos de la página', () => {
// Pins down: the score becomes a percentage, the age groups `16-23`..., and an empty «Sin dato» stratum is left
// out. Fails if the fraction isn't multiplied, the codes keep FHIR's underscore or the empty stratum becomes a bar.
const total = datosValidos(datosDeReportes(measure('M21-diagnosticados-con-eeg'), reports(fx.m21Semestres), 'semestre'),
'M21_diagnosticados_con_eeg', 'semestre');
expect(total.periodos).toEqual(['2025-S1', '2025-S2']);
expect(total.filas[0]).toMatchObject({ periodo: '2025-S1', grupo: 'TOTAL', estrato: null, numerador: 2, denominador: 2, valor: 100, suprimido: 0 });
const porEdad = datosDeReportes(measure('M21-diagnosticados-con-eeg'), reports(fx.m21Semestres), 'semestre', { estrato: 'grupo_edad' });
expect(porEdad['valores_estrato']).toEqual(['16-23', '24-29', '30-36']);
expect((porEdad['etiquetas_estrato'] as Record<string, string>)['16-23']).toBe('16 a 23 meses');
});
it('una exclusión del denominador llega como n_excluido', () => {
// Pins down: M24's neuropediatrics notes without F84.0 are counted apart. Fails if the exclusion is dropped.
const datos = datosDeReportes(measure('M24-confirmacion-diagnostico'), reports(fx.m24Semestres), 'semestre');
expect(datos.filas[0]).toMatchObject({ numerador: 2, denominador: 5, valor: 40, n_excluido: 1 });
});
it('una composición da todas sus categorías, también las de cero, y la página la dibuja', () => {
// Pins down: one row per category of the Measure, in its order, with zeros for the absent ones, so the C2 adapter
// accepts the partition. Fails if a category with no patients is left out (the page refuses an incomplete one).
const datos = datosDeReportes(measure('M29-calidad-eeg'), reports(fx.m29Semestres), 'semestre');
const s1 = datos.filas.filter(f => f['periodo'] === '2025-S1');
expect(s1.map(f => [f['categoria'], f['n']])).toEqual([['BUENO', 2], ['MALO', 1], ['SIN_ANALIZAR', 0]]);
const m28 = datosDeReportes(measure('M28-casos-por-estado'), [reports(fx.m28Semestres)[0]], 'semestre');
const figure = c2Figure(m28, { indicador: 'M28_casos_por_estado', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', dominio: 'tea' });
expect(figure.status).toBe('supported');
});
it('una duración da mediana, cuartiles y unidad en días, y su caja por periodo', () => {
// Pins down: the median and quartile extensions, `dias` (what the KPI card requires) and the box plot built here
// instead of by the server. Fails if the quartiles are lost or the box plot stops having one box per period.
const datos = datosDeReportes(measure('M25-dias-mchat-diagnostico'), reports(fx.m25Semestres), 'semestre');
expect(datos.filas[0]).toMatchObject({ mediana: 59.5, q1: 58.75, q3: 60.25, n: 2, n_sin_evento: 4, unidad: 'dias' });
const caja = cajaDeDatos(datos as IndicadorDatos);
expect(caja.data[0]).toMatchObject({ type: 'box', median: datos.filas.filter(f => f['mediana'] !== null).map(f => f['mediana']) });
});
it('los periodos siguen al primero sin huecos y los que no han empezado se descartan', () => {
// Pins down: semesters and months counted on from the first report, and none after today. Fails if a year
// boundary is crossed wrongly or a future period is offered.
expect(periodosDesde('2024-07-01', 'semestre', 3)).toEqual(['2024-S2', '2025-S1', '2025-S2']);
expect(periodosDesde('2024-11-01', 'mes', 3)).toEqual(['2024-11', '2024-12', '2025-01']);
const today = new Date(2025, 9, 15);
expect(periodoIniciado('2025-S2', today)).toBe(true);
expect(periodoIniciado('2025-11', today)).toBe(false);
});
});
describe('Servicios FHIR de indicadores', () => {
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), FhirIndicadoresService, FhirIndicadoresPeriodos] });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
it('pide los periodos elegidos de una medida a la búsqueda de MeasureReport', async () => {
// Pins down: one `Measure` list per domain, and `/MeasureReport?measure=<canonical>&periodo=...`. Fails if the
// request leaves the FHIR endpoint or loses the periods asked for.
const service = TestBed.inject(FhirIndicadoresService);
const answer = firstValueFrom(service.datos('tea', 'M21_diagnosticados_con_eeg', 'semestre', ['2025-S1', '2025-S2']));
http.expectOne('/tea/fhir/Measure').flush(fx.measures);
const request = http.expectOne(r => r.url === '/tea/fhir/MeasureReport');
expect(request.request.params.get('measure')).toBe('https://isssteleon.org/fhir/Measure/M21-diagnosticados-con-eeg');
expect(request.request.params.get('periodo')).toBe('2025-S1,2025-S2');
request.flush(fx.m21Semestres);
expect((await answer).filas.length).toBe(2);
});
it('el inventario de periodos sale de dos búsquedas de un solo reporte', async () => {
// Pins down: one report of each type and the search's total, shared by every measure of the domain. Fails if each
// measure computes its own periods or every period is evaluated to list them.
const periodos = TestBed.inject(FhirIndicadoresPeriodos);
periodos.today = () => new Date(2025, 11, 31);
const answer = firstValueFrom(periodos.periodos('tea', 'M28_casos_por_estado'));
http.expectOne('/tea/fhir/Measure').flush(fx.measures);
const semestres = http.expectOne(r => r.params.get('tipo-periodo') === 'semestre');
expect(semestres.request.params.get('_count')).toBe('1');
semestres.flush({ ...fx.m28Semestres, entry: fx.m28Semestres.entry!.slice(0, 1) });
const first = reports(fx.m28Semestres)[0];
http.expectOne(r => r.params.get('tipo-periodo') === 'mes').flush({ resourceType: 'Bundle', total: 12,
entry: [{ resource: { ...first, period: { start: '2025-01-01', end: '2025-01-31' } } }] });
const found = await answer;
expect(found.filter(p => p.tipo === 'semestre').map(p => p.periodo)).toEqual(['2025-S2', '2025-S1']);
expect(found.filter(p => p.tipo === 'mes').length).toBe(12);
expect(await firstValueFrom(periodos.periodos('tea', 'M21_diagnosticados_con_eeg'))).toEqual(found);
});
});
describe('Seguimiento de TEA sobre FHIR', () => {
let http: HttpTestingController;
let service: FhirTeaSeguimientoService;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), FhirTeaSeguimientoService] });
http = TestBed.inject(HttpTestingController);
service = TestBed.inject(FhirTeaSeguimientoService);
});
afterEach(() => http.verify());
it('la lista sale de los episodios con sus recursos incluidos y respeta filtros y página', async () => {
// Pins down: the window and cut-off as `date`, the filters as search parameters, paging as `_count`/`_offset`,
// and each row's age group, M-CHAT, ADOS-2, study EEG and alterations from the included resources. Fails if a
// filter is dropped or a column stops coming from its resource.
const answer = firstValueFrom(service.consultar({ corte: '2025-12-31', meses: 12, page: 1, page_size: 5, grupo_edad: '16-23 meses', estado_caso: 'completo' }));
const list = http.expectOne(r => r.url === '/tea/fhir/EpisodeOfCare');
expect(list.request.params.getAll('date')).toEqual(['ge2025-01-01', 'le2025-12-31']);
expect(list.request.params.get('grupo-edad')).toBe('16_23');
expect(list.request.params.get('status')).toBe('finished');
expect(list.request.params.get('_count')).toBe('5');
list.flush(fx.episodios);
http.expectOne(r => r.url === '/tea/fhir/EpisodeOfCare/$resumen-eeg').flush(fx.resumenEeg);
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
const response = await answer;
expect(response.paginacion).toEqual({ page: 1, page_size: 5, total_items: 6, total_pages: 2 });
expect(response.items[0]).toMatchObject({ id_seudonimo: 'P-4A59E9D8B4', grupo_edad: '16-23 meses', ultimo_eeg: '2025-05-20', mchat: 12,
css_ados2: 7, modulo_ados2: '1', estado_caso: 'completo', alteraciones_eeg: 'anormal', alteraciones: ['ritmo_posterior'], pendientes: [] });
expect(response.resumen_eeg).toMatchObject({ normales: 2, anormales: 1, sin_eeg: 3 });
expect(response.tipos_alteracion.map(t => t.codigo)).toContain('ritmo_posterior');
});
it('el resumen del paciente arma el ADOS-2, la calidad, las alteraciones y su mapa', async () => {
// Pins down: ADOS-2 domains whose totals add up (the page checks it), quality criteria in channels or dB, each
// metric's state and effects from the code system, and one map per evaluable metric from its electrodes. Fails if
// the summary stops passing the page's checks or a map appears for a metric without electrodes.
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente);
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
const detalle = await answer;
expect(detalle.grupo_edad).toBe('16-23 meses');
expect(detalle.ados2).toMatchObject({ modulo: '1', css: 7, clasificacion: 'autismo', nivel_css: 'moderado' });
expect(detalle.eeg!.calidad).toBe('bueno');
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'linea')).toMatchObject({ valor: 3.5, unidad: 'dB' });
const ritmo = detalle.eeg!.alteraciones.find(a => a.codigo === 'ritmo_posterior')!;
expect(ritmo).toMatchObject({ estado: 'disminuido', valor_z: -4.08 });
expect(ritmo.efectos).toContain('Ritmo más lento de lo esperado para la edad.');
expect(detalle.eeg!.mapas.map(m => m.codigo)).toEqual(['ritmo_posterior']);
});
it('el mapa toma el valor de cada electrodo y deja en blanco lo que ninguno alcanza', () => {
// Pins down: the electrode's own z at its position, regions averaged from the measured electrodes only, and no
// value far from every electrode. Fails if the map paints the whole head from a few occipital electrodes.
const mapa = mapaDeElectrodos('ritmo_posterior', 'Ritmo posterior', { O1: -2.8, O2: -2.4, Pz: -1.1 });
const eje = Array.from({ length: 41 }, (_, i) => Math.round((-1 + i * .05) * 100) / 100);
expect(mapa.z[eje.indexOf(-0.75)][eje.indexOf(-0.25)]).not.toBeNull();
expect(mapa.z[eje.indexOf(0.75)][eje.indexOf(0)]).toBeNull();
expect(mapa.regiones.map(r => r.codigo)).toEqual(['occipital', 'parietal']);
expect(mapa.regiones[0].valor_z).toBe(-2.6);
});
});
@@ -1,325 +0,0 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map, Observable, shareReplay, switchMap } from 'rxjs';
import { Bundle, code, Concept, display, extension, extensions, Extension, Resource, resources } from './fhir';
import { periodLabel } from './measure-report';
import {
DatosScope, Dominio, FigureSelection, Indicador, IndicadorDatos, IndicadorMetadatos, PlotlyFigure, requireDominio, TipoPeriodo,
} from './indicadores.models';
import { catalogoValido, datosParams, datosValidos, figuraPeriodos, figuraValida, IndicadoresService, metadatosValidos } from './indicadores.service';
import { AvailablePeriod, IndicadoresPeriodos, periodOrder } from './indicadores-periodos';
import { IndicadoresRequests } from './indicadores-requests';
// The indicator page over the WebApi's FHIR endpoint (`/<domain>/fhir/`): `Measure` for the catalog and the technical
// sheet, `MeasureReport` for the data rows. Everything is mapped into the shapes the page already reads, and checked
// by the same rules as before.
interface Population { code?: Concept; count?: number; description?: string; criteria?: { expression?: string } }
interface Score { value?: number; unit?: string; extension?: Extension[] }
interface Stratum { value?: Concept; population?: Population[]; measureScore?: Score; component?: { code?: Concept; value?: Concept }[] }
interface Stratifier { code?: Concept[] | Concept }
interface ReportStratifier { code?: Concept[]; stratum?: Stratum[] }
interface Group { code?: Concept; population?: Population[]; measureScore?: Score; stratifier?: (Stratifier & ReportStratifier)[] }
export interface Measure extends Resource {
url?: string; version?: string; name?: string; title?: string; description?: string;
scoring?: Concept; subjectCodeableConcept?: Concept; improvementNotation?: Concept; group?: Group[];
}
export interface Report extends Resource {
measure?: string; date?: string; period?: { start: string; end: string }; group?: Group[];
}
interface Categoria { etiqueta: string; color: string | null; grupo: null }
const MAX_COUNT = 200;
const POPULATION_GROUP: Record<string, string> = {
'initial-population': 'poblacion', denominator: 'denominador', numerator: 'numerador',
'denominator-exclusion': 'exclusion', 'measure-population-exclusion': 'exclusion', 'measure-observation': 'observacion',
};
// `M21-diagnosticados-con-eeg` <-> `M21_diagnosticados_con_eeg`, the ids the page and its TEA texts use.
export const indicadorId = (measureId: string) => measureId.replace(/-/g, '_');
const stratifierCode = (s: Stratifier) => code(Array.isArray(s.code) ? s.code[0] : s.code);
// Age groups travel as `16_23`; the page names them `16-23`.
export const estratoValor = (value: string) => /^\d+_\d+$/.test(value) ? value.replace('_', '-') : value;
function count(populations: Population[] | undefined, name: string): number | null {
const found = populations?.find(p => code(p.code) === name);
return found && Number.isSafeInteger(found.count) ? found.count! : null;
}
function decimal(score: Score | undefined, name: string): number | null {
const value = extension(score, name)?.valueDecimal;
return typeof value === 'number' ? value : null;
}
const round1 = (value: number) => Math.round(value * 10) / 10;
export function categorias(measure: Measure): Record<string, Categoria> {
return Object.fromEntries(extensions(measure, 'categoria').flatMap(e => {
const codigo = extension(e, 'codigo')?.valueCode, etiqueta = extension(e, 'etiqueta')?.valueString;
return codigo && etiqueta ? [[codigo, { etiqueta, color: extension(e, 'color')?.valueString ?? null, grupo: null }]] : [];
}));
}
function contrato(measure: Measure): string {
return extension(measure, 'contrato')?.valueCode ?? '';
}
// The strata a measure can be broken down by. A C2's first stratifier holds its categories, not a stratum.
function estratos(measure: Measure): string[] {
const all = (measure.group?.[0]?.stratifier ?? []).map(stratifierCode).filter((c): c is string => !!c);
return contrato(measure) === 'C2' ? all.slice(1) : all;
}
export function indicadorDeMeasure(measure: Measure): Indicador & Record<string, unknown> {
const notation = code(measure.improvementNotation);
const vistas = extensions(measure, 'vistas').map(e => e.valueCode).filter((v): v is string => !!v);
return {
id: indicadorId(measure.id ?? ''),
version: measure.version,
titulo: measure.title ?? measure.name ?? measure.id ?? '',
contrato: contrato(measure),
figuras: extensions(measure, 'figuras').map(e => e.valueString).filter((f): f is string => !!f),
tipos_periodo: extensions(measure, 'tipos-periodo').map(e => e.valueCode).filter((t): t is TipoPeriodo => t === 'semestre' || t === 'mes'),
unidad: code(measure.subjectCodeableConcept) ?? null,
sentido: notation === 'increase' ? 'mayor_mejor' : notation === 'decrease' ? 'menor_mejor' : null,
estratos: estratos(measure),
filtros: [],
...(vistas.length ? { vistas } : {}),
};
}
export function metadatosDeMeasure(measure: Measure): IndicadorMetadatos {
const unidad = code(measure.subjectCodeableConcept) ?? null;
return {
id: indicadorId(measure.id ?? ''),
version: measure.version,
descripcion: measure.description ?? null,
ficha: { codigo: (measure.id ?? '').split('-')[0], unidad, definicion: measure.description ?? null },
unidad,
referencias: [],
poblaciones: (measure.group?.[0]?.population ?? []).map(p => ({
grupo: POPULATION_GROUP[code(p.code) ?? ''] ?? code(p.code) ?? '',
codigo: p.criteria?.expression ?? code(p.code) ?? '',
descripcion: p.description ?? '',
})),
figuras_detalle: [],
categorias: categorias(measure),
};
}
// FHIR's period end is inclusive; the page's `periodo_fin`, like `dim_periodo`, is the next day.
function nextDay(day: string): string {
const date = new Date(day + 'T00:00:00Z');
date.setUTCDate(date.getUTCDate() + 1);
return date.toISOString().slice(0, 10);
}
function reporte(report: Report, periodo: string) {
const knowledge = extension(report, 'corte-conocimiento')?.valueDateTime;
return {
periodo,
report_id: extension(report, 'reporte-id')?.valueInteger ?? null,
periodo_inicio: report.period?.start ?? null,
periodo_fin: report.period ? nextDay(report.period.end) : null,
fecha_corte: extension(report, 'corte-evento')?.valueDate ?? knowledge?.slice(0, 10) ?? null,
generado_en: report.date ?? null,
};
}
function proporcion(populations: Population[] | undefined, score: Score | undefined) {
const numerador = count(populations, 'numerator'), denominador = count(populations, 'denominator');
return {
suprimido: 0, numerador, denominador,
valor: typeof score?.value === 'number' ? round1(score.value * 100) : null,
ic_bajo: decimal(score, 'ic-bajo'), ic_alto: decimal(score, 'ic-alto'),
n_sin_evento: numerador !== null && denominador !== null ? denominador - numerador : null,
n_excluido: count(populations, 'denominator-exclusion') ?? 0,
};
}
function duracion(populations: Population[] | undefined, score: Score | undefined) {
return {
suprimido: 0,
n: count(populations, 'measure-observation') ?? 0,
mediana: typeof score?.value === 'number' ? score.value : null,
q1: decimal(score, 'q1'), q3: decimal(score, 'q3'),
// The units without a value at the cut-off: FHIR's population exclusion.
n_sin_evento: count(populations, 'measure-population-exclusion') ?? 0,
n_excluido: 0,
unidad: 'dias',
};
}
function stratumValue(stratum: Stratum): string | undefined {
const value = code(stratum.value);
return value === undefined ? undefined : estratoValor(value);
}
// The `/datos` answer for `measure`, from one report per period.
export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoPeriodo, scope: DatosScope = {}): IndicadorDatos {
const kind = contrato(measure), cats = categorias(measure), estrato = scope.estrato;
const grupos = Object.fromEntries((measure.group ?? []).map(g => {
const id = code(g.code) ?? 'TOTAL';
return [id, id === 'TOTAL' ? 'Total' : display(g.code) ?? id];
}));
const valores = new Map<string, string>();
const filas: Record<string, unknown>[] = [];
const periodos: string[] = [];
for (const report of reports) {
if (!report.period) continue;
const periodo = periodLabel(report.period);
periodos.push(periodo);
for (const group of report.group ?? []) {
const grupo = code(group.code) ?? 'TOTAL';
if (kind === 'C2') {
const counts = new Map((group.stratifier?.[0]?.stratum ?? []).map(s => [code(s.value), s.population?.[0]?.count ?? 0]));
Object.keys(cats).forEach((categoria, orden) =>
filas.push({ periodo, grupo, estrato: null, categoria, n: counts.get(categoria) ?? 0, orden, suprimido: 0 }));
continue;
}
const row = (populations: Population[] | undefined, score: Score | undefined) =>
kind === 'C3r' ? duracion(populations, score) : proporcion(populations, score);
if (!estrato) {
filas.push({ periodo, grupo, estrato: null, ...row(group.population, group.measureScore) });
continue;
}
const stratifier = group.stratifier?.find(s => code(s.code?.[0]) === estrato);
if (!stratifier) throw new Error('Dimensión no admitida');
for (const stratum of stratifier.stratum ?? []) {
const valor = stratumValue(stratum);
// A stratum nobody falls in, like an empty «Sin dato», isn't a bar of its own.
if (!valor || !(stratum.population ?? []).some(p => (p.count ?? 0) > 0) && valor === 'sin_dato') continue;
valores.set(valor, display(stratum.value) ?? valor);
filas.push({ periodo, grupo, estrato: valor, ...row(stratum.population, stratum.measureScore) });
}
}
}
return {
id: indicadorId(measure.id ?? ''),
titulo: measure.title ?? measure.name ?? '',
version: measure.version,
contrato: kind,
unidad: code(measure.subjectCodeableConcept) ?? '',
tipo_periodo: tipo,
periodos,
estrato: estrato ?? null,
...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: Object.fromEntries(valores) } : { valores_estrato: [] }),
grupos,
categorias: cats,
grupos_de_categoria: {},
notas: [],
reportes: reports.filter(r => r.period).map(r => reporte(r, periodLabel(r.period!))),
filas,
};
}
// One box per period, from each period's median and quartiles.
export function cajaDeDatos(datos: IndicadorDatos): PlotlyFigure {
const filas = datos.filas.filter(f => f['grupo'] === 'TOTAL' && f['estrato'] == null && typeof f['mediana'] === 'number');
const values = (field: string) => filas.map(f => f[field]);
return {
data: filas.length ? [{ type: 'box', name: 'Total', x: values('periodo'), q1: values('q1'), median: values('mediana'), q3: values('q3'),
lowerfence: values('q1'), upperfence: values('q3') }] : [],
layout: { title: { text: String(datos['titulo'] ?? '') }, autosize: true, margin: { l: 60, r: 24, t: 60, b: 60 },
yaxis: { title: { text: 'días' }, rangemode: 'tozero' } },
};
}
function tipoDe(periodo: string): TipoPeriodo {
return periodo.includes('-S') ? 'semestre' : 'mes';
}
// The `count` periods of `tipo` from the one starting on `start`, in order.
export function periodosDesde(start: string, tipo: TipoPeriodo, total: number): string[] {
const [year, month] = start.split('-').map(Number);
return Array.from({ length: total }, (_, i) => {
if (tipo === 'semestre') {
const n = (year * 2 + (month >= 7 ? 1 : 0)) + i;
return `${Math.floor(n / 2)}-S${n % 2 + 1}`;
}
const n = year * 12 + month - 1 + i;
return `${Math.floor(n / 12)}-${String(n % 12 + 1).padStart(2, '0')}`;
});
}
// A period that hasn't started by `today` has no data to show.
export function periodoIniciado(periodo: string, today: Date): boolean {
const current = periodOrder(tipoDe(periodo) === 'semestre'
? `${today.getFullYear()}-S${today.getMonth() < 6 ? 1 : 2}`
: `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}`);
return periodOrder(periodo) <= current;
}
@Injectable({ providedIn: 'root' })
export class FhirMeasures {
private readonly http = inject(HttpClient);
private readonly cache = new Map<Dominio, Observable<Measure[]>>();
all(dominio: Dominio): Observable<Measure[]> {
const domain = requireDominio(dominio);
let request = this.cache.get(domain);
if (!request) {
request = this.http.get<Bundle>(`/${domain}/fhir/Measure`).pipe(
map(bundle => resources(bundle, 'Measure') as Measure[]), shareReplay({ bufferSize: 1, refCount: false }));
this.cache.set(domain, request);
}
return request;
}
one(dominio: Dominio, indicador: string): Observable<Measure> {
return this.all(dominio).pipe(map(measures => {
const found = measures.find(m => indicadorId(m.id ?? '') === indicador);
if (!found) throw new Error('Indicador no publicado');
return found;
}));
}
reports(dominio: Dominio, measure: Measure, params: HttpParams): Observable<Bundle> {
return this.http.get<Bundle>(`/${requireDominio(dominio)}/fhir/MeasureReport`, { params: params.set('measure', measure.url ?? measure.id ?? '') });
}
}
@Injectable()
export class FhirIndicadoresService extends IndicadoresService {
private readonly measures = inject(FhirMeasures);
override catalogo(dominio: Dominio = 'tea') {
return this.measures.all(dominio).pipe(map(all => catalogoValido(all.map(indicadorDeMeasure))));
}
override metadatos(dominio: Dominio, indicador: string) {
return this.measures.one(dominio, indicador).pipe(map(m => metadatosValidos(metadatosDeMeasure(m))));
}
override datos(dominio: Dominio, indicador: string, tipo: TipoPeriodo, periodos?: string[], scope: DatosScope = {}) {
datosParams(tipo, periodos, scope);
if (scope.filtros?.length) throw new Error('Filtro no admitido');
let params = new HttpParams().set('_count', MAX_COUNT);
params = periodos ? params.set('periodo', [...new Set(periodos)].join(',')) : params.set('tipo-periodo', tipo);
return this.measures.one(dominio, indicador).pipe(
switchMap(measure => this.measures.reports(dominio, measure, params).pipe(
map(bundle => datosValidos(datosDeReportes(measure, resources(bundle, 'MeasureReport') as Report[], tipo, scope), indicador, tipo, periodos, scope)))));
}
override figura(selection: FigureSelection) {
const dominio = requireDominio(selection.dominio ?? 'tea');
const periodos = figuraPeriodos(selection);
if (selection.figura !== 'fig_c3r_caja') throw new Error('Figura no disponible');
const tipo = selection.tipoPeriodo ?? (periodos ? tipoDe(periodos[0]) : 'semestre');
return this.datos(dominio, selection.indicador, tipo, periodos).pipe(map(datos => figuraValida(cajaDeDatos(datos))));
}
}
// Every measure of a domain shares its periods (`dim_periodo`, whole years); one report of each type gives the first
// period and the search's total how many follow.
@Injectable()
export class FhirIndicadoresPeriodos extends IndicadoresPeriodos {
private readonly measures = inject(FhirMeasures);
private readonly queue = inject(IndicadoresRequests);
private readonly byDomain = new Map<Dominio, Observable<AvailablePeriod[]>>();
today = () => new Date();
override periodos(domain: Dominio, id: string): Observable<AvailablePeriod[]> {
const dominio = requireDominio(domain);
let request = this.byDomain.get(dominio);
if (!request) {
request = this.measures.one(dominio, id).pipe(
switchMap(measure => this.queue.run(() => this.measures.reports(dominio, measure, new HttpParams().set('tipo-periodo', 'semestre').set('_count', 1))).pipe(
switchMap(semestres => this.queue.run(() => this.measures.reports(dominio, measure, new HttpParams().set('tipo-periodo', 'mes').set('_count', 1))).pipe(
map(meses => [...this.listed(semestres, 'semestre'), ...this.listed(meses, 'mes')]
.sort((a, b) => periodOrder(b.periodo) - periodOrder(a.periodo))))))),
shareReplay({ bufferSize: 1, refCount: false }));
this.byDomain.set(dominio, request);
}
return request;
}
private listed(bundle: Bundle, tipo: TipoPeriodo): AvailablePeriod[] {
const first = (resources(bundle, 'MeasureReport')[0] as Report | undefined)?.period;
if (!first || !bundle.total) return [];
const today = this.today();
return periodosDesde(first.start, tipo, bundle.total).filter(p => periodoIniciado(p, today)).map(periodo => ({ periodo, tipo }));
}
}
@@ -2,7 +2,6 @@ import { figureDisplayName } from './indicadores-figure-labels';
describe('UX-07A nombres de representaciones', () => {
it.each([
['fig_c1_barras_alteracion', 'Barras por alteración'],
['fig_c1_grupos', 'Grupos'],
['fig_c1_puntos', 'Puntos'],
['fig_c2_apiladas', 'Barras apiladas'],
@@ -2,11 +2,6 @@
// Exact IDs remain the option values and HTTP identities; never infer a type
// from a prefix. Unknown options keep a neutral label in publication order.
const FIGURE_LABELS: Readonly<Record<string, string>> = {
fig_c1_barras_alteracion: 'Barras por alteración',
fig_c1_barras_apiladas_edad: 'Barras apiladas por grupo de edad',
fig_c1_barras_edad: 'Barras por grupo de edad',
fig_c1_dona_edad: 'Dona por grupo de edad',
fig_c1_donas: 'Dona de dos anillos',
fig_c1_grupos: 'Grupos',
fig_c1_puntos: 'Puntos',
fig_c2_apiladas: 'Barras apiladas',
@@ -38,7 +38,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
function request(id: string) { return http.expectOne(r => r.url.endsWith('/' + id + '/figuras/f')); }
function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [42, null, 0] }], layout: {} })); fixture.detectChanges(); }
function draft(tipo: TipoPeriodo, periods: string[]) {
const control = editor(); control.changeTipo(tipo); control.select([]);
const control = editor(); control.changeTipo(tipo); control.changeMode('manual');
for (const period of periods) { control.year = period.slice(0, 4); control.unit = period.slice(5); control.add(); }
}
function apply() { page.applyFilters(); fixture.detectChanges(); }
@@ -67,7 +67,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
});
it('edición y vacío no consultan ni cambian el resultado vigente', () => {
load(); open(); respond(); const result = panels()[0].result();
editor().select([]); apply(); expect(page.filters!.applied.revision).toBe(0);
editor().changeMode('manual'); apply(); expect(page.filters!.applied.revision).toBe(0);
expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true);
draft('semestre', ['2025-S1']); fixture.detectChanges();
expect(panels()[0].result()).toBe(result); expect(page.filters!.applied.selection.mode).toBe('todos'); http.expectNone(() => true);
@@ -82,9 +82,9 @@ describe('D.2 integración de autoridad global y consumidores', () => {
http.expectNone(() => true);
});
it('aplicación equivalente conserva revisión, consumidores, hosts y resultados', () => {
load(); open(); respond(); draft('semestre', ['2025-S2']); apply(); respond();
load(); open(); respond(); draft('semestre', ['2025-S1', '2025-S2']); apply(); respond();
const panel = panels()[0], result = panel.result(), chart = fixture.nativeElement.querySelector('app-plotly-chart'), applied = page.filters!.applied;
editor().select(['2025-S2']); apply();
editor().select(['2025-S2', '2025-S1']); apply();
expect(page.filters!.applied).toBe(applied); expect(panel.result()).toBe(result);
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); expect(panels()[0]).toBe(panel); http.expectNone(() => true);
});
@@ -114,7 +114,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
expect(panel.result().status).toBe('incompatible'); expect(panel.result().figure).toBeUndefined();
http.expectNone(r => r.url.includes('/a/figuras/')); const r = request('b');
expect(r.request.params.get('periodos')).toBe('2025-01'); expect(r.request.params.has('tipoPeriodo')).toBe(false);
expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('intervalo de análisis mensual');
expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('intervalo de tiempo mes');
expect((host as HTMLElement).parentElement!.hidden).toBe(true);
r.flush({ data: [], layout: {} });
expect(fixture.nativeElement.textContent).not.toContain('Todos los meses');
@@ -145,7 +145,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
editor().year = '2025'; editor().unit = 'S2'; editor().add(); page.changeDominio('cacu'); fixture.detectChanges();
expect(outgoing.cancelled).toBe(true); load(undefined, 'cacu'); expect(page.filters!.applied.selection.mode).toBe('todos');
draft('mes', ['2026-01']); apply(); page.changeDominio('tea'); load();
expect(editor().selectedPeriods).toEqual(['2025-S2']); expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2025-S1'] });
expect(editor().selectedPeriods).toEqual(['2025-S1', '2025-S2']); expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2025-S1'] });
expect(cards()[0].visible).toBe(false);
http.match(r => r.url.endsWith('/datos')).filter(r => !r.cancelled).forEach(r => r.flush('missing', { status: 404, statusText: 'Not Found' }));
http.expectNone(() => true);
@@ -1,57 +0,0 @@
import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, toggleHighlight } from './indicadores-highlight';
import { PlotlyFigure } from './indicadores.models';
// A double donut like dona(): 0 centre, 1 groups, 2 categories.
const figure: PlotlyFigure = { data: [
{ type: 'pie', values: [1], text: ['<b>10</b><br>TOTAL'] },
{ type: 'pie', values: [6, 4], marker: { colors: ['rgba(10, 20, 30, 1)', '#FF0000'] } },
{ type: 'pie', values: [2, 4, 4], marker: { colors: ['#000000', '#111111', '#222222'] } },
], layout: {} };
const h: FigureHighlight = { traces: [1, 2], center: { trace: 0 }, allLabel: 'TOTAL',
groups: [{ id: 'A', label: 'Grupo A', color: '#000000', points: [{ trace: 1, index: 0 }, { trace: 2, index: 0 }, { trace: 2, index: 1 }], center: 'A' },
{ id: 'B', label: 'Grupo B', color: '#FF0000', points: [{ trace: 1, index: 1 }, { trace: 2, index: 2 }], center: 'B' }],
items: [{ id: 'a1', label: 'A · 1', short: '1', color: '#000000', group: 'A', points: [{ trace: 2, index: 0 }], center: 'a1' },
{ id: 'a2', label: 'A · 2', short: '2', color: '#111111', group: 'A', points: [{ trace: 2, index: 1 }] },
{ id: 'b1', label: 'B · 1', short: '1', color: '#222222', group: 'B', points: [{ trace: 2, index: 2 }] }] };
const colors = (f: PlotlyFigure, t: number) => (f.data[t]['marker'] as { colors: string[] }).colors;
describe('Botones que resaltan una parte de la figura', () => {
it('sin selección deja la figura intacta', () => {
expect(highlightFigure(figure, h, {})).toBe(figure);
expect(highlightLabel(h, {})).toBe('TOTAL');
});
it('un grupo conserva su parte de ambos anillos y atenúa el resto, también colores rgba', () => {
const f = highlightFigure(figure, h, { group: 'B' });
expect(colors(f, 1)).toEqual(['rgba(10, 20, 30, 0.3)', '#FF0000']);
expect(colors(f, 2)).toEqual(['rgba(0, 0, 0, 0.3)', 'rgba(17, 17, 17, 0.3)', '#222222']);
expect(f.data[0]['text']).toEqual(['B']);
expect(colors(figure, 2)).toEqual(['#000000', '#111111', '#222222']);
});
it('una categoría conserva su grupo en el anillo interior', () => {
const f = highlightFigure(figure, h, { item: 'a1' });
expect(colors(f, 1)).toEqual(['rgba(10, 20, 30, 1)', 'rgba(255, 0, 0, 0.3)']);
expect(colors(f, 2)).toEqual(['#000000', 'rgba(17, 17, 17, 0.3)', 'rgba(34, 34, 34, 0.3)']);
expect(f.data[0]['text']).toEqual(['a1']);
});
it('en barras atenúa con la opacidad de cada barra', () => {
const bars: PlotlyFigure = { data: [{ type: 'bar', x: ['a', 'b', 'c'], y: [1, 2, 3], marker: { color: '#000000' } }], layout: {} };
const hb: FigureHighlight = { groups: [], traces: [0], allLabel: 'Todas', items: ['a', 'b', 'c'].map((id, i) => ({ id, label: id, color: '#000000', points: [{ trace: 0, index: i }] })) };
expect((highlightFigure(bars, hb, { item: 'b' }).data[0]['marker'] as { opacity: number[] }).opacity).toEqual([.3, 1, .3]);
});
it('alterna como CaCu: repetir vuelve un paso y un grupo limita las categorías', () => {
expect(toggleHighlight(h, {}, 'group', 'A')).toEqual({ group: 'A' });
expect(toggleHighlight(h, { group: 'A' }, 'group', 'A')).toEqual({});
expect(toggleHighlight(h, { group: 'A' }, 'item', 'a2')).toEqual({ group: 'A', item: 'a2' });
expect(toggleHighlight(h, { group: 'A', item: 'a2' }, 'item', 'a2')).toEqual({ group: 'A' });
expect(toggleHighlight(h, { group: 'A' }, 'item', 'b1')).toEqual({ group: 'A' });
expect(toggleHighlight(h, {}, 'item', 'b1')).toEqual({ item: 'b1' });
});
it('un clic en el anillo exterior es la categoría; en el interior, el grupo', () => {
expect(highlightAt(h, { trace: 2, index: 1 })).toEqual({ kind: 'item', id: 'a2' });
expect(highlightAt(h, { trace: 1, index: 1 })).toEqual({ kind: 'group', id: 'B' });
expect(highlightAt(h, { trace: 0, index: 0 })).toBeUndefined();
});
it('agrupa los botones en filas: cada grupo seguido de sus categorías', () => {
expect(highlightRows(h).map(r => [r.group?.id, r.items.map(i => i.id)])).toEqual([['A', ['a1', 'a2']], ['B', ['b1']]]);
});
});
@@ -1,117 +0,0 @@
import { Modelo } from './indicadores-eu7-escenario';
import { PlotlyFigure } from './indicadores.models';
// Legend buttons that highlight one part of a figure, like CaCu's «Distribución de resultados
// citológicos»: the chosen group or category keeps its colour and everything else fades.
export interface HighlightPoint { trace: number; index: number; }
export interface HighlightEntry {
id: string; label: string; color: string;
// Shorter label for the button when it sits next to its group's button.
short?: string;
// Only for categories: the group they belong to (its button narrows the categories on offer).
group?: string;
points: readonly HighlightPoint[];
// Text for the centre of a donut while this entry is chosen.
center?: string;
}
export interface FigureHighlight {
groups: readonly HighlightEntry[];
items: readonly HighlightEntry[];
// Traces whose points fade when they are not part of the choice.
traces: readonly number[];
// Where a donut shows its centre text: a pie trace's single text, or a layout annotation.
center?: { trace: number } | { annotation: number };
// Name of the whole, for the status line.
allLabel: string;
}
export interface HighlightSelection { group?: string; item?: string; }
const FADED = .3;
// Accepts #RRGGBB and rgb()/rgba() (dona() already writes its colours as rgba).
function rgba(color: string, alpha: number): string {
const hex = /^#([0-9a-f]{6})$/i.exec(color);
if (hex) {
const [r, g, b] = [0, 2, 4].map(i => parseInt(hex[1].slice(i, i + 2), 16));
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}
const rgb = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i.exec(color);
return rgb ? `rgba(${rgb[1]}, ${rgb[2]}, ${rgb[3]}, ${alpha})` : color;
}
export function highlightEntry(h: FigureHighlight, sel: HighlightSelection): HighlightEntry | undefined {
return sel.item ? h.items.find(e => e.id === sel.item) : sel.group ? h.groups.find(e => e.id === sel.group) : undefined;
}
export function highlightLabel(h: FigureHighlight, sel: HighlightSelection): string {
return highlightEntry(h, sel)?.label ?? h.allLabel;
}
// Same state machine as CaCu: choosing the chosen entry again goes back one step.
export function toggleHighlight(h: FigureHighlight, sel: HighlightSelection, kind: 'group' | 'item', id: string): HighlightSelection {
if (kind === 'group') return !h.groups.some(g => g.id === id) || sel.group === id ? {} : { group: id };
const item = h.items.find(e => e.id === id);
if (!item || (sel.group && item.group !== sel.group)) return sel;
return sel.item === id ? (sel.group ? { group: sel.group } : {}) : { ...(sel.group ? { group: sel.group } : {}), item: id };
}
// The entry a click on the figure means: a category first, otherwise a group.
export function highlightAt(h: FigureHighlight, point: HighlightPoint): { kind: 'group' | 'item'; id: string } | undefined {
const hit = (e: HighlightEntry) => e.points.some(p => p.trace === point.trace && p.index === point.index);
// A group also covers its categories' slices, so an outer slice hits both: the category wins.
const item = h.items.find(hit);
if (item) return { kind: 'item', id: item.id };
const group = h.groups.find(hit);
return group ? { kind: 'group', id: group.id } : undefined;
}
export function highlightFigure(figure: PlotlyFigure, h: FigureHighlight, sel: HighlightSelection): PlotlyFigure {
const entry = highlightEntry(h, sel);
if (!entry) return figure;
const keep = new Set(entry.points.map(p => p.trace + ':' + p.index));
// A chosen category also keeps its group's slice of the inner ring (not its sibling categories).
const group = entry.group ? h.groups.find(g => g.id === entry.group) : undefined;
const own = new Set(entry.points.map(p => p.trace));
group?.points.filter(p => !own.has(p.trace)).forEach(p => keep.add(p.trace + ':' + p.index));
const data = figure.data.map((trace, t) => {
if (!h.traces.includes(t)) return trace;
const marker = (trace['marker'] ?? {}) as Record<string, unknown>;
if (trace['type'] === 'pie') {
const colors = (marker['colors'] as unknown[] | undefined) ?? [];
return { ...trace, marker: { ...marker, colors: colors.map((c, i) => typeof c === 'string' && !keep.has(t + ':' + i) ? rgba(c, FADED) : c) } };
}
const count = Array.isArray(trace['x']) ? (trace['x'] as unknown[]).length : Array.isArray(trace['y']) ? (trace['y'] as unknown[]).length : 0;
return { ...trace, marker: { ...marker, opacity: Array.from({ length: count }, (_, i) => keep.has(t + ':' + i) ? 1 : FADED) } };
});
let layout = figure.layout;
if (entry.center !== undefined && h.center) {
if ('trace' in h.center) {
const t = h.center.trace;
data[t] = { ...data[t], text: [entry.center] };
} else {
const annotations = [...((layout['annotations'] as Record<string, unknown>[] | undefined) ?? [])];
if (annotations[h.center.annotation]) annotations[h.center.annotation] = { ...annotations[h.center.annotation], text: entry.center };
layout = { ...layout, annotations };
}
}
return { ...figure, data, layout };
}
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// Buttons for a figure drawn by dona() (traces: 0 centre, 1 groups, 2 categories). A group also
// covers its categories' slices; the centre shows the count of the choice. `short` gives each
// category's button label next to its group (by default, its full label).
export function donaHighlight(m: Modelo, short: (id: string) => string | undefined = () => undefined): FigureHighlight {
const centre = (n: number, label: string) => '<b>' + n.toLocaleString('es-MX') + '</b><br>' + escape(label);
return { traces: [1, 2], center: { trace: 0 }, allLabel: 'TOTAL',
groups: m.grupos.map((g, gi) => {
const children = m.categorias.map((c, i) => ({ c, i })).filter(({ c }) => c.grupo === g.id);
return { id: g.id, label: g.etiqueta, color: g.color,
points: [{ trace: 1, index: gi }, ...children.map(({ i }) => ({ trace: 2, index: i }))],
center: centre(children.reduce((n, { c }) => n + (m.celdas[c.id].n ?? 0), 0), g.etiqueta) };
}),
items: m.categorias.map((c, i) => ({ id: c.id, label: c.etiqueta, short: short(c.id), color: c.color, group: c.grupo,
points: [{ trace: 2, index: i }], center: centre(m.celdas[c.id].n ?? 0, c.etiqueta) })) };
}
// Rows of buttons: each group followed by its categories; categories without a group share one row.
export function highlightRows(h: FigureHighlight): { group?: HighlightEntry; items: HighlightEntry[] }[] {
const rows = h.groups.map(group => ({ group, items: h.items.filter(i => i.group === group.id) }));
const loose = h.items.filter(i => !i.group || !h.groups.some(g => g.id === i.group));
return loose.length ? [...rows, { items: loose }] : rows;
}
@@ -1,174 +0,0 @@
import { filasDelGrupo, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Color, c2Theme, C2_PALETTE } from './indicadores-c2-palette';
import { sortedPeriods } from './indicadores-periodos';
import { M28_COMPLETO, M28_EN_PROCESO } from './indicadores-kpi';
export interface HistoricoFigura {
figure: PlotlyFigure;
comoLeer: string;
suprimidos: string[];
sinDato: string[];
}
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// The EEG indicators avoid green; their colours are shared with their age groups' palette.
const LINEAS: Readonly<Record<string, string>> = { M21_diagnosticados_con_eeg: C2_PALETTE.edades[0], M22_diagnosticados_sin_eeg: C2_PALETTE.edades[2] };
const numero = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
// sortedPeriods lists the newest first, for selectors; time here runs left to right.
export const cronologico = (periodos: readonly string[]) => sortedPeriods(periodos).reverse();
const MESES = ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic'];
// «mar 2024» and «2024 S1»: a bare 2024-03 was read as a mix of months and years.
export function etiquetaPeriodo(periodo: string): string {
const [anio, resto] = periodo.split('-');
return resto.startsWith('S') ? `${anio} ${resto}` : `${MESES[Number(resto) - 1]} ${anio}`;
}
export interface HistoricoOpciones {
// Same vertical scale across small charts, so their heights compare.
yMax?: number;
pequena?: boolean;
}
function validar(data: IndicadorDatos) {
for (const row of data.filas) {
if (![0, 1].includes(row['suprimido'] as number)) throw new Error('Fila de histórico inválida');
}
return cronologico(data.periodos);
}
function ejes(data: IndicadorDatos, periodos: string[], suprimidos: string[], tema: Tema, titulo: string, pequena = false) {
const theme = c2Theme(tema), mensual = data.tipo_periodo === 'mes', etiquetas = periodos.map(etiquetaPeriodo);
const cada = pequena && periodos.length > 12 ? 6 : 3;
return {
autosize: true, height: pequena ? 340 : 400, paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text },
margin: { l: 64, r: 16, t: 16, b: mensual ? 110 : 84 }, showlegend: true, legend: { orientation: 'h', y: mensual ? -0.42 : -0.26, itemclick: false, itemdoubleclick: false },
// A label for every month does not fit: one per quarter is still readable with the full period on hover.
xaxis: { type: 'category', categoryorder: 'array', categoryarray: etiquetas, showgrid: false, automargin: true, tickangle: mensual ? -45 : 0,
title: { text: mensual ? 'Mes y año' : 'Semestre' }, tickmode: 'array', tickvals: etiquetas.filter((_, i) => periodos.length <= 12 || i % cada === 0) },
yaxis: { rangemode: 'tozero', title: { text: titulo }, gridcolor: theme.grid, zeroline: false },
// Shaded, because an empty space alone reads as zero. Text below the figure says the same.
shapes: suprimidos.map(periodo => ({ type: 'rect', layer: 'below', xref: 'x', yref: 'paper', y0: 0, y1: 1, line: { width: 0 },
x0: periodos.indexOf(periodo) - .5, x1: periodos.indexOf(periodo) + .5, fillcolor: C2_PALETTE.states.suppressed, opacity: .18 })),
};
}
// One polygon per run of consecutive values: a band must not bridge a gap in the line.
function banda(periodos: string[], bajo: (number | null)[], alto: (number | null)[], name: string, color: string) {
const x: (string | null)[] = [], y: (number | null)[] = [];
let run: number[] = [];
const cerrar = () => {
if (run.length) {
if (x.length) { x.push(null); y.push(null); }
x.push(...run.map(i => periodos[i]), ...[...run].reverse().map(i => periodos[i]));
y.push(...run.map(i => alto[i]), ...[...run].reverse().map(i => bajo[i]));
}
run = [];
};
periodos.forEach((_, i) => { if (bajo[i] !== null && alto[i] !== null) run.push(i); else cerrar(); });
cerrar();
return { type: 'scatter', mode: 'lines', name, x, y, fill: 'toself', fillcolor: color + '40', line: { width: 0 }, hoverinfo: 'skip' };
}
// Separate rows from what is missing or suppressed; a period is judged by its only row.
function serie(data: IndicadorDatos, periodos: string[], valor: (row: Record<string, unknown>) => boolean) {
const delTotal = filasDelGrupo(data, 'TOTAL');
const filas = new Map(delTotal.map(row => [row['periodo'] as string, row]));
if (filas.size !== delTotal.length) throw new Error('Filas ambiguas');
const suprimidos: string[] = [], sinDato: string[] = [];
const validas = periodos.map(periodo => {
const row = filas.get(periodo);
if (row?.['suprimido'] === 1) { suprimidos.push(periodo); return null; }
if (!row || !valor(row)) { sinDato.push(periodo); return null; }
return row;
});
return { validas, suprimidos, sinDato };
}
const campo = (filas: (Record<string, unknown> | null)[], key: string) => filas.map(row => numero(row?.[key]) ? row![key] as number : null);
function porcentaje(data: IndicadorDatos, tema: Tema): HistoricoFigura {
const periodos = validar(data);
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']));
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), linea = LINEAS[data.id] ?? c2Theme(tema).line;
return {
figure: { data: [
banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', linea),
{ type: 'scatter', mode: 'lines+markers', name: 'Porcentaje', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'valor'), connectgaps: false, line: { color: linea, width: 2 },
text: validas.map(row => row ? `${row['valor']} %<br>${row['numerador']} de ${row['denominador']}<br>IC ${row['ic_bajo']} a ${row['ic_alto']} %` : ''),
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
comoLeer: 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.',
suprimidos, sinDato,
};
}
function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): HistoricoFigura {
const periodos = validar(data);
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']));
return {
figure: { data: [
banda(periodos.map(etiquetaPeriodo), campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', c2Theme(tema).line),
{ type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: c2Theme(tema).line, width: 2 },
text: validas.map(row => row ? `Mediana: ${row['mediana']} días<br>Q1 a Q3: ${row['q1']} a ${row['q3']} días<br>${row['n']} pacientes` : ''),
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
], layout: (() => {
const layout = ejes(data, periodos, suprimidos, tema, 'Días', opciones.pequena);
return opciones.yMax ? { ...layout, yaxis: { ...layout.yaxis, range: [0, opciones.yMax] } } : layout;
})() },
comoLeer: 'La línea es la mediana de días de cada periodo. La banda va del primer al tercer cuartil: la mitad central de los pacientes.',
suprimidos, sinDato,
};
}
// What each count means, for the indicators that don't count patients in the period.
const CONTEOS: Readonly<Record<string, { eje: string; comoLeer: string }>> = {
M28_casos_por_estado: { eje: 'Casos', comoLeer: 'Cada barra cuenta todos los casos iniciados hasta el cierre del periodo, con su estado en esa fecha. Un caso en proceso puede estar completo en el siguiente periodo.' },
M29_calidad_eeg: { eje: 'Estudios de EEG', comoLeer: 'Cada barra son los EEG del periodo, según su calificación general.' },
};
function conteo(data: IndicadorDatos, tema: Tema): HistoricoFigura {
const periodos = validar(data), catalogo = record(data['categorias']) ? data['categorias'] : {};
const celdas = new Map<string, Record<string, unknown>>(), categorias = new Map<string, number>();
for (const row of data.filas) {
const id = row['categoria'], key = JSON.stringify([id, row['periodo']]);
if (typeof id !== 'string' || !id || !numero(row['orden']) || celdas.has(key)) throw new Error('Fila de histórico inválida');
celdas.set(key, row);
categorias.set(id, row['orden']);
}
const orden = [...categorias].sort(([, a], [, b]) => a - b).map(([id]) => id);
const estadoDe = (periodo: string) => orden.map(id => celdas.get(JSON.stringify([id, periodo])));
const suprimidos = periodos.filter(p => estadoDe(p).some(row => row?.['suprimido'] === 1));
const sinDato = periodos.filter(p => !suprimidos.includes(p) && estadoDe(p).some(row => !numero(row?.['n'])));
return {
figure: { data: orden.map((id, i) => {
const meta = record(catalogo[id]) ? catalogo[id] : {};
const color = typeof meta['color'] === 'string' && /^#[0-9a-f]{6}$/i.test(meta['color']) ? meta['color'] : undefined;
const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) ? n : null; });
return { type: 'bar', name: escape(typeof meta['etiqueta'] === 'string' ? meta['etiqueta'] : id), x: periodos.map(etiquetaPeriodo), y: valores,
marker: { color: c2Color(color, i) }, hovertemplate: '%{y}<extra>%{fullData.name}</extra>' };
}), layout: { ...ejes(data, periodos, suprimidos, tema, CONTEOS[data.id]?.eje ?? 'Pacientes'), barmode: 'stack', bargap: .15, hovermode: 'x unified' } },
comoLeer: CONTEOS[data.id]?.comoLeer ?? 'Cada barra es el total de pacientes del periodo, y sus partes muestran cuántos hay en cada categoría.',
suprimidos, sinDato,
};
}
// The plot follows from what the contract's numbers mean: counts add up to a total, percentages
// and medians do not, so those two are never stacked.
export function historicoFigura(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones = {}): HistoricoFigura {
const figura = data.contrato === 'C2' ? conteo(data, tema) : data.contrato === 'C1' ? porcentaje(data, tema)
: data.contrato === 'C3r' ? mediana(data, tema, opciones) : undefined;
if (!figura) throw new Error('Representación no soportada');
return { ...figura, suprimidos: figura.suprimidos.map(etiquetaPeriodo), sinDato: figura.sinDato.map(etiquetaPeriodo) };
}
// The share of the children in the screening at each period's end who hadn't finished it, from M28's stages.
export function enProcesoFigura(data: IndicadorDatos, tema: Tema): HistoricoFigura {
const periodos = validar(data);
const n = (periodo: string, categorias: readonly string[]) => {
const valores = categorias.map(c => data.filas.find(f => f['periodo'] === periodo && f['categoria'] === c)?.['n']);
return valores.every(numero) ? (valores as number[]).reduce((s, v) => s + v, 0) : null;
};
const puntos = periodos.map(periodo => {
const proceso = n(periodo, M28_EN_PROCESO), completo = n(periodo, [M28_COMPLETO]);
return proceso === null || completo === null || proceso + completo === 0 ? null : { proceso, base: proceso + completo };
});
const layout = ejes(data, periodos, [], tema, 'Porcentaje');
return {
figure: { data: [{ type: 'scatter', mode: 'lines+markers', name: 'En proceso', x: periodos.map(etiquetaPeriodo), connectgaps: false, line: { color: C2_PALETTE.series[1], width: 2 },
y: puntos.map(p => p && Math.round(1000 * p.proceso / p.base) / 10), text: puntos.map(p => p ? `${p.proceso} de ${p.base} niños` : ''),
hovertemplate: '%{x}<br>%{y} % en proceso<br>%{text}<extra></extra>' }],
layout: { ...layout, showlegend: false, margin: { ...layout.margin, b: data.tipo_periodo === 'mes' ? 84 : 64 }, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
comoLeer: 'De los niños en el tamizaje al cierre de cada periodo, el porcentaje que todavía no lo completaba con un EEG de buena calidad.',
suprimidos: [], sinDato: periodos.filter((_, i) => !puntos[i]).map(etiquetaPeriodo),
};
}
@@ -1,58 +0,0 @@
import { Component, computed, inject, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { etiquetaPeriodo } from './indicadores-historico-figures';
import { TipoPeriodo } from './indicadores.models';
export interface PeriodosDialogoDatos { tipo: TipoPeriodo; periodos: readonly string[]; elegidos: readonly string[]; }
// The periods of the chosen analysis interval, by year. Closes with the chosen ones, oldest first, or with nothing if cancelled.
@Component({
selector: 'app-indicadores-historico-periodos',
imports: [MatButtonModule, MatCheckboxModule, MatDialogModule],
template: `
<h2 mat-dialog-title>Elegir {{ datos.tipo === 'mes' ? 'meses' : 'semestres' }}</h2>
<mat-dialog-content>
<div class="acciones">
<button type="button" mat-button (click)="elegidos.set(todos)">Elegir todos</button>
<button type="button" mat-button (click)="elegidos.set([])">Quitar todos</button>
</div>
@for (grupo of anios; track grupo.anio) {
<fieldset>
<legend>{{ grupo.anio }}</legend>
@for (periodo of grupo.periodos; track periodo) {
<mat-checkbox [checked]="elegidos().includes(periodo)" (change)="alternar(periodo)">{{ etiqueta(periodo) }}</mat-checkbox>
}
</fieldset>
}
</mat-dialog-content>
<mat-dialog-actions align="end">
<span class="cuenta" role="status">{{ cuenta() }}</span>
<button type="button" mat-button mat-dialog-close>Cancelar</button>
<button type="button" mat-flat-button [disabled]="!elegidos().length" (click)="aplicar()">Aplicar</button>
</mat-dialog-actions>
`,
styles: `
.acciones { display: flex; gap: .5rem; margin-bottom: .5rem; }
fieldset { display: grid; grid-template-columns: repeat(auto-fill, minmax(8rem, 1fr)); gap: 0 .5rem; margin: 0 0 .75rem; padding: .25rem .5rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
legend { padding-inline: .25rem; font-weight: 600; }
.cuenta { margin-inline-end: auto; padding-inline-start: .75rem; font: var(--mat-sys-body-medium); }
`,
})
export class IndicadoresHistoricoPeriodos {
readonly datos = inject<PeriodosDialogoDatos>(MAT_DIALOG_DATA);
private readonly dialogo = inject<MatDialogRef<IndicadoresHistoricoPeriodos, string[]>>(MatDialogRef);
readonly etiqueta = etiquetaPeriodo;
readonly todos = [...this.datos.periodos];
readonly elegidos = signal<readonly string[]>(this.datos.elegidos);
readonly anios = [...new Set(this.todos.map(p => p.slice(0, 4)))].map(anio => ({ anio, periodos: this.todos.filter(p => p.startsWith(anio)) }));
readonly cuenta = computed(() => {
const n = this.elegidos().length, mes = this.datos.tipo === 'mes';
return n === 1 ? (mes ? '1 mes elegido' : '1 semestre elegido') : `${n} ${mes ? 'meses elegidos' : 'semestres elegidos'}`;
});
alternar(periodo: string) {
this.elegidos.update(actual => actual.includes(periodo) ? actual.filter(p => p !== periodo) : [...actual, periodo]);
}
aplicar() { this.dialogo.close(this.todos.filter(p => this.elegidos().includes(p))); }
}
@@ -1,245 +0,0 @@
import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { Subject } from 'rxjs';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos';
import { IndicadoresHistorico } from './indicadores-historico';
import { enProcesoFigura, etiquetaPeriodo, historicoFigura } from './indicadores-historico-figures';
import { Indicador, IndicadorDatos } from './indicadores.models';
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
class ChartStub {}
const traza = (d: IndicadorDatos, i: number) => historicoFigura(d, 'claro').figure.data[i] as Record<string, unknown[]> & { x: unknown[]; y: unknown[] };
const base = { id: 'i', tipo_periodo: 'mes' as const, periodos: ['2024-03', '2024-01', '2024-02'] };
const c1 = (periodo: string, valor: number | null, suprimido = 0) => ({ periodo, suprimido, valor, numerador: valor, denominador: valor === null ? null : 100,
ic_bajo: valor === null ? null : valor - 5, ic_alto: valor === null ? null : valor + 5 });
const c2 = (periodo: string, categoria: string, n: number | null, orden: number, suprimido = 0) => ({ periodo, categoria, n, orden, suprimido });
describe('Figuras de histórico', () => {
it('C2 apila conteos en orden cronológico, por categoría y con el color publicado', () => {
const data: IndicadorDatos = { ...base, contrato: 'C2', categorias: { B: { etiqueta: 'Bé <b>', color: '#112233' } }, filas: base.periodos.flatMap(p => [c2(p, 'B', 2, 1), c2(p, 'A', 1, 0)]) };
const { figure, suprimidos, sinDato } = historicoFigura(data, 'claro');
expect(figure.layout['barmode']).toBe('stack');
expect(figure.data.map(t => t['name'])).toEqual(['A', 'Bé &lt;b&gt;']);
expect(figure.data[0]['x']).toEqual(['ene 2024', 'feb 2024', 'mar 2024']);
expect((figure.layout['xaxis'] as { title: { text: string } }).title.text).toBe('Mes y año');
expect((figure.data[1]['marker'] as { color: string }).color).toBe('#112233');
expect(suprimidos).toEqual([]); expect(sinDato).toEqual([]);
});
it('C2 no dibuja como cero una celda suprimida y sombrea su periodo', () => {
const data: IndicadorDatos = { ...base, contrato: 'C2', filas: [c2('2024-01', 'A', 5, 0), c2('2024-02', 'A', null, 0, 1), c2('2024-03', 'A', 0, 0)] };
const { figure, suprimidos } = historicoFigura(data, 'claro');
expect(figure.data[0]['y']).toEqual([5, null, 0]);
expect(suprimidos).toEqual(['feb 2024']);
expect(figure.layout['shapes']).toEqual([expect.objectContaining({ x0: .5, x1: 1.5 })]);
});
it('C1 con grupos adicionales dibuja la línea del total', () => {
// Pins down: a measure that publishes one group per alteration next to its total (TEA's EEG result) gets its
// history from the total's row of each period. Fails if the other groups' rows count as a second row of the
// period («Filas ambiguas»), or if two rows of the total stop being refused.
const grupos = { TOTAL: 'Total', ritmo_posterior: 'Ritmo posterior' };
const filas = base.periodos.flatMap(p => [{ ...c1(p, 40), grupo: 'TOTAL' }, { ...c1(p, 10), grupo: 'ritmo_posterior' }]);
const data: IndicadorDatos = { ...base, contrato: 'C1', grupos, filas };
expect(traza(data, 1).y).toEqual([40, 40, 40]);
expect(() => historicoFigura({ ...data, filas: [...filas, { ...c1('2024-01', 5), grupo: 'TOTAL' }] }, 'claro')).toThrow('Filas ambiguas');
});
it('C1 es una línea que no cruza huecos y su banda tampoco', () => {
const data: IndicadorDatos = { ...base, contrato: 'C1', filas: [c1('2024-01', 40), c1('2024-02', null, 1), c1('2024-03', 60)] };
const { suprimidos, figure } = historicoFigura(data, 'claro');
expect(traza(data, 1).y).toEqual([40, null, 60]);
expect(traza(data, 0).x).toEqual(['ene 2024', 'ene 2024', null, 'mar 2024', 'mar 2024']);
expect(traza(data, 0).y).toEqual([45, 35, null, 65, 55]);
expect(suprimidos).toEqual(['feb 2024']);
expect(figure.layout['barmode']).toBeUndefined();
expect((figure.layout['yaxis'] as { range: number[] }).range).toEqual([0, 100]);
});
it('C3r muestra la mediana con la banda entre cuartiles y distingue sin dato de suprimido', () => {
const data: IndicadorDatos = { ...base, periodos: ['2024-01', '2024-02'], contrato: 'C3r', filas: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 20, q1: 10, q3: 30 }] };
const { sinDato, suprimidos } = historicoFigura(data, 'claro');
expect(traza(data, 1).y).toEqual([20, null]);
expect(traza(data, 0).y).toEqual([30, 10]);
expect(sinDato).toEqual(['feb 2024']); expect(suprimidos).toEqual([]);
});
it('las líneas usan el verde legible en cada tema', () => {
const data: IndicadorDatos = { ...base, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) };
const color = (tema: 'claro' | 'oscuro') => (historicoFigura(data, tema).figure.data[1]['line'] as { color: string }).color;
expect(color('claro')).toBe('#6A8000'); expect(color('oscuro')).toBe('#A8C243');
});
it('escribe los periodos con mes y año', () => {
expect(etiquetaPeriodo('2024-03')).toBe('mar 2024');
expect(etiquetaPeriodo('2024-S2')).toBe('2024 S2');
});
it('el porcentaje en proceso suma las etapas antes del EEG sobre todos los niños en el tamizaje', () => {
const fila = (periodo: string, categoria: string, n: number) => ({ periodo, categoria, n, suprimido: 0 });
const { figure } = enProcesoFigura({ ...base, periodos: ['2024-01', '2024-02'], contrato: 'C2', filas: [
fila('2024-01', 'EEG', 10), fila('2024-01', 'SOLO_MCHAT', 10), fila('2024-01', 'PSICOLOGIA', 10), fila('2024-01', 'NEUROPEDIATRIA', 10),
fila('2024-02', 'EEG', 30), fila('2024-02', 'SOLO_MCHAT', 5), fila('2024-02', 'PSICOLOGIA', 5), fila('2024-02', 'NEUROPEDIATRIA', 0)] }, 'claro');
expect(figure.data[0]['y']).toEqual([75, 25]);
expect(figure.data[0]['x']).toEqual(['ene 2024', 'feb 2024']);
});
it('una escala compartida fija el máximo de las medianas', () => {
const data: IndicadorDatos = { ...base, periodos: ['2024-01'], contrato: 'C3r', filas: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 20, q1: 10, q3: 30 }] };
expect((historicoFigura(data, 'claro', { yMax: 90 }).figure.layout['yaxis'] as { range: number[] }).range).toEqual([0, 90]);
expect((historicoFigura(data, 'claro').figure.layout['yaxis'] as { range?: number[] }).range).toBeUndefined();
});
it('M21 y M22 no usan verde en sus líneas', () => {
const color = (id: string) => (historicoFigura({ ...base, id, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) }, 'claro').figure.data[1]['line'] as { color: string }).color;
expect(color('M21_diagnosticados_con_eeg')).toBe('#2F6DB3'); expect(color('M22_diagnosticados_sin_eeg')).toBe('#A23E8C');
});
it('rechaza contratos sin representación y filas ambiguas', () => {
expect(() => historicoFigura({ ...base, contrato: 'C9', filas: [] }, 'claro')).toThrow('no soportada');
expect(() => historicoFigura({ ...base, contrato: 'C1', filas: [c1('2024-01', 1), c1('2024-01', 2)] }, 'claro')).toThrow('ambiguas');
});
});
describe('Pestaña Histórico', () => {
let http: HttpTestingController;
let fixture: ComponentFixture<IndicadoresHistorico>;
const catalog: Indicador[] = [{ id: 'm1', titulo: 'Uno', contrato: 'C1', figuras: [], tipos_periodo: ['semestre', 'mes'] }];
const periodos = { id: 'm1', version: '1', periodos: [
{ periodo: '2024-01', tipo: 'mes', report_id: 1, periodo_inicio: '2024-01-01', periodo_fin: '2024-02-01', fecha_corte: '2024-03-01', generado_en: '2024-03-01T00:00:00+00:00' },
{ periodo: '2024-02', tipo: 'mes', report_id: 2, periodo_inicio: '2024-02-01', periodo_fin: '2024-03-01', fecha_corte: '2024-03-01', generado_en: '2024-03-01T00:00:00+00:00' },
{ periodo: '2024-S1', tipo: 'semestre', report_id: 3, periodo_inicio: '2024-01-01', periodo_fin: '2024-07-01', fecha_corte: '2024-08-01', generado_en: '2024-08-01T00:00:00+00:00' },
] };
const datos = (tipo: string, ps: string[]) => ({ id: 'm1', contrato: 'C1', tipo_periodo: tipo, periodos: ps, filas: ps.map(p => c1(p, 50)) });
const datosUrl = '/tea/indicadores/m1/datos';
const render = () => { TestBed.tick(); fixture.detectChanges(); };
const datos_ = (tipo: string, ps: string[]) => datos(tipo, ps);
const abrir_ = () => { fixture.componentRef.setInput('active', true); render(); http.expectOne('/tea/indicadores/m1/periodos').flush(periodos); http.expectOne(r => r.url === datosUrl).flush(datos('mes', ['2024-01', '2024-02'])); render(); };
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
http = TestBed.inject(HttpTestingController);
fixture = TestBed.createComponent(IndicadoresHistorico);
fixture.componentRef.setInput('dominio', 'tea');
fixture.componentRef.setInput('catalog', catalog);
fixture.componentRef.setInput('tema', 'claro');
render();
});
afterEach(() => http.verify());
const abrir = () => {
fixture.componentRef.setInput('active', true); render();
http.expectOne('/tea/indicadores/m1/periodos').flush(periodos);
};
it('no consulta hasta abrir la pestaña y entonces pide todos los periodos de una vez', () => {
http.expectNone(() => true);
abrir();
const request = http.expectOne(r => r.url === datosUrl);
expect(request.request.params.get('periodos')!.split(',').sort()).toEqual(['2024-01', '2024-02']);
request.flush(datos('mes', ['2024-01', '2024-02'])); render();
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('ene 2024 a feb 2024 (2 meses)');
});
it('cada intervalo se consulta una vez y cambiar de tema no vuelve a consultar', () => {
abrir();
http.expectOne(r => r.url === datosUrl).flush(datos('mes', ['2024-01', '2024-02'])); render();
fixture.componentInstance.tipo.set('semestre'); render();
const semestre = http.expectOne(r => r.url === datosUrl);
expect(semestre.request.params.get('periodos')).toBe('2024-S1');
semestre.flush(datos('semestre', ['2024-S1'])); render();
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('2024 S1 (1 semestre)');
fixture.componentInstance.tipo.set('mes'); render();
fixture.componentRef.setInput('tema', 'oscuro'); render();
http.expectNone(() => true);
});
it('el selector ofrece pasos de cinco en la unidad elegida y recorta a los periodos más recientes sin consultar', () => {
const c = fixture.componentInstance;
const meses = Array.from({ length: 12 }, (_, i) => '2024-' + String(i + 1).padStart(2, '0'));
const semestres = ['2020-S1', '2020-S2', '2021-S1', '2021-S2', '2022-S1', '2022-S2'];
fixture.componentRef.setInput('active', true); render();
http.expectOne('/tea/indicadores/m1/periodos').flush({ id: 'm1', periodos: [...meses.map(periodo => ({ periodo, tipo: 'mes' })), ...semestres.map(periodo => ({ periodo, tipo: 'semestre' }))] });
http.expectOne(r => r.url === datosUrl).flush(datos('mes', meses)); render();
expect(c.opciones().map(o => o.etiqueta)).toEqual(['Últimos 5 meses', 'Últimos 10 meses', 'Todos (12 meses)', 'Personalizado…']);
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('ene 2024 a dic 2024 (12 meses)');
c.elegirVentana(5); render();
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('ago 2024 a dic 2024 (5 meses)');
http.expectNone(() => true);
c.tipo.set('semestre'); render();
expect(c.ventana()).toBe(0);
http.expectOne(r => r.url === datosUrl).flush(datos('semestre', semestres)); render();
expect(c.opciones().map(o => o.etiqueta)).toEqual(['Últimos 5 semestres', 'Todos (6 semestres)', 'Personalizado…']);
c.tipo.set('mes'); render();
expect(c.ventana()).toBe(5);
http.expectNone(() => true);
});
it('agrupa los tres pasos de tiempo y añade el porcentaje en proceso tras los casos', () => {
const items: Indicador[] = ['M28_casos_por_estado', 'M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico']
.map(id => ({ id, titulo: id, contrato: id.startsWith('M28') ? 'C2' : 'C3r', figuras: [], tipos_periodo: ['mes'] }));
fixture.componentRef.setInput('catalog', items); fixture.componentRef.setInput('active', true); render();
for (const { id } of items) http.expectOne(`/tea/indicadores/${id}/periodos`).flush({ id, periodos: [{ periodo: '2024-01', tipo: 'mes' }] });
for (const { id } of items) {
const c2 = id.startsWith('M28');
http.expectOne(r => r.url === `/tea/indicadores/${id}/datos`).flush({ id, contrato: c2 ? 'C2' : 'C3r', tipo_periodo: 'mes', periodos: ['2024-01'],
filas: c2 ? [{ periodo: '2024-01', categoria: 'EEG', n: 3, orden: 0, suprimido: 0 }, { periodo: '2024-01', categoria: 'SOLO_MCHAT', n: 1, orden: 1, suprimido: 0 }, { periodo: '2024-01', categoria: 'PSICOLOGIA', n: 0, orden: 2, suprimido: 0 }, { periodo: '2024-01', categoria: 'NEUROPEDIATRIA', n: 0, orden: 3, suprimido: 0 }]
: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 5, q1: 2, q3: id.startsWith('M25') ? 100 : 10 }] });
}
render();
const paneles = fixture.componentInstance.paneles();
expect(paneles.map(p => p.item.id)).toEqual(['M28_casos_por_estado', 'en_proceso', 'tiempos']);
const grupo = paneles[2] as Extract<(typeof paneles)[number], { estado: 'listo' }>;
expect(grupo.pasos!.map(p => (p.figura.figure.layout['yaxis'] as { range: number[] }).range[1])).toEqual([105, 105, 105]);
expect(fixture.nativeElement.querySelectorAll('.pasos section')).toHaveLength(3);
});
it('Personalizado abre el diálogo con los periodos del intervalo y muestra solo los elegidos', async () => {
const c = fixture.componentInstance;
const cerrar = new Subject<string[] | undefined>();
const abrir = vi.spyOn(TestBed.inject(MatDialog), 'open').mockReturnValue({ afterClosed: () => cerrar } as never);
abrir_();
expect(c.opciones().at(-1)!.etiqueta).toBe('Personalizado…');
c.elegirVentana(-1);
const datos = abrir.mock.calls[0][1]!.data as PeriodosDialogoDatos;
expect(datos).toEqual({ tipo: 'mes', periodos: ['2024-01', '2024-02'], elegidos: ['2024-01', '2024-02'] });
// Cancelling changes nothing.
cerrar.next(undefined); render();
expect(c.ventana()).toBe(0);
c.elegirVentana(-1);
cerrar.next(['2024-02']); render();
expect(c.ventana()).toBe(-1);
expect(c.opciones().at(-1)!.etiqueta).toBe('Personalizado (1 mes)');
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('feb 2024 (1 mes, elegidos)');
// The other granularity keeps its own choice.
c.tipo.set('semestre'); render();
expect(c.ventana()).toBe(0);
http.expectOne(r => r.url === datosUrl).flush(datos_('semestre', ['2024-S1'])); render();
c.tipo.set('mes'); render();
expect(c.ventana()).toBe(-1);
http.expectNone(() => true);
});
it('avisa del error sin perder la pestaña y reintenta', () => {
abrir();
http.expectOne(r => r.url === datosUrl).flush({}, { status: 500, statusText: 'Error' }); render();
expect(fixture.nativeElement.querySelector('[role="alert"]')).not.toBeNull();
fixture.nativeElement.querySelector('[role="alert"] button').click(); render();
http.expectOne(r => r.url === datosUrl).flush(datos('mes', ['2024-01', '2024-02'])); render();
expect(fixture.nativeElement.querySelector('[role="alert"]')).toBeNull();
expect(fixture.nativeElement.querySelector('app-plotly-chart')).not.toBeNull();
});
it('un indicador sin reportes del intervalo lo dice sin consultar sus datos', () => {
fixture.componentRef.setInput('active', true); render();
http.expectOne('/tea/indicadores/m1/periodos').flush({ ...periodos, periodos: [periodos.periodos[2]] }); render();
http.expectNone(r => r.url === datosUrl);
expect(fixture.nativeElement.textContent).toContain('Sin reportes publicados');
});
});
describe('Diálogo de periodos de Histórico', () => {
it('el diálogo agrupa por año, no aplica sin periodos y devuelve los elegidos en orden', () => {
const cierre = vi.fn();
TestBed.configureTestingModule({ providers: [{ provide: MAT_DIALOG_DATA, useValue: { tipo: 'mes', periodos: ['2023-12', '2024-01', '2024-02'], elegidos: ['2024-02'] } }, { provide: MatDialogRef, useValue: { close: cierre } }] });
const dialogo = TestBed.createComponent(IndicadoresHistoricoPeriodos);
dialogo.detectChanges();
const root: HTMLElement = dialogo.nativeElement;
expect(Array.from(root.querySelectorAll('legend')).map(l => l.textContent)).toEqual(['2023', '2024']);
expect(root.textContent).toContain('dic 2023');
expect(root.querySelector('.cuenta')!.textContent).toBe('1 mes elegido');
const aplicar = Array.from(root.querySelectorAll('button')).find(b => b.textContent?.trim() === 'Aplicar')!;
dialogo.componentInstance.elegidos.set([]); dialogo.detectChanges();
expect(aplicar.disabled).toBe(true);
dialogo.componentInstance.alternar('2024-01'); dialogo.componentInstance.alternar('2023-12'); dialogo.detectChanges();
aplicar.click();
expect(cierre).toHaveBeenCalledWith(['2023-12', '2024-01']);
});
});
@@ -1,239 +0,0 @@
import { Component, computed, DestroyRef, effect, inject, input, signal, untracked, viewChild } 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 { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelect, MatSelectModule } from '@angular/material/select';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { catchError, forkJoin, map, Observable, of, Subject, switchMap } from 'rxjs';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { cronologico, enProcesoFigura, etiquetaPeriodo, historicoFigura, HistoricoFigura } from './indicadores-historico-figures';
import { httpMessage } from './indicadores-http';
import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos';
import { IndicadoresPeriodos } from './indicadores-periodos';
import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
import { IndicadoresService } from './indicadores.service';
const unidad = (tipo: TipoPeriodo, n: number) => tipo === 'mes' ? (n === 1 ? 'mes' : 'meses') : (n === 1 ? 'semestre' : 'semestres');
type Carga = { estado: 'listo'; datos: IndicadorDatos } | { estado: 'vacio' } | { estado: 'error'; mensaje: string };
type Panel = { item: Pick<Indicador, 'id' | 'titulo' | 'contrato'>; rango?: string } & (
{ estado: 'cargando' | 'vacio' } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] });
const TIEMPOS = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico'];
const CASOS = 'M28_casos_por_estado';
const PERSONALIZADO = -1;
// The screening steps go together as small charts, and the case counts are followed by their in-process share.
function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): Panel[] {
const pasos = TIEMPOS.map(id => paneles.find(p => p.item.id === id));
const listos = pasos.every(p => p?.estado === 'listo');
return paneles.flatMap((panel): Panel[] => {
if (listos && panel.item.id === TIEMPOS[0] && panel.estado === 'listo') {
const figuras = pasos.map(p => ({ titulo: p!.item.titulo, figura: (p as Extract<Panel, { estado: 'listo' }>).figura }));
const notas = (campo: 'suprimidos' | 'sinDato') => [...new Set(figuras.flatMap(f => f.figura[campo]))];
return [{ ...panel, item: { id: 'tiempos', titulo: 'Tiempos de tamizaje por paso', contrato: 'C3r' }, pasos: figuras,
figura: { ...panel.figura, comoLeer: 'La línea es la mediana de días de cada paso y la banda va del primer al tercer cuartil. Las tres usan la misma escala. Las medianas de los pasos no tienen que sumar la del total.',
suprimidos: notas('suprimidos'), sinDato: notas('sinDato') } }];
}
if (listos && TIEMPOS.includes(panel.item.id)) return [];
if (panel.item.id === CASOS && panel.estado === 'listo' && panel.datos) {
return [panel, { item: { id: 'en_proceso', titulo: 'Porcentaje de niños en proceso', contrato: 'C1' }, rango: panel.rango, estado: 'listo', figura: enProcesoFigura(panel.datos, tema) }];
}
return [panel];
});
}
// Evolution of each indicator: the granularity and how many of the latest periods to show.
// Nothing is requested until the tab is first opened, and each granularity is requested once.
@Component({
selector: 'app-indicadores-historico',
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
template: `
<div class="controles">
<span id="historico-intervalo">Intervalo de análisis</span>
<mat-button-toggle-group aria-labelledby="historico-intervalo" hideSingleSelectionIndicator [value]="tipo()" (change)="tipo.set($event.value)">
<mat-button-toggle value="mes">Mensual</mat-button-toggle>
<mat-button-toggle value="semestre">Semestral</mat-button-toggle>
</mat-button-toggle-group>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Periodos a mostrar</mat-label>
<mat-select #selector [value]="ventana()" (selectionChange)="elegirVentana($event.value)">
@for (opcion of opciones(); track opcion.valor) { <mat-option [value]="opcion.valor">{{ opcion.etiqueta }}</mat-option> }
</mat-select>
</mat-form-field>
@if (ventana() === PERSONALIZADO) { <button type="button" mat-stroked-button (click)="abrirPersonalizado()">Cambiar periodos</button> }
</div>
<div class="paneles">
@for (panel of paneles(); track panel.item.id) {
<article class="panel" [class.ancho]="panel.estado === 'listo' && panel.pasos" [attr.aria-busy]="panel.estado === 'cargando'">
<h2>{{ panel.item.titulo }}</h2>
@if (panel.rango) { <p class="rango">{{ panel.rango }}</p> }
@switch (panel.estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + panel.item.titulo" /> }
@case ('vacio') { <p role="status">Sin reportes publicados para este intervalo de análisis.</p> }
@case ('error') {
<div role="alert"><p>{{ panel.mensaje }}</p>
<button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button></div>
}
@case ('listo') {
@if (panel.pasos; as pasos) {
<div class="pasos">
@for (paso of pasos; track paso.titulo) {
<section><h3>{{ paso.titulo }}</h3>
<app-plotly-chart [style.--plot-height]="'340px'" [showNotes]="false" [figure]="paso.figura.figure" [label]="'Histórico de ' + paso.titulo + (panel.rango ? ', ' + panel.rango : '')" />
</section>
}
</div>
} @else {
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="panel.figura.figure"
[label]="'Histórico de ' + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" />
}
<p class="nota">{{ panel.figura.comoLeer }}</p>
@if (panel.figura.suprimidos.length) {
<p class="nota">Datos suprimidos, sombreados en la figura: {{ panel.figura.suprimidos.join(', ') }}. @if (panel.item.contrato === 'C2') {El total de esos periodos está incompleto.}</p>
}
@if (panel.figura.sinDato.length) { <p class="nota">Sin dato: {{ panel.figura.sinDato.join(', ') }}.</p> }
}
}
</article>
}
</div>
`,
styles: `
:host { display: block; min-width: 0; }
.controles { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); margin-bottom: var(--issste-space-6); padding: var(--issste-space-3) var(--issste-space-6);
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
.paneles { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
@container dashboard (min-width: 1304px) { .paneles { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
p { margin: var(--issste-space-3) 0 0; }
.rango, .nota { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
app-plotly-chart { margin-top: var(--issste-space-3); }
.panel.ancho { grid-column: 1 / -1; }
.pasos { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
@container dashboard (min-width: 960px) { .pasos { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
h3 { margin: 0; font: var(--mat-sys-title-small); }
mat-form-field { min-width: 18rem; }
`,
})
export class IndicadoresHistorico {
readonly dominio = input.required<Dominio>();
readonly catalog = input.required<readonly Indicador[]>();
readonly tema = input.required<Tema>();
readonly active = input(false);
readonly tipo = signal<TipoPeriodo>('mes');
// How many of the latest periods to show, per granularity; 0 shows them all.
private readonly ventanas = signal<Partial<Record<TipoPeriodo, number>>>({});
readonly ventana = computed(() => this.ventanas()[this.tipo()] ?? 0);
readonly PERSONALIZADO = PERSONALIZADO;
// The periods the user picked in the dialog, per granularity.
private readonly personalizados = signal<Partial<Record<TipoPeriodo, readonly string[]>>>({});
private readonly dialogo = inject(MatDialog);
private readonly selector = viewChild<MatSelect>('selector');
// Every period published for the granularity by any indicator.
private readonly disponibles = computed(() => cronologico(Object.values(this.cargas()[this.tipo()] ?? {})
.flatMap(carga => carga.estado === 'listo' ? carga.datos.periodos : [])));
// The periods on screen, out of those an indicator publishes.
private recortar(periodos: readonly string[]) {
const orden = cronologico(periodos), ventana = this.ventana();
if (ventana !== PERSONALIZADO) return orden.slice(-ventana);
const elegidos = this.personalizados()[this.tipo()] ?? [];
return orden.filter(p => elegidos.includes(p));
}
private readonly service = inject(IndicadoresService);
private readonly periodos = inject(IndicadoresPeriodos);
private readonly cargas = signal<Partial<Record<TipoPeriodo, Record<string, Carga>>>>({});
private readonly solicitudes = new Subject<{ tipo: TipoPeriodo; items: readonly Indicador[] }>();
private solicitada?: string;
private catalogoCargado?: readonly Indicador[];
// Steps of five, up to what the indicator with the most periods has published.
readonly opciones = computed(() => {
const tipo = this.tipo();
const total = Math.max(0, ...Object.values(this.cargas()[tipo] ?? {}).map(carga => carga.estado === 'listo' ? carga.datos.periodos.length : 0));
const opciones = [];
for (let n = 5; n < total; n += 5) opciones.push({ valor: n, etiqueta: `Últimos ${n} ${unidad(tipo, n)}` });
const elegidos = this.personalizados()[tipo]?.length;
return [...opciones, { valor: 0, etiqueta: total ? `Todos (${total} ${unidad(tipo, total)})` : 'Todos' },
...(total ? [{ valor: PERSONALIZADO, etiqueta: elegidos && this.ventana() === PERSONALIZADO ? `Personalizado (${elegidos} ${unidad(tipo, elegidos)})` : 'Personalizado…' }] : [])];
});
readonly paneles = computed<Panel[]>(() => {
const tipo = this.tipo(), cargas = this.cargas()[tipo], tema = this.tema();
// Top of the shared scale: the highest third quartile of the steps, in the periods on screen.
const maxTiempos = () => Math.max(1, ...TIEMPOS.flatMap(id => {
const carga = cargas?.[id];
if (carga?.estado !== 'listo') return [];
const visibles = this.recortar(carga.datos.periodos);
return carga.datos.filas.filter(f => visibles.includes(f['periodo'] as string)).map(f => (f['q3'] as number | null) ?? 0);
})) * 1.05;
const base: (Panel & { datos?: IndicadorDatos })[] = this.catalog().filter(item => item.tipos_periodo.includes(tipo)).map(item => {
const carga = cargas?.[item.id];
if (!carga) return { item, estado: 'cargando' };
if (carga.estado !== 'listo') return { item, ...carga };
const periodos = this.recortar(carga.datos.periodos);
if (!periodos.length) return { item, estado: 'vacio' };
const datos = { ...carga.datos, periodos, filas: carga.datos.filas.filter(fila => periodos.includes(fila['periodo'] as string)) };
const extremos = periodos.length === 1 ? etiquetaPeriodo(periodos[0]) : `${etiquetaPeriodo(periodos[0])} a ${etiquetaPeriodo(periodos[periodos.length - 1])}`;
const rango = `${extremos} (${periodos.length} ${unidad(tipo, periodos.length)}${this.ventana() === PERSONALIZADO ? ', elegidos' : ''})`;
try {
return { item, rango, estado: 'listo', figura: historicoFigura(datos, tema, TIEMPOS.includes(item.id) ? { yMax: maxTiempos(), pequena: true } : {}), datos };
} catch (error) {
return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' };
}
});
return agrupar(base, tema);
});
constructor() {
this.solicitudes.pipe(switchMap(({ tipo, items }) => forkJoin(items.filter(item => item.tipos_periodo.includes(tipo))
.map(item => this.cargar(item, tipo).pipe(map(carga => [item.id, carga] as const)))).pipe(map(cargas => ({ tipo, cargas })))),
takeUntilDestroyed(inject(DestroyRef))).subscribe(({ tipo, cargas }) => {
this.cargas.update(actual => ({ ...actual, [tipo]: Object.fromEntries(cargas) }));
});
effect(() => {
const tipo = this.tipo(), items = this.catalog();
if (!this.active() || !items.length) return;
untracked(() => {
if (this.catalogoCargado !== items) { this.catalogoCargado = items; this.cargas.set({}); this.solicitada = undefined; }
if (this.cargas()[tipo] || this.solicitada === tipo) return;
this.solicitada = tipo;
this.solicitudes.next({ tipo, items });
});
});
}
private cargar(item: Indicador, tipo: TipoPeriodo): Observable<Carga> {
return this.periodos.periodos(this.dominio(), item.id).pipe(
map(periodos => periodos.filter(p => p.tipo === tipo).map(p => p.periodo)),
switchMap((periodos): Observable<Carga> => periodos.length
? this.service.datos(this.dominio(), item.id, tipo, periodos).pipe(map(datos => ({ estado: 'listo', datos })))
: of({ estado: 'vacio' })),
catchError(error => of<Carga>({ estado: 'error', mensaje: httpMessage(error) })));
}
elegirVentana(valor: number) {
if (valor === PERSONALIZADO) { this.abrirPersonalizado(); return; }
this.ventanas.update(actual => ({ ...actual, [this.tipo()]: valor }));
}
abrirPersonalizado() {
const tipo = this.tipo(), periodos = this.disponibles();
// Starts from what's on screen, so the user only adjusts it.
const elegidos = this.ventana() === PERSONALIZADO ? this.personalizados()[tipo] ?? [] : periodos.slice(-this.ventana());
const data: PeriodosDialogoDatos = { tipo, periodos, elegidos };
this.dialogo.open<IndicadoresHistoricoPeriodos, PeriodosDialogoDatos, string[]>(IndicadoresHistoricoPeriodos, { data, width: 'min(40rem, 92vw)', maxHeight: '85vh' })
.afterClosed().subscribe(resultado => {
if (resultado?.length) {
this.personalizados.update(actual => ({ ...actual, [tipo]: resultado }));
this.ventanas.update(actual => ({ ...actual, [tipo]: PERSONALIZADO }));
}
// Cancelled, the selector goes back to what's on screen.
this.selector()?.writeValue(this.ventana());
});
}
reintentar() {
const tipo = this.tipo();
this.solicitada = tipo;
this.cargas.update(({ [tipo]: _, ...resto }) => resto);
this.solicitudes.next({ tipo, items: this.catalog() });
}
}
@@ -33,8 +33,9 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
http = TestBed.inject(HttpTestingController);
if (domain !== 'tea') { http.expectOne('/tea/indicadores').flush([]); page.changeDominio(domain); }
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
// The anchor shares the catalog inventory request; availability runs four at a time.
expect(flushPeriodos(() => [...periods].reverse().map(periodo => ({ periodo, tipo: 'semestre' })))).toBe(items.length);
const inventory = http.match(r => r.url.endsWith('/periodos'));
expect(inventory).toHaveLength(items.length); // The anchor shares the catalog inventory request.
inventory.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [...periods].reverse().map(periodo => ({ periodo, tipo: 'semestre' })) }));
fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
@@ -44,13 +45,6 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
periodo: period, grupo: d.contrato === 'C1' && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: value, suprimido: 0,
valor: 50, numerador: 5, denominador: 10, mediana: 2, q1: 1, q3: 3, unidad: 'dias' }] };
}
function flushPeriodos(periodos: () => unknown[]) {
let flushed = 0;
for (let pending = http.match(r => r.url.endsWith('/periodos')); pending.length; pending = http.match(r => r.url.endsWith('/periodos'))) {
pending.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: periodos() })); flushed += pending.length;
}
return flushed;
}
function request(period: string) { return http.expectOne(r => r.url.endsWith(`/${definitions[0].id}/datos`) && r.params.get('periodos') === period); }
// Regression assertions below target the original KPI contracts. The added lab
// consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts.
@@ -66,15 +60,11 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); }
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; }
// The shared request queue runs four at a time: flushing a batch starts the next.
function flushPanels(period: string, expected = definitions.length - 1) {
let flushed = 0;
for (let requests = originalRequests(); requests.length; requests = originalRequests()) {
requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(period);
const index = definitions.findIndex(d => r.request.url.endsWith(`/${d.id}/datos`)); r.flush(data(index, period)); });
flushed += requests.length;
}
expect(flushed).toBe(expected);
const requests = originalRequests();
expect(requests).toHaveLength(expected);
requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(period);
const index = definitions.findIndex(d => r.request.url.endsWith(`/${d.id}/datos`)); r.flush(data(index, period)); });
fixture.detectChanges();
}
function choose() {
@@ -89,7 +79,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
const ongoing = request(periods[0]);
for (const section of ['seguimiento', 'datos', 'resumen', 'datos'] as const) {
page.changeSection(section); fixture.detectChanges();
for (const req of http.match(r => r.url === '/cacu/seguimiento' || r.url === '/tea/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' });
for (const req of http.match(r => r.url === '/cacu/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' });
expect(page.initialPeriodState()).toBe('loading');
expect(ongoing.cancelled).toBe(false);
http.expectNone(() => true);
@@ -109,7 +99,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
editor().select([periods[2]]); fixture.detectChanges();
for (let i = 0; i < 3; i++) for (const section of ['seguimiento', 'datos', 'resumen'] as const) {
page.changeSection(section); fixture.detectChanges();
for (const req of http.match(r => r.url === '/cacu/seguimiento' || r.url === '/tea/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' });
for (const req of http.match(r => r.url === '/cacu/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' });
expect(page.filters).toBe(state); expect(page.filters!.applied).toBe(applied);
expect(editor().selectedPeriods).toEqual([periods[2]]);
expect(cards()).toContain(card); expect(card.selectedFigure).toBe('g');
@@ -146,11 +136,12 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(periods[0]); r.flush('', { status: 404, statusText: 'Missing' }); });
fixture.detectChanges(); expect(panels().slice(1).every(p => p.result().state === 'Sin datos del periodo')).toBe(true); http.expectNone(() => true);
});
it('aplicación manual posterior prevalece sin repetir la búsqueda', () => {
it('aplicación manual posterior y Todos prevalecen sin repetir la búsqueda', () => {
choose(); editor().select([periods[2]]); fixture.detectChanges(); http.expectNone(() => true);
page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], definitions.length);
expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [periods[2]] });
expect(panels().every(p => !p.initialPresentation)).toBe(true); http.expectNone(() => true);
editor().changeMode('todos'); page.applyFilters(); fixture.detectChanges(); flushPanels(periods[0]);
expect(page.filters!.applied.selection.mode).toBe('todos'); expect(panels().every(p => !p.initialPresentation)).toBe(true); http.expectNone(() => true);
});
it('tema, ancho y representación no reinician el periodo ni la búsqueda', () => {
choose(); const applied = page.filters!.applied;
@@ -230,7 +221,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
const catalog = definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, tipos_periodo: ['semestre'], figuras: ['f'] }));
catalogs.set(target, catalog);
page.changeDominio(target); http.expectOne('/' + target + '/indicadores').flush(catalog); fixture.detectChanges();
flushPeriodos(() => [{ periodo: period, tipo: 'semestre' }]);
http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [{ periodo: period, tipo: 'semestre' }] }));
const payload = (index: number) => {
const value = data(0, period); value.id = definitions[index].id; value.contrato = definitions[index].contrato;
value.filas[0].grupo = definitions[index].contrato === 'C1' && target !== 'tea' ? 'total' : 'TOTAL'; return value;
@@ -21,14 +21,6 @@ describe.each(['tea', 'cacu', 'cama'] as const)('KPI %s', domain => {
expect(result.value).toBe('33.4'); expect(result.info).toContain('2 de 6');
expect(run(1, [{ ...total, grupo: c1Group, valor: 0, numerador: 0, denominador: 6 }]).value).toBe('0.0');
});
it('C1 con grupos adicionales publicados lee la fila de su grupo', () => {
// Pins down: the rows of the other groups a measure publishes (one per alteration) don't make the card
// unconsolidable; a row of a group nobody published still does. Fails if those rows are mixed into the total.
const rows = [{ ...total, grupo: c1Group, valor: 50, numerador: 3, denominador: 6 }, { ...total, grupo: 'ritmo_posterior', valor: 10, numerador: 1, denominador: 6 }];
const d = { ...data(domain, 1, rows), grupos: { [c1Group]: 'Total', ritmo_posterior: 'Ritmo posterior' } };
expect(kpiResult(d, definitions[domain][1], domain, applied).value).toBe('50.0');
expect(kpiResult({ ...d, grupos: { [c1Group]: 'Total' } }, definitions[domain][1], domain, applied).state).toBe('Selección no consolidable');
});
it('C3r conserva mediana cero y Q1/Q3, sin reglas provisionales en la tarjeta', () => {
const result = run(2, [{ ...total, mediana: 0, n: 5, q1: 0, q3: 7, unidad: 'dias' }]);
expect(result.value).toBe(0);
@@ -63,12 +55,9 @@ it('categorías incompletas nunca producen un total parcial', () => {
expect(kpiResult(d, KPI_BY_DOMAIN.cacu[0], 'cacu', applied).value).toBeUndefined();
});
it('TEA usa sus cinco indicadores destacados y su grupo C1 es TOTAL', () => {
it('TEA usa sus tres indicadores destacados y su grupo C1 es TOTAL', () => {
expect(KPI_BY_DOMAIN.tea.map(d => [d.id, d.contrato])).toEqual([
['M23_pacientes_evaluados', 'C2'], ['M24_confirmacion_diagnostico', 'C1'], ['M25_dias_mchat_diagnostico', 'C3r'],
['M21_diagnosticados_con_eeg', 'C1'], ['M22_diagnosticados_sin_eeg', 'C1']]);
const eeg = data('tea', 3, [{ ...total, grupo: 'TOTAL', valor: 62.3, numerador: 71, denominador: 114 }]);
expect(kpiResult(eeg, KPI_BY_DOMAIN.tea[3], 'tea', applied).info).toBe('71 de 114 pacientes con diagnóstico confirmado tienen un EEG de buena calidad.');
['M23_pacientes_evaluados', 'C2'], ['M24_confirmacion_diagnostico', 'C1'], ['M25_dias_mchat_diagnostico', 'C3r']]);
const d = data('tea', 1, [{ ...total, grupo: 'TOTAL', valor: 50, numerador: 3, denominador: 6 }]);
expect(kpiResult(d, KPI_BY_DOMAIN.tea[1], 'tea', applied)).toEqual({ state: 'Disponible', value: '50.0',
info: '3 de 6 pacientes con nota médica con diagnóstico CIE-10 F84.0.' });
@@ -1,12 +1,8 @@
import { Dominio, filasDelGrupo, IndicadorDatos } from './indicadores.models';
import { Dominio, IndicadorDatos } from './indicadores.models';
import { GlobalApplied } from './indicadores-memory';
import { percentNumber } from './indicadores-format';
export interface KpiDefinition {
id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; singleAppliedPeriod?: boolean;
// C1 only: replaces the domain's explanatory line when the numerator is not the domain's usual one.
c1Info?: (numerador: number, denominador: number) => string;
}
export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; singleAppliedPeriod?: boolean; }
// Same laboratory-result source used by PARES_TIEMPOS; diagnosis has its own ID.
export const CACU_RESULTADO_KPI: KpiDefinition = {
id: 'cacu_eu_tiempo_reporte', title: 'Días de toma a resultado', contrato: 'C3r', unit: 'días (mediana)', singleAppliedPeriod: true,
@@ -15,24 +11,11 @@ export const CACU_RESULTADO_KPI: KpiDefinition = {
// in indicadores_kit, except the C2 patient counts, whose card shows the sum of the categories
// (patients), not the distribution. If a TOML title changes, change it here too, until the
// cards read the `titulo` that the API already sends.
// M28's stages at the period's end: a child finishes the screening with a good EEG; the other stages are in process.
export const M28_COMPLETO = 'EEG';
export const M28_EN_PROCESO = ['SOLO_MCHAT', 'PSICOLOGIA', 'NEUROPEDIATRIA'];
// What only TEA's summary paragraph needs: the children by stage and the time of each screening step.
export const KPI_RESUMEN_TEA: KpiDefinition[] = [
{ id: 'M28_casos_por_estado', title: 'Niños en el tamizaje', contrato: 'C2', unit: 'pacientes' },
{ id: 'M26_dias_mchat_ados2', title: 'Tiempo de M-CHAT a ADOS-2', contrato: 'C3r', unit: 'días (mediana)' },
{ id: 'M27_dias_ados2_diagnostico', title: 'Tiempo de ADOS-2 a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
];
export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
tea: [
{ id: 'M23_pacientes_evaluados', title: 'Total de pacientes evaluados', contrato: 'C2', unit: 'pacientes' },
{ id: 'M24_confirmacion_diagnostico', title: 'Porcentaje de confirmación diagnóstica', contrato: 'C1', unit: '%' },
{ id: 'M25_dias_mchat_diagnostico', title: 'Tiempo de aplicación de M-CHAT (psicología) a diagnóstico positivo', contrato: 'C3r', unit: 'días (mediana)' },
{ id: 'M21_diagnosticados_con_eeg', title: 'Porcentaje de pacientes con diagnóstico de TEA con EEG', contrato: 'C1', unit: '%',
c1Info: (n, d) => `${n} de ${d} pacientes con diagnóstico confirmado tienen un EEG de buena calidad.` },
{ id: 'M22_diagnosticados_sin_eeg', title: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG', contrato: 'C1', unit: '%',
c1Info: (n, d) => `${n} de ${d} pacientes con diagnóstico confirmado no tienen todavía un EEG de buena calidad.` },
],
cacu: [
{ id: 'cacu_eu7', title: 'Pacientes evaluadas', contrato: 'C2', unit: 'pacientes' },
@@ -56,7 +39,7 @@ const C3R_INFO: Record<Dominio, (n: number, q1: number, q3: number) => string> =
cacu: (n, q1, q3) => `${n} citologías; primer cuartil: ${q1} días; tercer cuartil: ${q3} días.`,
cama: (n, q1, q3) => `${n} mastografías; Q1 a Q3: ${q1} a ${q3} días.`,
};
export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; categorias?: Record<string, number>; }
export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; }
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
const count = (v: unknown): v is number => finite(v) && Number.isSafeInteger(v) && v >= 0;
const unscoped = { state: 'Selección no consolidable', info: 'Elige un único periodo. No hay una regla aprobada para consolidar periodos, grupos o estratos.' };
@@ -72,9 +55,9 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai
if (data.periodos.length !== 1 || new Set(data.filas.map(row => row['periodo'])).size > 1) return unscoped;
const period = data.periodos[0];
if (applied.selection.mode === 'explicit' && (applied.selection.periodos.length !== 1 || applied.selection.periodos[0] !== period)) return unscoped;
const group = definition.contrato === 'C1' ? C1_GROUP[domain] : 'TOTAL';
const rows = definition.contrato === 'C1' ? filasDelGrupo(data, group) : data.filas;
const rows = data.filas;
if (!rows.length) return { state: 'Sin filas utilizables' };
const group = definition.contrato === 'C1' ? C1_GROUP[domain] : 'TOTAL';
if (rows.some(row => row['periodo'] !== period || row['grupo'] !== group || row['estrato'] != null)) return unscoped;
if (definition.contrato !== 'C2' && rows.length !== 1) return unscoped;
if (rows.some(row => finite(row['suprimido']) && row['suprimido'] !== 0)) return { state: 'Dato oculto por tamaño' };
@@ -91,11 +74,11 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai
if (!rows.every(row => count(row['n']))) return empty;
const value = rows.reduce((sum, row) => sum + (row['n'] as number), 0);
if (!count(value)) return empty;
return { state: 'Disponible', value, categorias: Object.fromEntries(rows.map(row => [row['categoria'] as string, row['n'] as number])), info: domain === 'cacu' ? 'Pacientes con citología tomada en el periodo.' : 'Conteo de pacientes únicos en el periodo.' };
return { state: 'Disponible', value, info: domain === 'cacu' ? 'Pacientes con citología tomada en el periodo.' : 'Conteo de pacientes únicos en el periodo.' };
}
if (definition.contrato === 'C1') {
if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100 || !count(row['numerador']) || !count(row['denominador']) || row['numerador'] > row['denominador']) return empty;
return { state: 'Disponible', value: percentNumber(row['valor']), info: (definition.c1Info ?? C1_INFO[domain])(row['numerador'], row['denominador']) };
return { state: 'Disponible', value: percentNumber(row['valor']), info: C1_INFO[domain](row['numerador'], row['denominador']) };
}
if (!finite(row['mediana']) || !count(row['n']) || (definition.id === CACU_RESULTADO_KPI.id && row['n'] === 0) || !finite(row['q1']) || !finite(row['q3']) || row['q1'] < 0 || row['q1'] > row['mediana'] || row['mediana'] > row['q3'] || row['unidad'] !== 'dias') return empty;
return { state: 'Disponible', value: row['mediana'], info: C3R_INFO[domain](row['n'], row['q1'], row['q3']) };
@@ -46,11 +46,11 @@ export type Compatibility = { compatible: true } | { compatible: false; reason:
export function filterCompatibility(applied: GlobalApplied | undefined, types: readonly TipoPeriodo[]): Compatibility {
if (!types.length) return { compatible: false, reason: 'El catálogo no declara capacidades temporales suficientes para consultar.' };
if (!applied) return { compatible: false, reason: 'No hay un filtro general aplicado.' };
if (!types.includes(applied.tipo)) return { compatible: false, reason: 'Esta figura no admite el intervalo de análisis ' + (applied.tipo === 'mes' ? 'mensual' : 'semestral') + ' del filtro general.' };
if (!types.includes(applied.tipo)) return { compatible: false, reason: 'Esta figura no admite el intervalo de tiempo ' + applied.tipo + ' del filtro general.' };
const mode = applied.selection.mode;
if (!validDraft(applied.selection, applied.tipo, [...types])) return { compatible: false, reason: mode === 'todos'
? 'Todos con reporte requiere semestre como primer intervalo de análisis publicado. Para meses elige un periodo.'
: 'Los periodos del filtro general no son válidos para este intervalo de análisis.' };
? 'Todos con reporte requiere semestre como primer intervalo de tiempo publicado. Para meses elige periodos explícitos.'
: 'Los periodos del filtro general no son válidos para este intervalo de tiempo.' };
return { compatible: true };
}
export function applyGlobal(state: GlobalFilterState, types: TipoPeriodo[]): boolean {
@@ -0,0 +1,432 @@
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { By } from '@angular/platform-browser';
import { IndicadoresPage } from './indicadores-page';
import { Indicador } from './indicadores.models';
import { identityElementId, indicatorIdentity } from './indicadores-identities';
import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing';
import fixtureData from './fixtures/cacu_seguimiento.json';
const item = (id: string, titulo: string): Indicador => ({ id, titulo, contrato: 'C1', figuras: ['f-' + id], tipos_periodo: ['semestre'] });
describe('UX-10 navegación lateral del catálogo gráfico', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
let page: IndicadoresPage;
let http: HttpTestingController;
beforeEach(() => {
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
TestBed.configureTestingModule({
imports: [IndicadoresPage],
providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider],
});
fixture = TestBed.createComponent(IndicadoresPage);
page = fixture.componentInstance;
http = TestBed.inject(HttpTestingController);
vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
});
afterEach(() => {
page.closeGraphicNavigation(false, false);
fixture.detectChanges();
http.match(request => request.url.endsWith('/seguimiento')).forEach(request => request.flush(fixtureData));
http.match(request => request.url.endsWith('/metadatos')).forEach(request => request.flush({}));
fixture.destroy();
http.verify();
vi.restoreAllMocks();
vi.unstubAllGlobals();
vi.useRealTimers();
});
async function load(items: Indicador[], domain: 'tea' | 'cacu' | 'cama' = 'tea') {
if (domain !== page.dominio) {
http.expectOne('/' + page.dominio + '/indicadores').flush([]);
fixture.detectChanges();
page.changeDominio(domain);
}
http.expectOne('/' + domain + '/indicadores').flush(items);
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
}
function trigger() { return fixture.nativeElement.querySelector('.graphic-navigation-trigger') as HTMLButtonElement | null; }
function optionButtons() { return Array.from(document.querySelectorAll<HTMLButtonElement>('#indicator-navigation-panel .panel-list button')); }
async function openPanel() {
const button = trigger()!;
button.focus();
button.click();
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
return button;
}
function expectNoFigureRequests() { http.expectNone(request => request.url.includes('/figuras/') || request.url.endsWith('/datos')); }
it.each(['tea', 'cacu', 'cama'] as const)('aparece solo en Resumen para el dominio %s', async domain => {
await load([item('chart', 'Indicador gráfico')], domain);
expect(trigger()).not.toBeNull();
page.changeSection('seguimiento'); fixture.detectChanges();
expect(trigger()).toBeNull();
page.changeSection('datos'); fixture.detectChanges();
expect(trigger()).toBeNull();
page.changeSection('resumen'); fixture.detectChanges();
page.fichaPacienteAbierta.set(true); fixture.detectChanges();
expect(trigger()).toBeNull();
page.fichaPacienteAbierta.set(false); fixture.detectChanges();
expect(trigger()).not.toBeNull();
expectNoFigureRequests();
});
it('toma únicamente títulos y orden del catálogo visible, sin agregar KPI ni nombres alternos', async () => {
const items = [item('a', 'Tasa visible exacta'), item('b', 'Distribución por edad')];
await load(items, 'cacu');
expect(page.showGraphicNavigation).toBe(true);
await openPanel();
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Tasa visible exacta', 'Distribución por edad']);
expect(optionButtons().map(button => button.getAttribute('aria-label'))).toEqual(['Tasa visible exacta', 'Distribución por edad']);
expect(optionButtons().some(button => button.textContent?.includes('Oportunidad') || button.textContent?.includes('destacado'))).toBe(false);
expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-panel').length).toBe(0);
expectNoFigureRequests();
});
it('presenta un popover compacto anclado al botón, sin backdrop ni bloqueo del scroll', async () => {
await load([item('a', 'Uno'), item('b', 'Título largo del indicador')]);
const button = trigger()!;
vi.spyOn(button, 'getBoundingClientRect').mockReturnValue(new DOMRect(8, 180, 48, 48));
const bodyOverflow = document.body.style.overflow;
await openPanel();
const panel = document.querySelector<HTMLElement>('.panel-shell')!;
expect(page.navigationPositions[0]).toEqual({ originX: 'start', overlayX: 'start', originY: 'center', overlayY: 'center' });
expect(panel.closest('.cdk-overlay-pane')).not.toBeNull();
expect(document.querySelector('.cdk-overlay-backdrop')).toBeNull();
expect(getComputedStyle(panel).maxHeight).toBe('min(58dvh, 32rem)');
expect(bodyOverflow).toBe(document.body.style.overflow);
expect(page.navigationScrollStrategy.constructor.name).toBe('RepositionScrollStrategy');
expectNoFigureRequests();
});
it('usa scroll interno en una lista extensa y se adapta al ancho disponible', async () => {
await load(Array.from({ length: 30 }, (_, index) => item('indicator-' + index, 'Indicador clínico ' + index)));
await openPanel();
const panel = document.querySelector<HTMLElement>('.panel-shell')!;
const list = panel.querySelector<HTMLElement>('.panel-list')!;
expect(optionButtons()).toHaveLength(30);
expect(getComputedStyle(panel).maxHeight).toBe('min(58dvh, 32rem)');
expect(getComputedStyle(list).overflowY).toBe('auto');
expect(getComputedStyle(panel.parentElement!).maxWidth).toBe('calc(100vw - 1rem)');
expectNoFigureRequests();
});
it('reubica el popover en viewports estrechos y conserva límites verticales', async () => {
await load([item('one', 'Indicador')]);
const previousWidth = window.innerWidth;
Object.defineProperty(window, 'innerWidth', { configurable: true, value: 320 });
try {
await openPanel();
const panel = document.querySelector<HTMLElement>('.panel-shell')!;
const host = panel.parentElement!;
expect(getComputedStyle(host).maxWidth).toBe('calc(100vw - 1rem)');
expect(page.navigationPositions).toEqual(expect.arrayContaining([
expect.objectContaining({ originX: 'end', overlayX: 'end' }),
expect.objectContaining({ originY: 'bottom', overlayY: 'bottom' }),
]));
expect(panel.closest('.cdk-overlay-pane')).not.toBeNull();
} finally {
Object.defineProperty(window, 'innerWidth', { configurable: true, value: previousWidth });
}
});
it('sigue el orden priorizado por búsqueda y fijación mientras el panel está abierto', async () => {
await load([item('one', 'Alfa'), item('two', 'Beta'), item('three', 'Gamma')]);
page.togglePinned(page.catalog()[2]);
fixture.detectChanges();
await openPanel();
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Gamma', 'Alfa', 'Beta']);
page.changeSearchQuery('beta');
fixture.detectChanges();
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Beta', 'Gamma', 'Alfa']);
page.changeSearchQuery('sin coincidencias');
fixture.detectChanges();
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Gamma', 'Alfa', 'Beta']);
page.searchQuery.set('');
page.catalog.set([item('updated', 'Versión actualizada'), item('two', 'Beta')]);
fixture.detectChanges();
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Versión actualizada', 'Beta']);
expectNoFigureRequests();
});
it('mantiene keys únicas para títulos duplicados y navega a la tarjeta elegida', async () => {
const items = [item('duplicate-a', 'Resultado clínico'), item('duplicate-b', 'Resultado clínico')];
await load(items, 'cama');
const scroll = vi.fn();
const focus = vi.spyOn(HTMLElement.prototype, 'focus');
for (const card of fixture.nativeElement.querySelectorAll('app-indicador-catalog-card')) {
card.scrollIntoView = scroll;
}
await openPanel();
expect(optionButtons()).toHaveLength(2);
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Resultado clínico', 'Resultado clínico']);
optionButtons()[1].click();
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
const targetId = identityElementId(indicatorIdentity('cama', 'duplicate-b'));
expect(scroll).toHaveBeenCalledOnce();
expect(scroll.mock.instances[0]).toBe(fixture.nativeElement.querySelector('#' + targetId));
expect(focus).toHaveBeenCalled();
expect(document.activeElement).toBe(fixture.nativeElement.querySelector('#' + targetId + ' h2'));
expectNoFigureRequests();
});
it('abre con foco dentro, expone el estado expandido y cierra restaurando el foco con Escape', async () => {
await load([item('one', 'Indicador')]);
const button = await openPanel();
expect(button.getAttribute('aria-expanded')).toBe('true');
expect(document.querySelector('nav[aria-label="Navegar a indicadores clínicos"]')).not.toBeNull();
expect(document.activeElement).toBe(optionButtons()[0]);
expect(document.querySelector('.cdk-focus-trap-anchor')).toBeNull();
document.querySelector('.panel-shell')!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', keyCode: 27, bubbles: true, cancelable: true }));
await fixture.whenStable();
fixture.detectChanges();
expect(page.navigationOpen()).toBe(false);
expect(button.getAttribute('aria-expanded')).toBe('false');
expect(document.activeElement).toBe(button);
expectNoFigureRequests();
});
it('cierra al pulsar fuera y mantiene el click externo disponible', async () => {
const bodyOverflow = document.body.style.overflow;
await load([item('one', 'Indicador')]);
await openPanel();
document.body.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
document.body.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
fixture.detectChanges();
expect(page.navigationOpen()).toBe(false);
expect(page.navigationClosing()).toBe(true);
expect(document.querySelector('app-indicadores-navegacion-panel')?.hasAttribute('inert')).toBe(true);
expect(document.querySelector('.cdk-overlay-pane.indicator-navigation-overlay:has(.panel-closing)')).not.toBeNull();
expect(document.body.style.overflow).toBe(bodyOverflow);
expectNoFigureRequests();
});
it('no conserva elementos al cambiar de dominio y elimina el encabezado y el botón X', async () => {
await load([item('one', 'TEA gráfico')]);
await openPanel();
expect(document.querySelector('#indicator-navigation-title')).toBeNull();
expect(document.querySelector('.panel-header')).toBeNull();
expect(document.querySelector('.panel-shell mat-icon')).toBeNull();
expect(document.querySelector('.panel-shell')?.querySelectorAll('button')).toHaveLength(1);
page.changeDominio('cacu');
http.expectOne('/cacu/indicadores').flush([item('new', 'CaCu clínico')]);
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
expect(page.navigationOpen()).toBe(false);
expect(trigger()).not.toBeNull();
await openPanel();
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['CaCu clínico']);
expect(optionButtons().some(button => button.textContent?.includes('TEA'))).toBe(false);
expectNoFigureRequests();
});
it('respeta movimiento reducido, enfoca la tarjeta y no solicita sus figuras desde el panel', async () => {
await load([item('lazy', 'Carga diferida')]);
const card = fixture.nativeElement.querySelector('app-indicador-catalog-card') as HTMLElement;
const scroll = vi.fn();
card.scrollIntoView = scroll;
vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true })));
await openPanel();
optionButtons()[0].click();
await fixture.whenStable(); fixture.detectChanges();
expect(scroll).toHaveBeenCalledWith({ behavior: 'instant', block: 'start' });
expect(fixture.debugElement.query(By.css('app-indicador-catalog-card'))?.componentInstance?.visible).toBe(false);
expectNoFigureRequests();
});
function pointer(target: Element, type: 'pointerenter' | 'pointerleave' | 'pointermove', pointerType = 'mouse', moved = true) {
const event = new Event(type);
Object.defineProperty(event, 'pointerType', { value: pointerType });
target.dispatchEvent(event);
// A real entry caused by mouse movement also dispatches pointermove. Layout-only entries don't.
if (type === 'pointerenter' && moved) {
const move = new Event('pointermove');
Object.defineProperty(move, 'pointerType', { value: pointerType });
target.dispatchEvent(move);
}
fixture.detectChanges();
}
function hoverDevice(enabled = true) {
vi.stubGlobal('matchMedia', vi.fn((query: string) => ({ matches: enabled && query === '(hover: hover) and (pointer: fine)' })));
}
it('abre por hover sin mover el foco y conserva el origen CDK oculto y su caja', async () => {
await load([item('a', 'Indicador')]);
hoverDevice();
const button = trigger()!;
const origin = fixture.debugElement.query(By.css('[cdkOverlayOrigin]')).nativeElement;
const rect = new DOMRect(8, 180, 48, 48);
vi.spyOn(button, 'getBoundingClientRect').mockReturnValue(rect);
const initialFocus = document.activeElement;
pointer(button, 'pointerenter');
expect(page.navigationOpen()).toBe(true);
expect(document.activeElement).toBe(initialFocus);
expect(trigger()).toBe(origin);
expect(getComputedStyle(button).opacity).toBe('0');
expect(getComputedStyle(button).pointerEvents).toBe('none');
expect(getComputedStyle(button).display).not.toBe('none');
expect(button.getBoundingClientRect()).toBe(rect);
expect(button.tabIndex).toBe(-1);
expect(optionButtons()).toHaveLength(1);
expectNoFigureRequests();
});
it('permite cruzar del disparador a cualquier opción y cancela el cierre al reingresar', async () => {
await load([item('a', 'Uno'), item('b', 'Dos')]);
hoverDevice(); vi.useFakeTimers();
pointer(trigger()!, 'pointerenter');
pointer(trigger()!, 'pointerleave');
vi.advanceTimersByTime(200);
expect(page.navigationOpen()).toBe(true);
const panel = document.querySelector('app-indicadores-navegacion-panel')!;
pointer(panel, 'pointerenter');
vi.advanceTimersByTime(300);
expect(page.navigationOpen()).toBe(true);
pointer(panel, 'pointerleave');
vi.advanceTimersByTime(200);
pointer(panel, 'pointerenter');
vi.advanceTimersByTime(500);
expect(page.navigationOpen()).toBe(true);
pointer(panel, 'pointerleave');
vi.advanceTimersByTime(229);
expect(page.navigationOpen()).toBe(true);
vi.advanceTimersByTime(1); fixture.detectChanges();
expect(page.navigationOpen()).toBe(false);
expect(page.navigationAttached()).toBe(true);
expect(document.querySelector('.panel-closing')).not.toBeNull();
vi.advanceTimersByTime(180); fixture.detectChanges();
expect(page.navigationAttached()).toBe(false);
expect(document.querySelector('.panel-shell')).toBeNull();
});
it.each(['touch', 'pen', 'mouse'])('sin hover real ignora %s y conserva la apertura por toque/clic', async pointerType => {
await load([item('a', 'Indicador')]);
hoverDevice(false);
pointer(trigger()!, 'pointerenter', pointerType);
expect(page.navigationOpen()).toBe(false);
trigger()!.dispatchEvent(new MouseEvent('click', { bubbles: true, detail: 1 }));
fixture.detectChanges();
expect(page.navigationOpen()).toBe(true);
page.toggleGraphicNavigation(new MouseEvent('click', { detail: 1 }));
expect(page.navigationOpen()).toBe(false);
});
it.each(['Enter', ' '])('abre con %s, enfoca la primera opción y deja salir el foco con Tab', async key => {
await load([item('a', 'Uno'), item('b', 'Dos')]);
trigger()!.focus();
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
trigger()!.dispatchEvent(event);
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
expect(event.defaultPrevented).toBe(true);
expect(document.activeElement).toBe(optionButtons()[0]);
const tab = new KeyboardEvent('keydown', { key: 'Tab', bubbles: true, cancelable: true });
optionButtons()[1].dispatchEvent(tab);
expect(tab.defaultPrevented).toBe(false);
expect(document.querySelector('.cdk-focus-trap-anchor')).toBeNull();
const outside = fixture.nativeElement.querySelector('[role="tab"]') as HTMLButtonElement;
outside.focus();
expect(document.activeElement).toBe(outside);
expectNoFigureRequests();
});
it('no cierra al salir el puntero si una opción conserva el foco de teclado', async () => {
await load([item('a', 'Indicador')]);
await openPanel();
vi.useFakeTimers();
pointer(document.querySelector('app-indicadores-navegacion-panel')!, 'pointerleave');
vi.advanceTimersByTime(500);
expect(page.navigationOpen()).toBe(true);
});
it('cierra con Escape aun cuando hover no haya trasladado el foco al panel', async () => {
await load([item('a', 'Indicador')]); hoverDevice();
pointer(trigger()!, 'pointerenter');
document.body.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, bubbles: true, cancelable: true }));
fixture.detectChanges();
expect(page.navigationOpen()).toBe(false);
expect(document.activeElement).toBe(trigger());
});
it('no espera animación al cerrar con movimiento reducido', async () => {
await load([item('a', 'Indicador')]);
vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true })));
await openPanel();
page.closeGraphicNavigation(); fixture.detectChanges();
expect(page.navigationAttached()).toBe(false);
expect(document.querySelector('.panel-shell')).toBeNull();
});
it('no reabre por entradas del puntero generadas al desmontar el overlay y admite un nuevo movimiento', async () => {
await load([item('a', 'Indicador')]); hoverDevice(); vi.useFakeTimers();
pointer(trigger()!, 'pointerenter');
page.closeGraphicNavigation(); fixture.detectChanges();
page.closeGraphicNavigation(); fixture.detectChanges();
pointer(trigger()!, 'pointerenter', 'mouse', false);
expect(page.navigationOpen()).toBe(false);
vi.advanceTimersByTime(180); fixture.detectChanges();
expect(page.navigationAttached()).toBe(false);
pointer(trigger()!, 'pointermove');
expect(page.navigationOpen()).toBe(true);
page.closeGraphicNavigation(false); fixture.detectChanges();
pointer(trigger()!, 'pointerenter');
vi.advanceTimersByTime(500); fixture.detectChanges();
expect(page.navigationOpen()).toBe(true);
expect(page.navigationClosing()).toBe(false);
});
it('cancela el cierre pendiente al cambiar de sección o dominio y al destruir', async () => {
await load([item('a', 'TEA')]); hoverDevice(); vi.useFakeTimers();
pointer(trigger()!, 'pointerenter'); pointer(trigger()!, 'pointerleave');
page.changeSection('datos'); fixture.detectChanges();
expect(page.navigationAttached()).toBe(false);
page.changeSection('resumen'); fixture.detectChanges();
pointer(trigger()!, 'pointerenter');
vi.advanceTimersByTime(500);
expect(page.navigationOpen()).toBe(true);
pointer(trigger()!, 'pointerleave');
page.changeDominio('cama');
http.expectOne('/cama/indicadores').flush([item('b', 'CaMa')]); fixture.detectChanges();
expect(page.navigationAttached()).toBe(false);
pointer(trigger()!, 'pointerenter');
vi.advanceTimersByTime(500);
expect(page.navigationOpen()).toBe(true);
pointer(trigger()!, 'pointerleave');
const clear = vi.spyOn(globalThis, 'clearTimeout');
const close = vi.spyOn(page, 'closeGraphicNavigation');
fixture.destroy();
expect(page.navigationAttached()).toBe(false);
expect(clear).toHaveBeenCalled();
const callsAtDestroy = close.mock.calls.length;
vi.advanceTimersByTime(500);
expect(close.mock.calls).toHaveLength(callsAtDestroy);
});
it('mantiene botones estables, títulos completos multilínea y transforma solo la etiqueta visual', async () => {
const title = 'Indicador clínico con un título extenso que puede ocupar varias líneas completas';
await load([item('a', title), item('b', 'Otro indicador')]);
await openPanel();
const button = optionButtons()[0];
expect(button.textContent?.trim()).toBe(title);
expect(getComputedStyle(button).minHeight).toBe('44px');
expect(getComputedStyle(button).whiteSpace).toBe('normal');
expect(getComputedStyle(button).transform).not.toContain('scale');
expect(button.querySelector('.option-label')).not.toBeNull();
expect(getComputedStyle(document.querySelector('.panel-list')!).overflowX).toBe('hidden');
const styles = Array.from(document.querySelectorAll('style')).map(style => style.textContent).join('\n');
expect(styles).toContain('button:focus-visible');
expect(styles).toContain('scale(1.02)');
expect(styles).toContain('scale(0.99)');
expect(styles).toContain('prefers-reduced-motion: reduce');
expect(styles).toContain('@starting-style');
});
});
@@ -0,0 +1,11 @@
<div class="panel-shell" id="indicator-navigation-panel" (keydown)="onKeydown($event)">
<nav class="panel-list" aria-label="Navegar a indicadores clínicos">
@if (items().length) {
<ul>
@for (item of items(); track item.key) {
<li><button mat-button type="button" [attr.aria-label]="item.titulo" (click)="seleccionar(item.key)"><span class="option-label">{{ item.titulo }}</span></button></li>
}
</ul>
}
</nav>
</div>
@@ -0,0 +1,20 @@
:host { display: block; width: min(20rem, calc(100vw - 1rem)); max-width: calc(100vw - 1rem); min-width: 0; color: var(--issste-text); }
.panel-shell { display: flex; flex-direction: column; width: 100%; max-height: min(58dvh, 32rem); min-height: 0; overflow: hidden; color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: 0 8px 28px rgb(8 24 57 / 24%); opacity: 1; transform: scale(1); transform-origin: left center; transition: opacity 180ms ease, transform 180ms cubic-bezier(.2, .8, .2, 1); }
@starting-style { .panel-shell { opacity: 0; transform: scale(.97); } }
:host(.panel-closing) { pointer-events: none; }
:host(.panel-closing) .panel-shell { opacity: 0; transform: scale(.97); }
.panel-list { flex: 0 1 auto; min-height: 0; overflow-y: auto; overflow-x: hidden; overscroll-behavior: contain; padding: .35rem .5rem; }
ul { list-style: none; margin: 0; padding: 0; }
li + li { margin-top: .1rem; }
li button { display: flex; width: 100%; min-height: 44px; height: auto; justify-content: flex-start; padding: .15rem .2rem; text-align: start; white-space: normal; line-height: 1.35; color: inherit; }
.option-label { display: block; width: 100%; min-width: 0; padding: .4rem; box-sizing: border-box; border-radius: .35rem; overflow-wrap: anywhere; transition: transform 180ms ease, background-color 180ms ease; }
button:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: -2px; }
.panel-list:has(button:focus-visible) button:not(:focus-visible) .option-label { transform: scale(.99); }
button:focus-visible .option-label { transform: scale(1.02); background: color-mix(in srgb, var(--issste-accent) 14%, transparent); }
@media (hover: hover) and (pointer: fine) {
.panel-list:has(button:hover) button:not(:hover):not(:focus-visible) .option-label { transform: scale(.99); }
button:hover .option-label { transform: scale(1.02); background: color-mix(in srgb, var(--issste-accent) 14%, transparent); }
}
@media (prefers-reduced-motion: reduce) {
.panel-shell, .option-label { transition: none; transform: none !important; }
}
@@ -0,0 +1,35 @@
import { Component, ElementRef, Input, Signal, inject, output } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
export interface IndicadorNavegacionItem {
key: string;
titulo: string;
}
@Component({
selector: 'app-indicadores-navegacion-panel',
imports: [MatButtonModule],
host: { '[class.panel-closing]': 'closing', '[attr.inert]': "closing ? '' : null" },
templateUrl: './indicadores-navegacion-panel.html',
styleUrl: './indicadores-navegacion-panel.scss',
})
export class IndicadoresNavegacionPanel {
@Input({ required: true }) items!: Signal<readonly IndicadorNavegacionItem[]>;
@Input() closing = false;
readonly selected = output<string>();
readonly closed = output<void>();
private readonly element = inject<ElementRef<HTMLElement>>(ElementRef);
focusFirstOption() { this.element.nativeElement.querySelector<HTMLButtonElement>('.panel-list button')?.focus({ preventScroll: true }); }
containsFocus() { return this.element.nativeElement.contains(this.element.nativeElement.ownerDocument.activeElement); }
onKeydown(event: KeyboardEvent) {
if (event.key !== 'Escape') return;
event.preventDefault();
event.stopPropagation();
this.closed.emit();
}
seleccionar(key: string) {
if (this.items().some(item => item.key === key)) this.selected.emit(key);
}
}
@@ -53,7 +53,7 @@ describe('UX-04 navegación Angular', () => {
const tea = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
load('tea', harness); harness.detectChanges();
const control = harness.routeDebugElement!.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
(harness.routeDebugElement!.componentInstance as IndicadoresPage).applyFilters(); harness.detectChanges();
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
control.year = '2025'; control.unit = 'S2'; control.add();
@@ -62,7 +62,7 @@ describe('UX-04 navegación Angular', () => {
const restored = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
const req = load('tea', harness);
expect(req.request.params.get('periodos')).toBe('2025-S1');
expect((harness.routeDebugElement!.componentInstance as IndicadoresPage).filters?.editors.semestre?.draft).toEqual({ mode: 'explicit', periodos: ['2025-S2'] });
expect((harness.routeDebugElement!.componentInstance as IndicadoresPage).filters?.editors.semestre?.draft).toEqual({ mode: 'explicit', periodos: ['2025-S1', '2025-S2'] });
expect(TestBed.inject(Router).url).toBe('/indicadores/tea');
});
it('un nuevo arranque conserva la URL de entrada y reinicia indicador, tema y filtros', async () => {
@@ -1,8 +1,8 @@
<section class="dashboard" [class.reporte-impresion]="preparandoReporte()" aria-labelledby="dashboard-title">
<section class="dashboard" aria-labelledby="dashboard-title">
<header>
@if (fichaPacienteAbierta()) {
<h1 id="dashboard-title">Ficha del paciente</h1>
<p>Consulta individual de seguimiento de {{ domainLabels[dominio] }}</p>
<p>Consulta individual de seguimiento de cáncer cervicouterino</p>
} @else {
<span class="domain">{{ domainTitles[dominio] }}, investigación</span>
<h1 id="dashboard-title">Indicadores</h1>
@@ -26,6 +26,27 @@
}
</div>
}
@if (showGraphicNavigation) {
<button #navigationTrigger cdkOverlayOrigin #navigationOrigin="cdkOverlayOrigin" class="graphic-navigation-trigger" mat-mini-fab type="button"
[class.graphic-navigation-trigger-expanded]="navigationOpen()" [tabIndex]="navigationOpen() ? -1 : 0"
[attr.aria-label]="navigationOpen() ? 'Cerrar navegación por indicadores' : 'Abrir navegación por indicadores'"
aria-controls="indicator-navigation-panel" [attr.aria-expanded]="navigationOpen()" (click)="toggleGraphicNavigation($event)"
(keydown)="navigationTriggerKeydown($event)" (pointerenter)="navigationPointerEnter($event)" (pointerleave)="navigationPointerLeave($event)"
(pointermove)="navigationPointerMove($event)">
<mat-icon aria-hidden="true">format_list_bulleted</mat-icon>
</button>
<ng-template cdkConnectedOverlay [cdkConnectedOverlayOrigin]="navigationOrigin"
[cdkConnectedOverlayOpen]="navigationAttached()" [cdkConnectedOverlayPositions]="navigationPositions"
[cdkConnectedOverlayScrollStrategy]="navigationScrollStrategy" [cdkConnectedOverlayViewportMargin]="8"
[cdkConnectedOverlayFlexibleDimensions]="true" [cdkConnectedOverlayPush]="true"
cdkConnectedOverlayPanelClass="indicator-navigation-overlay"
[cdkConnectedOverlayHasBackdrop]="false" (overlayOutsideClick)="closeGraphicNavigationFromOutside($event)"
(overlayKeydown)="navigationOverlayKeydown($event)">
<app-indicadores-navegacion-panel [items]="navigationItems" [closing]="navigationClosing()"
(pointerenter)="navigationPointerEnter($event)" (pointerleave)="navigationPointerLeave($event)" (focusout)="navigationFocusOut()"
(closed)="closeGraphicNavigation()" (selected)="selectGraphicNavigation($event)" />
</ng-template>
}
<div id="panel-resumen" class="section-panel" role="tabpanel" aria-labelledby="tab-resumen" tabindex="0" [hidden]="activeSection() !== 'resumen'">
@if (!catalogLoading() && filters; as state) {
@@ -55,11 +76,8 @@
@let kpis = opportunityKpis;
@if (kpis.length && !initialPeriodBlocked) {
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
@let resumen = teaResumenPeriodo;
<h2 id="kpi-section-title" class="section-title">{{ dominio === 'cacu' ? 'Indicadores de oportunidad' : resumen ? 'Resumen' : 'Indicadores destacados' }}</h2>
@if (resumen) { <app-tea-resumen-periodo [periodo]="resumen" [paneles]="kpiPanels()" /> }
<!-- With the summary the panels keep loading the data, but their cards are not shown. -->
<div class="kpi-grid" [class.kpi-grid-oculto]="resumen" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : 0)">
<h2 id="kpi-section-title" class="section-title">{{ dominio === 'cacu' ? 'Indicadores de oportunidad' : 'Indicadores destacados' }}</h2>
<div class="kpi-grid" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : 0)">
@for (definition of kpis; track dominio + ':' + definition.id) {
<app-indicador-kpi-panel [dominio]="dominio" [definition]="definition" [indicador]="kpiIndicator(definition.id)"
[applied]="filters?.applied" [availability]="availability()" [initialPresentation]="false" />
@@ -76,7 +94,7 @@
<div class="catalog-heading">
<h2 id="graphic-section-title" class="section-title">{{ dominio === 'cacu' ? 'Indicadores clínicos' : 'Indicadores gráficos' }}</h2>
@if (!catalogLoading() && !catalogError() && catalog().length) {
<p class="catalog-count" role="status">{{ catalogOrder().length }} indicadores publicados</p>
<p class="catalog-count" role="status">{{ catalog().length }} indicadores publicados</p>
}
</div>
@if (catalogLoading()) {
@@ -93,30 +111,23 @@
<div class="catalog-search">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Buscar indicadores</mat-label>
<mat-select #indicatorSelect multiple panelClass="indicator-select-panel" [ngModel]="selectedIndicators()" (ngModelChange)="changeIndicatorSelection($event)" aria-describedby="catalog-search-result">
<mat-select-trigger><span class="select-value">{{ selectionSummary() }}</span></mat-select-trigger>
@for (item of catalogOrder(); track item.id) {
<mat-option [value]="item.id"><span class="option-row"><span class="option-title">{{ item.titulo }}</span>
<a class="option-go" [href]="'#' + cardElementId(item)" (click)="goToIndicator(item.id, $event)"
[attr.aria-label]="'Ir a ' + item.titulo">Ir</a></span></mat-option>
}
</mat-select>
<input #searchInput matInput type="search" [ngModel]="searchQuery()" (ngModelChange)="changeSearchQuery($event)"
placeholder="Título o identificador" aria-describedby="catalog-search-help catalog-search-result" />
<button mat-icon-button matIconSuffix type="button" (click)="clearSearch()" [disabled]="!searchQuery()"
aria-label="Limpiar búsqueda"><mat-icon aria-hidden="true">close</mat-icon></button>
<mat-hint id="catalog-search-help">Las coincidencias aparecen primero; todos los indicadores siguen visibles.</mat-hint>
</mat-form-field>
<button mat-stroked-button type="button" (click)="showAllIndicators()" [disabled]="indicatorSelection() === null">Mostrar todos</button>
</div>
<p id="catalog-search-result" class="search-result" role="status">
Mostrando {{ searchResults().items.length }} de {{ catalogOrder().length }} indicadores.
<p id="catalog-search-result" class="search-result">
@if (searchResults().active) {
@if (searchResults().count) {
{{ searchResults().count }} coincidencias de {{ catalog().length }} indicadores. Todos permanecen disponibles.
} @else {
No se encontraron coincidencias. El catálogo completo permanece disponible; los indicadores fijados aparecen primero.
}
}
</p>
}
@if (!searchResults().items.length) {
<p class="state" role="status">No hay indicadores seleccionados. Elige al menos uno en «Buscar indicadores».</p>
}
@if (dominio === 'tea') {
<div class="reporte-acciones">
<button mat-stroked-button type="button" [disabled]="preparandoReporte()" (click)="descargarReporte()">{{ preparandoReporte() ? 'Preparando reporte…' : 'Descargar reporte' }}</button>
<span>Incluye el periodo y los indicadores seleccionados. Elige «Guardar como PDF» en el cuadro de impresión.</span>
</div>
}
<div class="catalog-grid">
@for (item of searchResults().items; track cardIdentity(item)) {
<app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
@@ -127,12 +138,6 @@
</section>
</div>
@if (dominio === 'tea') {
<section id="panel-historico" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-historico" tabindex="0" [hidden]="activeSection() !== 'historico'">
<app-indicadores-historico [dominio]="dominio" [catalog]="catalog()" [tema]="tema" [active]="activeSection() === 'historico'" />
</section>
}
<section id="panel-seguimiento" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" [attr.aria-labelledby]="fichaPacienteAbierta() ? 'dashboard-title' : 'tab-seguimiento'" tabindex="0" [hidden]="activeSection() !== 'seguimiento'">
<app-indicadores-tracking [domainLabel]="domainLabels[dominio]" [dominio]="dominio" [active]="activeSection() === 'seguimiento'"
(fichaPacienteAbierta)="setFichaPacienteAbierta($event)" />
@@ -41,16 +41,16 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
.kpi-section, .graphic-section { min-width: 0; }
.graphic-section { margin-top: var(--issste-space-6); padding-top: var(--issste-space-6); border-top: 1px solid var(--issste-border); }
.kpi-grid, .catalog-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
.kpi-section .kpi-grid.kpi-grid-oculto { display: none; }
.catalog-grid { align-items: stretch; }
.reporte-acciones { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); margin-bottom: var(--issste-space-4); }
.reporte-acciones span { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.catalog-grid > app-indicador-catalog-card { min-width: 0; margin: 0; }
.catalog-heading { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--issste-space-3); margin-bottom: var(--issste-space-4); }
.catalog-count { margin: 0 0 0 auto; text-align: right; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
.catalog-search { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: center; gap: var(--issste-space-3); margin-top: var(--issste-space-4); }
.catalog-search { display: flex; justify-content: flex-end; margin-top: var(--issste-space-4); }
.catalog-search mat-form-field { width: 100%; min-width: 0; max-width: 32rem; }
.catalog-search button { min-height: 48px; }
.catalog-search button { width: 48px; height: 48px; }
.catalog-search button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: -3px; }
// Keep search semantics; Material supplies the single accessible clear control.
.catalog-search input::-webkit-search-cancel-button { -webkit-appearance: none; appearance: none; }
.search-result { color: var(--mat-sys-on-surface-variant); font: var(--mat-sys-body-medium); text-align: right;
overflow-wrap: anywhere; margin: var(--issste-space-2) 0 var(--issste-space-4); }
@container dashboard (min-width: 600px) { .kpi-grid { grid-template-columns: repeat(min(2, var(--kpi-count)), minmax(0, 1fr)); } }
@@ -87,3 +87,8 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
.section-panel { padding-block: var(--issste-space-6); }
.section-panel[hidden] { display: none; }
@media (max-width: 550px) { .section-tabs button { flex: 1 1 auto; padding-inline: .65rem; } }
.graphic-navigation-trigger { transition: opacity 180ms ease; }
.graphic-navigation-trigger-expanded { opacity: 0; pointer-events: none; }
@media (prefers-reduced-motion: reduce) {
.graphic-navigation-trigger { transition: none; }
}
@@ -55,15 +55,15 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
it('cambia al encabezado de ficha sin destruir el estado de las pestañas', () => {
load();
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Indicadores');
expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(4);
expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(3);
fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(true); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Ficha del paciente');
expect(fixture.nativeElement.textContent).toContain('Consulta individual de seguimiento de TEA');
expect(fixture.nativeElement.textContent).toContain('Consulta individual de seguimiento de cáncer cervicouterino');
expect(fixture.nativeElement.querySelector('.section-tabs')).toBeNull();
expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('dashboard-title');
fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(false); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Indicadores');
expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(4);
expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(3);
expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('tab-seguimiento');
expect(page.activeSection()).toBe('resumen');
http.expectNone(() => true);
@@ -101,23 +101,16 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
expect(cards()).toEqual(before); expect(cards().every(card => card.visible)).toBe(true);
http.expectNone(() => true);
});
it('D.3.A muestra identidad y skeleton sin control de expansión ni HTTP', () => {
it('D.3.A muestra identidad, selector y skeleton sin control de expansión ni HTTP', () => {
load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card');
expect(host.querySelector('h2').textContent).toBe('Uno');
expect(host.querySelector('header button')).toBeNull();
expect(host.querySelector('mat-select')).toBeNull();
expect(host.querySelector('mat-select')).toBeTruthy();
expect(host.querySelector('.figure-skeleton').textContent).toContain('pendiente');
expect(host.textContent).not.toContain('Contrato C1');
expect(host.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas');
http.expectNone(() => true);
});
it('Resumen omite los indicadores publicados solo para otra pestaña', () => {
load([item, { ...second, vistas: ['historico'] }]);
expect(page.searchResults().items.map(i => i.id)).toEqual([item.id]);
expect(fixture.nativeElement.querySelector('.catalog-count').textContent).toContain('1 indicadores');
expect(page.catalog()).toHaveLength(2);
http.expectNone(r => r.url.endsWith('/figuras/f1'));
});
it('D.3.A conserva encabezado y contenido al salir del viewport', () => {
load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card');
const header = host.querySelector('header'); toggle(); flushAll();
@@ -212,7 +205,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
it('un único borrador actualiza todas las figuras y tema usa aplicado', () => {
load([item]); toggle(); flushAll(); const a = control();
expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1);
a.select([]); a.year = '2025'; a.unit = 'S1'; a.add(); http.expectNone(() => true);
a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add(); http.expectNone(() => true);
page.applyFilters(); fixture.detectChanges();
const appliedA = request('f1');
expect(appliedA.request.params.get('periodos')).toBe('2025-S1');
@@ -220,14 +213,14 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
page.changeTema('oscuro'); fixture.detectChanges();
const themedA = request('f1');
expect(themedA.request.params.get('periodos')).toBe('2025-S1');
expect(themedA.request.params.get('tema')).toBe('oscuro'); expect(a.selectedPeriods).toEqual(['2025-S2']);
expect(themedA.request.params.get('tema')).toBe('oscuro'); expect(a.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
themedA.flush({ data: [], layout: {} });
});
it('UX-06D expandir metodología carga metadatos una vez y conserva panel, figura y borrador', () => {
load([{ ...item, contrato: 'C2', figuras: ['fig_c2_apiladas'] }]); toggle(); flushAll();
const panel = panels()[0], chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance;
const filters = control();
filters.select([]); filters.year = '2025'; filters.unit = 'S1'; filters.add();
filters.changeMode('manual'); filters.year = '2025'; filters.unit = 'S1'; filters.add();
const draft = structuredClone(filters.entry.draft), applied = structuredClone(page.filters!.applied);
const result = panel.result();
const button = fixture.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement;
@@ -245,10 +238,10 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
}
});
it('salir y volver al viewport conserva borrador, aplicado y resultado sin HTTP redundante', () => {
load([item]); toggle(); flushAll(); const a = control(); a.select([]); a.year = '2025'; a.unit = 'S1'; a.add();
load([item]); toggle(); flushAll(); const a = control(); a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add();
page.applyFilters(); fixture.detectChanges(); flushAll(); kpiMissing(); a.year = '2025'; a.unit = 'S2'; a.add();
cards()[0].setVisible(false); fixture.detectChanges(); toggle();
expect(control()).toBe(a); expect(control().selectedPeriods).toEqual(['2025-S2']);
expect(control()).toBe(a); expect(control().selectedPeriods).toEqual(['2025-S1', '2025-S2']);
http.expectNone(() => true);
});
it('tema solo consulta paneles visibles, cancela los anteriores y no repite el mismo tema', () => {
@@ -268,7 +261,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
expect(() => oldCatalog.flush(syntheticCatalogs.cacu)).toThrow(); expect(page.dominio).toBe('cama');
});
it('restaura representación y tema de dominio sin aplicar borrador pendiente', () => {
load(); toggle(); flushAll(); control().select([]);
load(); toggle(); flushAll(); control().changeMode('manual');
page.changeTema('oscuro'); fixture.detectChanges(); flushAll();
page.changeDominio('cacu'); fixture.detectChanges(); load(syntheticCatalogs.cacu, 'cacu'); toggle(); flushAll();
toggle(); page.changeDominio('tea'); fixture.detectChanges(); load();
@@ -322,7 +315,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
load(syntheticCatalogs.tea);
const index = cards().findIndex(c => c.indicador.id === id);
toggle(index); flushAll();
const c = control(); c.select([]); fixture.detectChanges(); await fixture.whenStable();
const c = control(); c.changeMode('manual'); fixture.detectChanges(); await fixture.whenStable();
expect(c.canApply).toBe(false); http.expectNone(() => true);
c.year = '2025'; c.unit = 'S1'; c.add(); c.select([]); fixture.detectChanges(); await fixture.whenStable();
toggle(index); toggle(index); flushAll(); await fixture.whenStable();
@@ -348,7 +341,9 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
const a = http.expectOne(r => r.url.endsWith('/i1/figuras/f1'));
const b = http.expectOne(r => r.url.endsWith('/i2/figuras/f1'));
a.flush({ data: [{ y: [1] }], layout: {} }); b.flush({ data: [{ y: [2] }], layout: {} }); fixture.detectChanges();
const buttons = fixture.nativeElement.querySelectorAll('app-indicador-catalog-card mat-select') as NodeListOf<HTMLElement>;
expect(panels()[0].titleId).not.toBe(panels()[1].titleId);
expect(buttons[0].tabIndex).toBe(-1); expect(buttons[1].tabIndex).toBe(-1);
expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [2]]);
});
});
+167 -107
View File
@@ -8,16 +8,16 @@ import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatIconModule } from '@angular/material/icon';
import { MatSelect, MatSelectModule } from '@angular/material/select';
import { MatSelectModule } from '@angular/material/select';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { catchError, first, map, of, startWith, Subject, switchMap, takeUntil } from 'rxjs';
import { ConnectedPosition, Overlay, OverlayModule } from '@angular/cdk/overlay';
import { catchError, map, of, startWith, Subject, switchMap, takeUntil } from 'rxjs';
import { Dominio, DOMINIOS, isDominio, Indicador, Tema } from './indicadores.models';
import { IndicadoresService } from './indicadores.service';
import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory';
import { IndicadorPeriodFilters } from './indicador-period-filters';
import { IndicadorCatalogCard } from './indicador-catalog-card';
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN, KPI_RESUMEN_TEA } from './indicadores-kpi';
import { TeaResumenPeriodo } from './tea-resumen-periodo';
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
import { IndicadorKpiPanel } from './indicador-kpi-panel';
import { IndicadorKpiCard } from './indicador-kpi-card';
import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection';
@@ -27,32 +27,31 @@ import { httpMessage } from './indicadores-http';
import { IndicadoresInitialPeriod } from './indicadores-initial-period';
import { IndicadoresDefinitions } from './indicadores-definitions';
import { IndicadoresTracking } from './indicadores-tracking';
import { IndicadoresHistorico } from './indicadores-historico';
import { IndicadorNavegacionItem, IndicadoresNavegacionPanel } from './indicadores-navegacion-panel';
type DashboardSection = 'resumen' | 'historico' | 'seguimiento' | 'datos';
const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
{ id: 'resumen', label: 'Resumen' },
{ id: 'seguimiento', label: 'Seguimiento' },
{ id: 'datos', label: 'Datos y definiciones' },
];
// Only TEA has enough periods for its history to say anything.
const TEA_SECTIONS: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]];
type DashboardSection = 'resumen' | 'seguimiento' | 'datos';
@Component({
selector: 'app-indicadores-page',
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, OverlayModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNavegacionPanel],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})
export class IndicadoresPage {
get sections() { return this.dominio === 'tea' ? TEA_SECTIONS : SECTIONS; }
readonly sections: readonly { id: DashboardSection; label: string }[] = [
{ id: 'resumen', label: 'Resumen' },
{ id: 'seguimiento', label: 'Seguimiento' },
{ id: 'datos', label: 'Datos y definiciones' },
];
readonly activeSection = signal<DashboardSection>('resumen');
readonly fichaPacienteAbierta = signal(false);
setFichaPacienteAbierta(open: boolean) {
this.fichaPacienteAbierta.set(open);
if (open) this.closeGraphicNavigation(false, false);
}
changeSection(section: DashboardSection) {
if (!this.sections.some(item => item.id === section) || this.activeSection() === section) return;
if (section !== 'resumen') this.closeGraphicNavigation(false, false);
this.activeSection.set(section);
// Retain views, filters and Plotly hosts; only visible regions authorize loading.
if (section !== 'resumen') for (const card of this.graphicCards()) card.setVisible(false);
@@ -72,9 +71,28 @@ export class IndicadoresPage {
private readonly document = inject(DOCUMENT);
private readonly element = inject<ElementRef<HTMLElement>>(ElementRef);
private readonly injector = inject(Injector);
private readonly indicatorSelect = viewChild<MatSelect>('indicatorSelect');
private readonly searchInput = viewChild<ElementRef<HTMLInputElement>>('searchInput');
private readonly overlay = inject(Overlay);
readonly navigationScrollStrategy = this.overlay.scrollStrategies.reposition();
readonly navigationPositions: ConnectedPosition[] = [
{ originX: 'start', originY: 'center', overlayX: 'start', overlayY: 'center' },
{ originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'top' },
{ originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'bottom' },
{ originX: 'end', originY: 'center', overlayX: 'end', overlayY: 'center' },
];
readonly navigationOpen = signal(false);
readonly navigationClosing = signal(false);
readonly navigationAttached = computed(() => this.navigationOpen() || this.navigationClosing());
readonly navigationKeyboard = signal(false);
private readonly navigationPanel = viewChild(IndicadoresNavegacionPanel);
private navigationHoverTimer?: ReturnType<typeof setTimeout>;
private navigationAnimationTimer?: ReturnType<typeof setTimeout>;
private navigationPointerInside = false;
// Removing the overlay can generate pointerenter on the button under a stationary cursor.
private navigationHoverDismissed = false;
readonly navigationItems = computed<readonly IndicadorNavegacionItem[]>(() =>
this.searchResults().items.map(item => ({ key: indicatorIdentity(this.dominio, item.id), titulo: item.titulo })));
private readonly graphicCards = viewChildren(IndicadorCatalogCard);
readonly kpiPanels = viewChildren(IndicadorKpiPanel);
private readonly observedRegions = new Map<Element, IndicadorCatalogCard>();
private renderedCards: readonly IndicadorCatalogCard[] = [];
private visibilityObserver?: IntersectionObserver;
@@ -160,26 +178,7 @@ export class IndicadoresPage {
this.visibilityObserver = observer;
for (const region of this.observedRegions.keys()) observer.observe(region);
}
// Report: every selected chart has to be drawn, narrow enough for a page, before opening the print dialog.
readonly preparandoReporte = signal(false);
async descargarReporte() {
const browser = this.document.defaultView;
if (!browser || this.preparandoReporte()) return;
this.preparandoReporte.set(true);
for (const card of this.graphicCards()) card.setVisible(true);
this.changeDetector.markForCheck();
const espera = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
const pendiente = () => this.element.nativeElement.querySelector('#panel-resumen mat-progress-bar, #panel-resumen .figure-skeleton');
await espera(100);
for (let i = 0; pendiente() && i < 150; i++) await espera(100);
// Charts resize to the page width on their next frames.
await espera(500);
const terminar = () => { this.preparandoReporte.set(false); this.changeDetector.markForCheck(); this.visibilityChanged(); };
browser.addEventListener('afterprint', terminar, { once: true });
browser.print();
}
private evaluateVisibility() {
if (this.preparandoReporte()) return;
const browser = this.document.defaultView;
if (!browser || this.visibilityDestroyed || !this.visibilityObserver) return;
if (this.activeSection() !== 'resumen') return;
@@ -196,12 +195,14 @@ export class IndicadoresPage {
}
this.changeDetector.markForCheck();
}
changeIndicatorSelection(ids: string[]) {
this.preserveCardFocus();
// Every indicator checked is the same as no filter, so later catalog additions also show.
this.indicatorSelection.set(ids.length === this.catalogOrder().length ? null : ids);
clearSearch() {
this.changeSearchQuery('');
this.searchInput()?.nativeElement.focus({ preventScroll: true });
}
changeSearchQuery(query: string) {
this.preserveCardFocus();
this.searchQuery.set(query);
}
showAllIndicators() { this.changeIndicatorSelection(this.catalogOrder().map(item => item.id)); }
isPinned(item: Indicador) { return this.memory.isPinned(this.dominio, item.id); }
togglePinned(item: Indicador) {
this.preserveCardFocus();
@@ -273,7 +274,7 @@ export class IndicadoresPage {
// Short form for the domain-switcher buttons (our shell's own nav, see the
// template comment above it) -- `domainLabels`/`domainTitles` are prose-length.
readonly domainNavLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' };
readonly kpisByDomain = { ...KPI_BY_DOMAIN, tea: [...KPI_BY_DOMAIN.tea, ...KPI_RESUMEN_TEA] };
readonly kpisByDomain = KPI_BY_DOMAIN;
figureApplied(item: Indicador) { return figureApplied(this.dominio, item.id, this.filters!.applied); }
independentPeriods(item: Indicador) { return independentFigurePeriods(this.dominio, item.id); }
kpiIndicator(id: string) {
@@ -289,11 +290,6 @@ export class IndicadoresPage {
return undefined;
}
get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); }
// TEA shows a summary paragraph instead of its cards for exactly one explicitly chosen period.
get teaResumenPeriodo(): string | undefined {
const selection = this.filters?.applied.selection;
return this.dominio === 'tea' && selection?.mode === 'explicit' && selection.periodos.length === 1 ? selection.periodos[0] : undefined;
}
get opportunityKpis() {
const definitions = this.availableKpis;
if (this.dominio !== 'cacu' || (!definitions.length && !this.catalog().some(item => item.id === CACU_RESULTADO_KPI.id))) return definitions;
@@ -304,28 +300,31 @@ export class IndicadoresPage {
}
private readonly catalogRequests = new Subject<void>();
readonly catalog = signal<Indicador[]>([]);
// Ids of the indicators to render; null shows the whole catalog.
readonly indicatorSelection = signal<string[] | null>(null);
readonly searchVisible = computed(() => this.catalogOrder().length >= 2);
// Stable presentation priority; pins still take precedence in the grid.
readonly catalogOrder = computed(() => {
const catalog = this.catalog();
return this.dominio === 'cacu'
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')]
: catalog.filter(item => !item.vistas || item.vistas.includes('resumen'));
});
readonly selectedIndicators = computed(() => this.indicatorSelection() ?? this.catalog().map(item => item.id));
readonly selectionSummary = computed(() => {
const selected = this.selectedIndicators();
if (this.indicatorSelection() === null) return 'Todos los indicadores';
if (selected.length === 1) return this.catalog().find(item => item.id === selected[0])?.titulo ?? selected[0];
return selected.length + ' indicadores';
});
readonly searchQuery = signal('');
readonly searchVisible = computed(() => this.catalog().length >= 5);
readonly searchResults = computed(() => {
const selected = new Set(this.selectedIndicators());
const items = this.catalogOrder().filter(item => selected.has(item.id));
return { items: [...items.filter(item => this.isPinned(item)), ...items.filter(item => !this.isPinned(item))] };
const catalog = this.catalog();
// Stable presentation priority; search matches and pins still take precedence.
const items = this.dominio === 'cacu'
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')]
: catalog;
const query = this.normalizeSearch(this.searchQuery());
const prioritize = (group: Indicador[]) => [
...group.filter(item => this.isPinned(item)),
...group.filter(item => !this.isPinned(item)),
];
if (!query) return { items: prioritize(items), active: false, count: 0 };
const matches: Indicador[] = [];
const remaining: Indicador[] = [];
for (const item of items) {
const matchesQuery = [item.titulo, item.id].some(value => this.normalizeSearch(value).includes(query));
(matchesQuery ? matches : remaining).push(item);
}
return { items: [...prioritize(matches), ...prioritize(remaining)], active: true, count: matches.length };
});
private normalizeSearch(value: string) {
return value.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase().trim();
}
readonly catalogLoading = signal(true);
readonly catalogError = signal('');
tema: Tema = 'claro';
@@ -355,56 +354,115 @@ export class IndicadoresPage {
}
cardIdentity(item: Indicador) { return indicatorIdentity(this.dominio, item.id); }
cardElementId(item: Indicador) { return identityElementId(this.cardIdentity(item)); }
// «Ir» in the indicator selector: show the indicator if it was filtered out, then scroll to its card.
goToIndicator(id: string, event?: Event) {
// The link sits inside a mat-option: it must not toggle the option's selection.
event?.preventDefault(); event?.stopPropagation();
if (!this.catalog().some(item => item.id === id)) return;
const selection = this.indicatorSelection();
if (selection && !selection.includes(id)) this.indicatorSelection.set([...selection, id]);
const key = indicatorIdentity(this.dominio, id), select = this.indicatorSelect();
const scroll = () => afterNextRender(() => this.scrollToIndicator(key), { injector: this.injector });
// Closing the panel returns focus to the selector, which would cancel a scroll started before it ends.
if (select?.panelOpen) { select.openedChange.pipe(first(open => !open)).subscribe(scroll); select.close(); }
else scroll();
get showGraphicNavigation() {
return this.activeSection() === 'resumen' && !this.fichaPacienteAbierta() && !this.catalogLoading()
&& !this.catalogError() && !this.initialPeriodBlocked && this.navigationItems().length > 0;
}
toggleGraphicNavigation(event?: MouseEvent) {
if (!this.showGraphicNavigation) return;
if (this.navigationOpen()) this.closeGraphicNavigation(false);
else this.openGraphicNavigation(event?.detail === 0);
}
private openGraphicNavigation(keyboard = false) {
if (!this.showGraphicNavigation) return;
this.clearNavigationTimers();
this.navigationHoverDismissed = false;
this.navigationKeyboard.set(keyboard);
this.navigationClosing.set(false);
this.navigationOpen.set(true);
if (keyboard) afterNextRender(() => {
if (this.navigationOpen() && this.navigationKeyboard()) this.navigationPanel()?.focusFirstOption();
}, { injector: this.injector });
}
navigationTriggerKeydown(event: KeyboardEvent) {
if (event.key !== 'Enter' && event.key !== ' ') return;
event.preventDefault();
this.openGraphicNavigation(true);
}
navigationPointerEnter(event: PointerEvent) {
if (this.navigationHoverDismissed || !this.navigationCanHover(event)) return;
this.navigationPointerInside = true;
if (this.navigationHoverTimer !== undefined) clearTimeout(this.navigationHoverTimer);
this.navigationHoverTimer = undefined;
if (!this.navigationOpen()) this.openGraphicNavigation();
}
navigationPointerMove(event: PointerEvent) {
if (!this.navigationHoverDismissed || !this.navigationCanHover(event)) return;
this.navigationHoverDismissed = false;
this.navigationPointerEnter(event);
}
private navigationCanHover(event: PointerEvent) {
return event.pointerType === 'mouse' && this.document.defaultView?.matchMedia?.('(hover: hover) and (pointer: fine)').matches;
}
navigationPointerLeave(event: PointerEvent) {
if (!this.navigationCanHover(event)) return;
this.navigationPointerInside = false;
this.scheduleNavigationClose();
}
navigationFocusOut() { this.scheduleNavigationClose(); }
private scheduleNavigationClose() {
if (!this.navigationOpen()) return;
if (this.navigationHoverTimer !== undefined) clearTimeout(this.navigationHoverTimer);
this.navigationHoverTimer = setTimeout(() => {
this.navigationHoverTimer = undefined;
if (!this.navigationPointerInside && !this.navigationPanel()?.containsFocus()) this.closeGraphicNavigation(false);
}, 230);
}
navigationOverlayKeydown(event: KeyboardEvent) {
if (event.key !== 'Escape') return;
event.preventDefault();
this.closeGraphicNavigation();
}
private clearNavigationTimers() {
if (this.navigationHoverTimer !== undefined) clearTimeout(this.navigationHoverTimer);
if (this.navigationAnimationTimer !== undefined) clearTimeout(this.navigationAnimationTimer);
this.navigationHoverTimer = this.navigationAnimationTimer = undefined;
}
closeGraphicNavigation(restoreFocus = true, animate = true) {
const wasOpen = this.navigationOpen();
this.clearNavigationTimers();
this.navigationHoverDismissed ||= wasOpen;
this.navigationPointerInside = false;
this.navigationKeyboard.set(false);
this.navigationOpen.set(false);
const reducedMotion = this.document.defaultView?.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
this.navigationClosing.set(animate && wasOpen && !reducedMotion);
if (this.navigationClosing()) this.navigationAnimationTimer = setTimeout(() => {
this.navigationAnimationTimer = undefined;
this.navigationClosing.set(false);
}, 180);
if (wasOpen && restoreFocus && this.showGraphicNavigation) {
this.element.nativeElement.querySelector<HTMLButtonElement>('.graphic-navigation-trigger')?.focus({ preventScroll: true });
}
}
closeGraphicNavigationFromOutside(event: MouseEvent) {
const target = event.target;
const trigger = this.element.nativeElement.querySelector<HTMLButtonElement>('.graphic-navigation-trigger');
if (target instanceof Node && trigger?.contains(target)) return;
this.closeGraphicNavigation(false);
}
selectGraphicNavigation(key: string) {
if (!this.navigationItems().some(item => item.key === key)) {
this.closeGraphicNavigation(false);
return;
}
this.closeGraphicNavigation(false, false);
afterNextRender(() => this.scrollToIndicator(key), { injector: this.injector });
}
private scrollToIndicator(key: string) {
if (this.activeSection() !== 'resumen' || this.fichaPacienteAbierta()) return;
if (this.activeSection() !== 'resumen' || this.fichaPacienteAbierta()
|| !this.navigationItems().some(item => item.key === key)) return;
const target = this.document.getElementById(identityElementId(key));
const grid = this.element.nativeElement.querySelector('.catalog-grid');
if (!target || !grid?.contains(target)) return;
const reducedMotion = this.document.defaultView?.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
target.scrollIntoView({ behavior: reducedMotion ? 'instant' : 'smooth', block: 'start' });
target.querySelector('h2')?.focus({ preventScroll: true });
this.keepAligned(target, grid);
}
// Figures above the card load as the scroll passes them and grow taller than their placeholders,
// pushing the card down. For a short while, put it back in place whenever the grid resizes;
// any scrolling by the user ends this.
private stopAligning?: () => void;
private keepAligned(target: HTMLElement, grid: Element) {
this.stopAligning?.();
const browser = this.document.defaultView;
if (!browser || typeof ResizeObserver === 'undefined') return;
const host = this.element.nativeElement;
const userInput = ['wheel', 'touchstart', 'keydown', 'pointerdown'] as const;
const observer = new ResizeObserver(() => {
const offset = target.getBoundingClientRect().top - host.getBoundingClientRect().top - parseFloat(browser.getComputedStyle(target).scrollMarginTop || '0');
if (Math.abs(offset) > 2) target.scrollIntoView({ behavior: 'instant', block: 'start' });
});
const timer = setTimeout(() => this.stopAligning?.(), 2500);
const stop = () => {
observer.disconnect(); clearTimeout(timer);
for (const type of userInput) host.removeEventListener(type, stop);
if (this.stopAligning === stop) this.stopAligning = undefined;
};
this.stopAligning = stop;
observer.observe(grid);
for (const type of userInput) host.addEventListener(type, stop, { passive: true });
}
constructor() {
afterEveryRender(() => {
this.syncVisibility();
if (!this.showGraphicNavigation && (this.navigationAttached() || this.navigationHoverTimer !== undefined)) this.closeGraphicNavigation(false, false);
});
const browser = this.document.defaultView;
if (typeof IntersectionObserver !== 'undefined') {
@@ -412,9 +470,9 @@ export class IndicadoresPage {
browser?.addEventListener('resize', this.viewportChanged);
}
this.destroyRef.onDestroy(() => {
this.stopAligning?.();
this.filtersEdited();
this.visibilityDestroyed = true;
this.closeGraphicNavigation(false, false);
this.clearVisibility();
this.sizeObserver?.disconnect();
this.sizeTargets.clear();
@@ -429,6 +487,7 @@ export class IndicadoresPage {
return this.periodService.dominio(this.dominio, this.catalog());
}), takeUntilDestroyed(this.destroyRef)).subscribe(state => this.availability.set(state));
this.catalogRequests.pipe(startWith(undefined), switchMap(() => {
this.closeGraphicNavigation(false, false);
this.cancelInitialPeriod.next();
this.initialPeriodState.set('ready');
this.clearVisibility();
@@ -450,8 +509,9 @@ export class IndicadoresPage {
}
changeDominio(dominio: Dominio) {
if (!isDominio(dominio) || dominio === this.dominio) return;
this.closeGraphicNavigation(false, false);
this.activeSection.set('resumen');
this.indicatorSelection.set(null);
this.searchQuery.set('');
this.filtersEdited();
this.filters = undefined;
this.dominio = dominio;
@@ -92,7 +92,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
expect(requests).toHaveLength(2); expect(panels()[0].result().state).toBe('Sin reportes disponibles');
expect(panels()[0].result().value).toBeUndefined();
});
it('selección mensual edita sin HTTP; un periodo consulta y no se pueden elegir varios', async () => {
it('multiselección mensual edita sin HTTP; un periodo consulta y varios no consolidan', async () => {
load('cacu', Array(3).fill(['2026-S2', '2025-02', '2025-10', '2026-01'])); flushDatos('cacu');
const control = editor(); control.changeTipo('mes'); control.select(['2025-10']); fixture.detectChanges();
expect(control.options).toEqual(['2026-01', '2025-10', '2025-02']);
@@ -103,9 +103,10 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
const single = flushDatos('cacu'); expect(single).toHaveLength(2);
expect(single.every(r => r.request.params.get('periodos') === '2025-10')).toBe(true);
control.select(['2025-10', '2025-02']); fixture.detectChanges(); http.expectNone(() => true);
expect(control.selectedPeriods).toEqual(['2025-10']);
fixture.componentInstance.applyFilters(); fixture.detectChanges();
expect(panels().every(p => p.result().state !== 'Selección no consolidable')).toBe(true);
expect(panels().every(p => p.result().state === 'Selección no consolidable' && p.result().value === undefined)).toBe(true);
http.expectNone(() => true);
control.select(['2025-02', '2025-10']); fixture.componentInstance.applyFilters(); fixture.detectChanges();
http.expectNone(() => true);
await fixture.whenStable();
});
@@ -118,7 +119,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
expect(panels()).toHaveLength(0);
expect(fixture.nativeElement.textContent).toContain('No se pudo determinar el periodo inicial de cáncer cervicouterino');
expect(fixture.nativeElement.textContent).not.toContain('private');
const control = editor(); control.select([]); control.select(['2025-S2']);
const control = editor(); control.changeMode('manual'); control.select(['2025-S2']);
expect(control.canApply).toBe(false);
fixture.componentInstance.retryAvailability(); fixture.componentInstance.retryInitialPeriod(); fixture.detectChanges();
const retry = http.expectOne('/cacu/indicadores/cacu_eu7/periodos');
@@ -63,22 +63,25 @@ describe('UX-06E.D.3.B fijación temporal', () => {
await pin('i2'); expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']);
expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); http.expectNone(() => true);
});
it('la selección de indicadores conserva la prioridad de los fijados', async () => {
it('coincidencias preceden a los fijados no coincidentes y la fijación resuelve cada grupo', async () => {
await pin('i3'); await pin('i4');
page.changeIndicatorSelection(['i1', 'i3', 'i4']); fixture.detectChanges(); await settle();
expect(ids()).toEqual(['i3', 'i4', 'i1']);
await pin('i1'); expect(ids()).toEqual(['i1', 'i3', 'i4']);
expect(cards()).toHaveLength(3); http.expectNone(() => true);
page.changeSearchQuery(' EVALUACION '); fixture.detectChanges(); await settle();
expect(ids()).toEqual(['i4', 'i1', 'i3', 'i0', 'i2']);
expect(page.searchResults().count).toBe(2); expect(page.searchResults().active).toBe(true);
await pin('i1'); expect(ids()).toEqual(['i1', 'i4', 'i3', 'i0', 'i2']);
expect(cards()).toHaveLength(items.length); http.expectNone(() => true);
});
it('Mostrar todos restaura el catálogo con los fijados primero', async () => {
await pin('i3'); page.changeIndicatorSelection(['i0']); fixture.detectChanges(); await settle();
expect(ids()).toEqual(['i0']);
it('limpiar mediante el buscador restaura fijados primero y mantiene foco', async () => {
await pin('i3'); page.changeSearchQuery('Edad'); fixture.detectChanges(); await settle();
expect(ids()[0]).toBe('i0');
fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle();
expect(page.indicatorSelection()).toBeNull(); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']); http.expectNone(() => true);
expect(page.searchQuery()).toBe(''); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']);
expect(document.activeElement).toBe(fixture.nativeElement.querySelector('.catalog-search input')); http.expectNone(() => true);
});
it('un fijado sin seleccionar no se muestra', async () => {
await pin('i2'); page.changeIndicatorSelection(['i0', 'i1']); fixture.detectChanges(); await settle();
expect(ids()).toEqual(['i0', 'i1']); http.expectNone(() => true);
it('búsqueda sin coincidencias conserva todo el catálogo con prioridad de fijados', async () => {
await pin('i2'); page.changeSearchQuery('inexistente'); fixture.detectChanges(); await settle();
expect(ids()).toEqual(['i2', 'i0', 'i1', 'i3', 'i4']); expect(page.searchResults().count).toBe(0);
expect(fixture.nativeElement.textContent).toContain('El catálogo completo permanece disponible'); http.expectNone(() => true);
});
it('memoria independiente por dominio y persistente al recrear la página', async () => {
await pin('i3'); page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id));
@@ -4,11 +4,15 @@ import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { provideRouter } from '@angular/router';
import { By } from '@angular/platform-browser';
import { NgModel } from '@angular/forms';
import { MatSelect } from '@angular/material/select';
import { IndicadoresPage } from './indicadores-page';
import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigurePanel } from './indicador-figure-panel';
import { IndicadorPeriodFilters } from './indicador-period-filters';
import { IndicadoresMemory } from './indicadores-memory';
import { Indicador } from './indicadores.models';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
const items: Indicador[] = [
@@ -19,15 +23,16 @@ const items: Indicador[] = [
{ id: 'E05', titulo: 'Evaluación final', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
];
describe('Selección de indicadores gráficos', () => {
describe('UX-05C búsqueda local y partición estable', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
let page: IndicadoresPage;
let http: HttpTestingController;
const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } };
const disconnect = vi.fn();
beforeEach(() => {
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
vi.resetAllMocks(); runtime.react.mockResolvedValue(undefined); runtime.Plots.resize.mockResolvedValue(undefined);
vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); });
vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = disconnect; });
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider,
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
@@ -38,88 +43,184 @@ describe('Selección de indicadores gráficos', () => {
http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges();
}
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
function ids() { return cards().map(c => c.indicador.id); }
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel); }
function select() { return fixture.debugElement.query(By.css('.catalog-search mat-select'))?.componentInstance as MatSelect | undefined; }
function showAll(): HTMLButtonElement { return fixture.nativeElement.querySelector('.catalog-search button'); }
function result() { return (fixture.nativeElement.querySelector('#catalog-search-result') as HTMLElement).textContent!.trim(); }
function choose(selection: string[]) { page.changeIndicatorSelection(selection); fixture.detectChanges(); }
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); }
function filters() { return fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters)).map(e => e.componentInstance as IndicadorPeriodFilters); }
function charts() { return fixture.debugElement.queryAll(By.directive(PlotlyChart)).map(e => e.componentInstance as PlotlyChart); }
function input(): HTMLInputElement { return fixture.nativeElement.querySelector('.catalog-search input'); }
async function settle() { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); }
async function search(value: string) {
input().value = value; input().dispatchEvent(new Event('input', { bubbles: true })); fixture.detectChanges(); await settle();
}
function respond() {
http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [0, null] }], layout: {} })); fixture.detectChanges();
}
function request(id: string) { return http.expectOne(r => r.url.endsWith('/' + id + '/figuras/f')); }
it.each([0, 1, 2, 5])('muestra el selector desde dos indicadores: catálogo de %i', count => {
it.each([0, 1, 4, 5, 18, 37])('muestra búsqueda exclusivamente desde cinco: catálogo de %i', count => {
load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'id-' + i })));
expect(!!select()).toBe(count >= 2); expect(cards()).toHaveLength(count);
expect(!!input()).toBe(count >= 5); expect(cards()).toHaveLength(count);
expect(cards().every(c => !c.visible)).toBe(true);
http.expectNone(() => true);
if (!count) expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles');
});
it.each([
['sexo', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1],
['M02', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1],
['tribuci', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1],
['SEXO', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1],
['evaluacion', ['B02', 'E05', 'A01', 'M02_sexo', 'D04'], 2],
[' EVALUACIÓN ', ['B02', 'E05', 'A01', 'M02_sexo', 'D04'], 2],
['imposible', ['A01', 'B02', 'M02_sexo', 'D04', 'E05'], 0],
['', ['A01', 'B02', 'M02_sexo', 'D04', 'E05'], 0],
[' ', ['A01', 'B02', 'M02_sexo', 'D04', 'E05'], 0],
])('consulta %s preserva todos los objetos y el catálogo original', async (query, ids, count) => {
load(); const original = page.catalog(), snapshot = JSON.stringify(original), before = cards();
await search(query as string);
expect(cards().map(c => c.indicador.id)).toEqual(ids);
expect(page.searchResults().count).toBe(count); expect(page.searchResults().active).toBe(!!(query as string).trim());
expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot);
for (const card of cards()) {
expect(card).toBe(before.find(c => c.indicador.id === card.indicador.id));
expect(card.indicador).toBe(original.find(i => i.id === card.indicador.id)); expect(card.visible).toBe(false);
}
if (query === 'imposible') expect(fixture.nativeElement.textContent).toContain('El catálogo completo permanece disponible');
if (!(query as string).trim()) expect(fixture.nativeElement.querySelector('#catalog-search-result').textContent.trim()).toBe('');
http.expectNone(() => true);
});
it('lista todo el catálogo, con todos seleccionados al inicio', () => {
load();
expect(select()!.multiple).toBe(true);
expect(select()!.options.map(o => o._getHostElement().querySelector('.option-title')!.textContent)).toEqual(items.map(i => i.titulo));
expect(page.selectedIndicators()).toEqual(items.map(i => i.id));
expect(page.selectionSummary()).toBe('Todos los indicadores');
expect(result()).toBe('Mostrando 5 de 5 indicadores.');
expect(showAll().disabled).toBe(true);
it('D.1 mantiene KPI fuera de la búsqueda y del recuento y utiliza un único suffix Material', async () => {
load(); await settle();
const kpis = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card'));
const field = fixture.nativeElement.querySelector('.catalog-search mat-form-field') as HTMLElement;
const clear = field.querySelector('button')!;
expect(clear.hasAttribute('matIconSuffix')).toBe(true);
expect(clear.closest('.mat-mdc-form-field-icon-suffix')).toBeTruthy();
expect(fixture.nativeElement.querySelectorAll('.catalog-search button')).toHaveLength(1);
expect(input().type).toBe('search');
for (const query of ['sexo', 'Indicador destacado', '']) {
await search(query);
expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card'))).toEqual(kpis);
expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('5 indicadores publicados');
expect(cards()).toHaveLength(5);
}
http.expectNone(() => true);
});
it('solo renderiza los seleccionados y conserva las tarjetas que siguen visibles', () => {
load(); const before = cards(), original = page.catalog();
choose(['B02', 'E05']);
expect(ids()).toEqual(['B02', 'E05']);
expect(cards()[0]).toBe(before[1]); expect(cards()[1]).toBe(before[4]);
expect(page.selectionSummary()).toBe('2 indicadores');
expect(result()).toBe('Mostrando 2 de 5 indicadores.');
expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('5 indicadores publicados');
choose(['M02_sexo']); expect(ids()).toEqual(['M02_sexo']); expect(page.selectionSummary()).toBe('Distribución por sexo');
expect(page.catalog()).toBe(original);
it('escritura y limpieza mantienen foco, cursor, etiqueta y ayudas sin HTTP', async () => {
load(); await settle(); const field = input(); field.focus(); await search('sexo');
expect(document.activeElement).toBe(field); expect(field.value).toBe('sexo');
field.setSelectionRange(2, 2); fixture.detectChanges(); await settle(); expect(field.selectionStart).toBe(2); expect(field.selectionEnd).toBe(2);
expect(field.labels?.[0].textContent).toContain('Buscar indicadores');
for (const id of field.getAttribute('aria-describedby')!.split(' ')) expect(document.getElementById(id)).toBeTruthy();
expect(fixture.nativeElement.querySelector('#catalog-search-result').getAttribute('aria-live')).toBeNull();
const clear = fixture.nativeElement.querySelector('.catalog-search button') as HTMLButtonElement;
expect(clear.getAttribute('aria-label')).toBe('Limpiar búsqueda'); clear.focus(); expect(document.activeElement).toBe(clear); clear.click(); fixture.detectChanges(); await settle();
expect(page.searchQuery()).toBe(''); expect(field.value).toBe(''); expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id));
expect(clear.disabled).toBe(true); expect(input()).toBe(field); expect(document.activeElement).toBe(field);
await search('edad'); field.setSelectionRange(2, 2); expect(document.activeElement).toBe(field); expect(field.selectionStart).toBe(2);
http.expectNone(() => true);
});
it('sin selección no muestra tarjetas y Mostrar todos restaura el catálogo', () => {
load(); choose([]);
expect(cards()).toHaveLength(0); expect(panels()).toHaveLength(0);
expect(fixture.nativeElement.textContent).toContain('No hay indicadores seleccionados');
expect(showAll().disabled).toBe(false);
showAll().click(); fixture.detectChanges();
expect(ids()).toEqual(items.map(i => i.id)); expect(page.indicatorSelection()).toBeNull(); expect(showAll().disabled).toBe(true);
it('botón nativo iconográfico conserva nombre, semántica, tamaño y estado sin HTTP', async () => {
load(); await settle();
const clear = fixture.nativeElement.querySelector('.catalog-search button') as HTMLButtonElement;
expect(clear.type).toBe('button'); expect(clear.disabled).toBe(true);
expect(clear.getAttribute('aria-label')).toBe('Limpiar búsqueda');
const icon = clear.querySelector('mat-icon')!;
expect(icon.textContent).toBe('close'); expect(icon.getAttribute('aria-hidden')).toBe('true');
expect(clear.textContent).not.toContain('Limpiar');
expect(getComputedStyle(clear).width).toBe('48px'); expect(getComputedStyle(clear).height).toBe('48px');
await search('sexo'); expect(clear.disabled).toBe(false); expect(clear.tabIndex).toBe(0);
// jsdom does not synthesize native keyboard activation. Verify that keys remain
// available to the browser; Enter/Space activation is a Chrome acceptance check.
for (const key of ['Enter', ' ']) {
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
clear.dispatchEvent(event); expect(event.defaultPrevented).toBe(false);
}
clear.focus(); clear.click(); fixture.detectChanges(); await settle();
expect(document.activeElement).toBe(input()); expect(clear.disabled).toBe(true);
http.expectNone(() => true);
});
it('marcar todos equivale a no filtrar', () => {
load(); choose(['A01']); choose(items.map(i => i.id));
expect(page.indicatorSelection()).toBeNull(); expect(page.selectionSummary()).toBe('Todos los indicadores');
});
it('los indicadores destacados no dependen de la selección', () => {
load(); const kpis = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-panel'));
choose(['A01']);
expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-panel'))).toEqual(kpis);
});
it('«Ir» lleva a la tarjeta sin alternar la opción y muestra el indicador si estaba oculto', async () => {
const scroll = vi.fn();
Element.prototype.scrollIntoView = scroll;
load(); choose(['A01']);
select()!.open(); fixture.detectChanges(); await fixture.whenStable();
const go = (id: string) => Array.from(document.querySelectorAll<HTMLAnchorElement>('.indicator-select-panel .option-go'))
.find(a => a.closest('mat-option')!.textContent!.includes(items.find(i => i.id === id)!.titulo))!;
expect(go('D04').getAttribute('aria-label')).toBe('Ir a Seguimiento');
// The scroll waits until the panel has finished closing.
const settle = (calls: number) => vi.waitFor(async () => { fixture.detectChanges(); await fixture.whenStable(); expect(scroll).toHaveBeenCalledTimes(calls); });
go('D04').click(); fixture.detectChanges(); await fixture.whenStable();
expect(page.selectedIndicators()).toEqual(['A01', 'D04']);
expect(select()!.panelOpen).toBe(false);
await settle(1);
expect((scroll.mock.contexts[0] as HTMLElement).querySelector('h2')?.textContent).toContain('Seguimiento');
select()!.open(); fixture.detectChanges(); await fixture.whenStable();
go('A01').click(); fixture.detectChanges(); await fixture.whenStable();
// Already visible: the selection is untouched.
expect(page.selectedIndicators()).toEqual(['A01', 'D04']);
await settle(2);
http.match(() => true).forEach(r => r.flush({ data: [], layout: {} }));
});
it('no muestra el botón flotante de navegación por indicadores', () => {
load();
expect(fixture.nativeElement.querySelector('.graphic-navigation-trigger')).toBeNull();
it('tres tarjetas abiertas conservan paneles, borrador/aplicado, Forms, memoria y hosts Plotly sin react/purge', async () => {
load(); cards().slice(0, 3).forEach(c => c.setVisible(true)); fixture.detectChanges(); respond(); await settle();
const beforeCards = cards(), beforePanels = panels(), beforeFilters = filters(), beforeCharts = charts();
const c = beforeFilters[0]; c.changeMode('manual'); c.year = '2025'; c.unit = 'S1'; c.add();
page.applyFilters(); fixture.detectChanges(); respond(); await settle();
c.year = '2025'; c.unit = 'S2'; c.add(); c.year = '2026';
fixture.detectChanges(); await settle();
const states = beforePanels.map(p => p.applied), results = beforePanels.map(p => p.result());
const titleIds = beforePanels.map(p => p.titleId);
expect(new Set(titleIds).size).toBe(beforePanels.length);
const snapshots = states.map(s => JSON.stringify(s)), hosts = beforeCharts.map(c => c.host.nativeElement);
const selects = fixture.debugElement.queryAll(By.directive(MatSelect)).filter(e => e.componentInstance.multiple);
const writes = selects.map(e => vi.spyOn(e.injector.get(NgModel).control, 'setValue'));
const memory = TestBed.inject(IndicadoresMemory), saves = vi.spyOn(memory, 'saveGlobal'), restores = vi.spyOn(memory, 'restoreGlobal');
const reacts = runtime.react.mock.calls.length;
const helps = [...fixture.nativeElement.querySelectorAll('.methodology-toggle')] as HTMLButtonElement[];
expect(helps).toHaveLength(5);
const helpIds = helps.map(button => button.getAttribute('aria-controls')!);
expect(new Set(helpIds).size).toBe(5);
for (const id of helpIds) expect(document.getElementById(id)?.hidden).toBe(true);
helps[0].click(); fixture.detectChanges();
http.expectOne(r => r.url.endsWith('/metadatos')).flush({});
fixture.detectChanges(); await settle();
expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false', 'false', 'false']);
expect(helpIds.map(id => document.getElementById(id)?.hidden)).toEqual([false, true, true, true, true]);
for (const query of ['sexo', 'evaluacion', '']) {
if (query) await search(query);
else { fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle(); }
for (const card of beforeCards) expect(cards().find(c => c.indicador.id === card.indicador.id)).toBe(card);
for (const panel of beforePanels) expect(panels().find(p => p.indicador.id === panel.indicador.id)).toBe(panel);
beforeFilters.forEach(c => expect(filters().find(f => f.state === c.state)).toBe(c));
beforeCharts.forEach(c => expect(charts().find(chart => chart.host.nativeElement === c.host.nativeElement)).toBe(c));
}
expect(cards()).toEqual(beforeCards); expect(beforeCards.slice(0, 3).every(c => c.visible)).toBe(true);
for (const button of helps) expect(button.isConnected).toBe(true);
expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false', 'false', 'false']);
helps[0].click(); fixture.detectChanges(); await settle();
expect(document.getElementById(helpIds[0])?.hidden).toBe(true);
expect(panels()).toEqual(beforePanels); expect(filters()).toEqual(beforeFilters); expect(charts()).toEqual(beforeCharts);
expect(beforePanels.map(p => p.titleId)).toEqual(titleIds);
for (const id of titleIds) {
const heading = document.getElementById(id)!;
expect(heading.tagName).toBe('H3'); expect(heading.parentElement!.getAttribute('aria-labelledby')).toBe(id);
}
beforePanels.forEach((p, i) => { expect(p.applied).toBe(states[i]); expect(JSON.stringify(p.applied)).toBe(snapshots[i]); expect(p.result()).toBe(results[i]); });
beforeCharts.forEach((c, i) => expect(c.host.nativeElement).toBe(hosts[i]));
expect(c.year).toBe('2026'); expect(c.unit).toBe('S2'); expect(c.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
for (const write of writes) expect(write).not.toHaveBeenCalled();
expect(saves).not.toHaveBeenCalled(); expect(restores).not.toHaveBeenCalled();
expect(runtime.react).toHaveBeenCalledTimes(reacts); expect(runtime.purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled();
http.expectNone(() => true);
});
it('cambiar de dominio restablece la selección', () => {
load(); choose(['A01']);
page.changeDominio('cacu'); fixture.detectChanges(); expect(page.indicatorSelection()).toBeNull();
load(items, 'cacu'); expect(ids()).toEqual(items.map(i => i.id));
it('reordenar conserva un panel cargando y otro con error; completar y reintentar siguen siendo independientes', async () => {
load(); cards().slice(0, 3).forEach(c => c.setVisible(true)); fixture.detectChanges();
const before = panels(), a = request('A01'), b = request('B02'), c = request('M02_sexo');
b.flush('private', { status: 404, statusText: 'Not Found' }); c.flush({ data: [{ y: [3] }], layout: {} }); await settle();
await search('sexo'); expect(a.cancelled).toBe(false); expect(before[0].result().status).toBe('loading'); expect(before[1].result().status).toBe('error');
expect(panels()).toEqual([before[2], before[0], before[1]]); http.expectNone(() => true);
a.flush({ data: [{ y: [1] }], layout: {} }); await settle(); expect(before[0].result().figure?.data[0]['y']).toEqual([1]);
const other = before[2].result(); before[1].requestFigure(); request('B02').flush({ data: [{ y: [2] }], layout: {} });
expect(before[2].result()).toBe(other); await search(''); expect(panels()).toEqual(before); http.expectNone(() => true);
});
it('reordenar el catálogo conserva foco en el selector global existente', async () => {
load(); cards()[2].setVisible(true); fixture.detectChanges(); respond(); await settle();
filters()[0].changeMode('manual'); fixture.detectChanges(); await settle();
const field = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-period-filters mat-select') as NodeListOf<HTMLElement>).at(-1)!;
field.focus(); expect(document.activeElement).toBe(field);
page.changeSearchQuery('sexo'); fixture.detectChanges(); await settle();
expect(document.activeElement).toBe(field); expect(field.isConnected).toBe(true);
page.changeSearchQuery(''); fixture.detectChanges(); await settle(); expect(document.activeElement).toBe(field);
http.expectNone(() => true);
});
it('cambiar de dominio limpia búsqueda y volver conserva figura y borrador mediante memoria existente', async () => {
load(); cards()[2].setVisible(true); fixture.detectChanges(); respond(); await settle();
filters()[0].changeMode('manual'); filters()[0].year = '2025'; filters()[0].unit = 'S1'; filters()[0].add();
await search('sexo'); page.changeDominio('cacu'); fixture.detectChanges(); expect(page.searchQuery()).toBe('');
load([{ ...items[0], figuras: [] }], 'cacu'); expect(input()).toBeNull(); expect(cards()[0].visible).toBe(false);
page.changeDominio('tea'); fixture.detectChanges(); load(); expect(page.searchQuery()).toBe('');
expect(cards().map(c => c.visible)).toEqual([false, false, false, false, false]);
http.expectNone(() => true); cards()[2].setVisible(true); fixture.detectChanges();
const r = request('M02_sexo'); expect(r.request.params.has('periodos')).toBe(false); r.flush({ data: [], layout: {} });
expect(filters()[0].selectedPeriods).toEqual(['2025-S1']);
await search('sexo'); fixture.destroy(); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); load(); respond();
expect(page.searchQuery()).toBe(''); expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id));
});
});
@@ -31,16 +31,14 @@ describe('Secciones compartidas por dominio', () => {
});
afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
it.each(DOMINIOS)('entrada directa en %s presenta sus pestañas y Resumen seleccionado', async domain => {
it.each(DOMINIOS)('entrada directa en %s presenta tres pestañas y Resumen seleccionado', async domain => {
const harness = await RouterTestingHarness.create();
const page = await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage);
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
const root = harness.routeNativeElement!;
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
expect(tabs.map(t => t.textContent?.trim())).toEqual(domain === 'tea'
? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']);
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(tabs.map((_, i) => String(i === 0)));
const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;
expect(tabs.map(t => t.textContent?.trim())).toEqual(['Resumen', 'Seguimiento', 'Datos y definiciones']);
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(['true', 'false', 'false']);
expect(root.querySelector('[role="tablist"]')?.getAttribute('aria-label')).toContain(page.domainLabels[domain]);
// Upstream moved domain selection to its own App shell; ours keeps it on
// the page itself (see indicadores-page.html), since our shell is shared
@@ -52,9 +50,9 @@ describe('Secciones compartidas por dominio', () => {
expect(panel.hidden).toBe(tab.id !== 'tab-resumen');
}
const cards = harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance);
tab('seguimiento').click(); harness.detectChanges();
if (domain === 'cacu' || domain === 'tea') {
http.expectOne(r => r.url === '/' + domain + '/seguimiento').flush({}, { status: 404, statusText: 'Pending' });
tabs[1].click(); harness.detectChanges();
if (domain === 'cacu') {
http.expectOne(r => r.url === '/cacu/seguimiento').flush({}, { status: 404, statusText: 'Pending' });
harness.detectChanges();
}
const tracking = root.querySelector<HTMLElement>('#panel-seguimiento')!;
@@ -63,18 +61,15 @@ describe('Secciones compartidas por dominio', () => {
if (domain === 'cacu') {
expect(tracking.querySelector('tbody')).toBeNull();
expect(tracking.querySelector('input[type=date]')).not.toBeNull();
} else if (domain === 'tea') {
expect(tracking.querySelector('tbody')).toBeNull();
expect(tracking.querySelector('input[type=date]')).not.toBeNull();
} else {
expect(tracking.querySelectorAll('thead th')).toHaveLength(6);
expect(tracking.querySelectorAll('tbody tr')).toHaveLength(1);
expect(tracking.querySelector('tbody td')?.getAttribute('colspan')).toBe('6');
expect(tracking.querySelectorAll('input,button,select')).toHaveLength(0);
}
tab('datos').click(); harness.detectChanges();
tabs[2].click(); harness.detectChanges();
expect(root.querySelector<HTMLElement>('#panel-datos')!.hidden).toBe(false);
tab('resumen').click(); harness.detectChanges();
tabs[0].click(); harness.detectChanges();
expect(harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance)).toEqual(cards);
http.expectNone(() => true); // No patient, metadata, catalog or figure requests on section changes.
});
@@ -96,15 +91,15 @@ describe('Secciones compartidas por dominio', () => {
const page = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
http.expectOne('/tea/indicadores').flush(catalog); harness.detectChanges();
const tabs = Array.from(harness.routeNativeElement!.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
expect(tabs.map(t => t.tabIndex)).toEqual([0, -1, -1, -1]);
expect(tabs.map(t => t.tabIndex)).toEqual([0, -1, -1]);
const focus = tabs.map(tab => vi.spyOn(tab, 'focus'));
function key(index: number, key: string, target: number) {
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
tabs[index].dispatchEvent(event); expect(event.defaultPrevented).toBe(true);
expect(focus[target]).toHaveBeenCalled(); expect(page.activeSection()).toBe('resumen');
}
key(0, 'ArrowRight', 1); key(0, 'ArrowLeft', 3); key(1, 'Home', 0); key(0, 'End', 3);
tabs[3].click(); harness.detectChanges(); expect(tabs.map(t => t.tabIndex)).toEqual([-1, -1, -1, 0]);
key(0, 'ArrowRight', 1); key(0, 'ArrowLeft', 2); key(1, 'Home', 0); key(0, 'End', 2);
tabs[2].click(); harness.detectChanges(); expect(tabs.map(t => t.tabIndex)).toEqual([-1, -1, 0]);
http.expectNone(() => true);
});
@@ -1,28 +0,0 @@
import { C2Distribution } from './indicadores-c2-adapter';
import { highlightFigure } from './indicadores-highlight';
import { teaC2Donut } from './indicadores-tea-c2';
const categoria = (id: string, label: string, value: number, color: string, parentId?: string) => ({ id, label, value, color, parentId });
const modelo = (extra: object = {}) => ({ period: '2025-S2', unit: 'paciente', title: 'T', total: 380, notes: [], nodes: [], parents: [],
categories: [categoria('CONFIRMADO', 'Diagnóstico confirmado', 338, '#A8C243'), categoria('EN_PROCESO', 'En proceso', 42, '#B8433A')], ...extra }) as unknown as C2Distribution;
describe('Dona C2 de TEA', () => {
it('sin grupos dibuja un anillo con rótulos, el total al centro y un botón por categoría', () => {
const { figure, highlight } = teaC2Donut(modelo(), 'claro', { text: 'T' })!;
expect(figure.data).toHaveLength(1);
expect(figure.data[0]).toMatchObject({ type: 'pie', values: [338, 42], labels: ['Diagnóstico confirmado', 'En proceso'] });
expect(figure.data[0]['text']).toEqual(['Diagnóstico confirmado<br>88.9 %', 'En proceso<br>11.1 %']);
expect((figure.layout['annotations'] as { text: string }[])[0].text).toBe('<b>380</b><br>TOTAL');
expect(highlight.groups).toEqual([]);
expect(highlight.items.map(i => [i.label, i.color])).toEqual([['Diagnóstico confirmado', '#A8C243'], ['En proceso', '#B8433A']]);
});
it('al elegir una categoría atenúa la otra y muestra su número al centro', () => {
const { figure, highlight } = teaC2Donut(modelo(), 'claro', { text: 'T' })!;
const elegida = highlightFigure(figure, highlight, { item: 'EN_PROCESO' });
expect((elegida.data[0]['marker'] as { colors: string[] }).colors).toEqual(['rgba(168, 194, 67, 0.3)', 'rgba(184,67,58,1)']);
expect((elegida.layout['annotations'] as { text: string }[])[0].text).toBe('<b>42</b><br>En proceso');
});
it('sin pacientes no dibuja nada', () => {
expect(teaC2Donut(modelo({ total: 0 }), 'claro', {})).toBeUndefined();
});
});
@@ -1,48 +0,0 @@
import { C2Distribution } from './indicadores-c2-adapter';
import { c2Color, c2Theme } from './indicadores-c2-palette';
import { Categoria, dona, Grupo, Modelo } from './indicadores-eu7-escenario';
import { donaHighlight, FigureHighlight } from './indicadores-highlight';
import { PlotlyFigure, Tema } from './indicadores.models';
// TEA (mock): C2 distributions with groups are drawn like CaCu's «Distribución de resultados
// citológicos», both rings at once with highlight buttons, instead of the drill-down donut.
const average = (colors: string[]) => '#' + [1, 3, 5].map(i => Math.round(colors.reduce((s, c) => s + parseInt(c.slice(i, i + 2), 16), 0) / colors.length)
.toString(16).padStart(2, '0')).join('').toUpperCase();
const hex = (c: string | undefined, i: number) => { const v = c2Color(c, i); return /^#[0-9a-f]{6}$/i.test(v) ? v : c2Color(undefined, i); };
export function teaC2Donut(model: C2Distribution, tema: Tema, title: unknown): { figure: PlotlyFigure; highlight: FigureHighlight } | undefined {
if (model.total === 0) return undefined;
const unAnillo = !model.parents.length;
const categorias: Categoria[] = model.categories.map((c, i) => ({ id: c.id, etiqueta: c.label, color: hex(c.color, i), grupo: unAnillo ? 'total' : 'group:' + c.parentId }));
// A group takes the average colour of its categories, as in CaCu.
const padres = unAnillo ? [{ id: 'total', label: 'TOTAL' }] : model.parents;
const grupos: Grupo[] = padres.map(p => ({ id: p.id, etiqueta: p.label, color: average(categorias.filter(c => c.grupo === p.id).map(c => c.color)) }));
const celdas: Modelo['celdas'] = Object.fromEntries(model.categories.map(c => [c.id, { n: c.value, estado: 'Publicado' as const }]));
const modelo: Modelo = { periodo: model.period, categorias, grupos, celdas, total: model.total, sinDato: { n: 0, estado: 'Publicado' },
escenarios: [], vacio: false, notas: [...model.notes], sinDatoEtiqueta: '' };
const figure = dona(modelo, {}, tema);
const unit = model.unit.endsWith('s') ? model.unit : model.unit + 's';
for (const trace of figure.data.slice(1)) trace['hovertemplate'] = '%{label}<br>%{customdata[0]} ' + unit + ', %{customdata[1]} % de ' + model.total + '<extra></extra>';
figure.layout = { ...figure.layout, title };
if (unAnillo) {
// Without groups, only the categories' ring around the total, like M21's donut.
figure.data = [{ ...figure.data[2], hole: .6 }];
figure.layout = { ...figure.layout, annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false,
text: '<b>' + model.total.toLocaleString('es-MX') + '</b><br>TOTAL', font: { size: 20, color: c2Theme(tema).text } }] };
return { figure, highlight: { groups: [], traces: [0], center: { annotation: 0 }, allLabel: 'TOTAL',
items: categorias.map((c, i) => ({ id: c.id, label: c.etiqueta, color: c.color, points: [{ trace: 0, index: i }],
center: '<b>' + celdas[c.id].n!.toLocaleString('es-MX') + '</b><br>' + c.etiqueta })) } };
}
return { figure, highlight: donaHighlight(modelo) };
}
// Buttons for the C2 bars: one per category (bar), and its group highlights all of its bars.
export function c2BarsHighlight(model: C2Distribution): FigureHighlight {
const items = model.categories.map((c, i) => ({ id: c.id, label: c.label, color: hex(c.color, i),
group: c.parentId ? 'group:' + c.parentId : undefined, points: [{ trace: 0, index: i }] }));
const groups = model.parents.map(p => {
const children = items.filter(c => c.group === p.id);
return { id: p.id, label: p.label, color: average(children.map(c => c.color)), points: children.flatMap(c => c.points) };
});
return { groups, items, traces: [0], allLabel: 'Todas las categorías' };
}
@@ -5,7 +5,7 @@
}
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado'">
<h2>Seguimiento de {{ domainLabel }}</h2>
@if (dominio !== 'cacu' && dominio !== 'tea') {
@if (dominio !== 'cacu') {
<p>El seguimiento aún no está disponible.</p>
<div class="tracking-table" role="region" aria-label="Estructura prevista de seguimiento" tabindex="0">
<table>
@@ -19,32 +19,13 @@
<label>Ventana de meses <select name="meses" [(ngModel)]="draft.meses">
@for (m of [1,3,6,12]; track m) { <option [ngValue]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</option> }
</select></label>
<label>{{ dominio === 'tea' ? 'Alteraciones EEG' : 'Estatus de seguimiento' }} <select name="estatus" [(ngModel)]="draft.estatus">
<option [ngValue]="undefined">{{ dominio === 'tea' ? 'Todas' : 'Todos' }}</option>
<label>Estatus de seguimiento <select name="estatus" [(ngModel)]="draft.estatus">
<option [ngValue]="undefined">Todos</option>
@for (s of statuses; track s.codigo) { <option [value]="s.codigo">{{ s.etiqueta }}</option> }
</select></label>
@if (dominio === 'tea') {
<label>Grupo de edad <select name="grupo_edad" [(ngModel)]="draft.grupo_edad">
<option [ngValue]="undefined">Todos</option>
@for (g of gruposEdad; track g) { <option [value]="g">{{ g }}</option> }
</select></label>
<label>Puntaje M-CHAT <select name="mchat" [(ngModel)]="draft.mchat">
<option [ngValue]="undefined">Todos</option>
@for (r of rangosMchat; track r.codigo) { <option [value]="r.codigo">{{ r.etiqueta }}</option> }
</select></label>
<label>CSS ADOS-2 <select name="css" [(ngModel)]="draft.css">
<option [ngValue]="undefined">Todos</option>
@for (r of rangosCss; track r.codigo) { <option [value]="r.codigo">{{ r.etiqueta }}</option> }
</select></label>
<label>Estado del caso <select name="estado_caso" [(ngModel)]="draft.estado_caso">
<option [ngValue]="undefined">Todos</option>
@for (e of estadosCaso; track e.codigo) { <option [value]="e.codigo">{{ e.etiqueta }}</option> }
</select></label>
<label>Tipo de alteración <select name="alteracion" [(ngModel)]="draft.alteracion">
<option [ngValue]="undefined">Todas</option>
@for (t of tiposAlteracion; track t.codigo) { <option [value]="t.codigo">{{ t.etiqueta }}</option> }
</select></label>
}
<label>Ordenar por prioridad <select name="prioridad" disabled>
<option>No disponible</option>
</select></label>
<label>Registros por página <input name="size" type="number" min="1" max="200" required [(ngModel)]="draft.page_size" /></label>
<button type="submit" [disabled]="status === 'loading'">Consultar</button>
</form>
@@ -52,47 +33,8 @@
@if (status === 'pending') { <p role="status">El seguimiento aún no está disponible para esta consulta. Funcionalidad pendiente de publicación.</p> }
@if (message && status !== 'pending') { <p role="alert">{{ message }}</p> }
@if (status === 'error' || status === 'pending') { <button type="button" (click)="retry()">Reintentar seguimiento</button> }
@if (response; as response) {
@if (data; as response) {
<p>Ventana consultada: {{ response.ventana.desde }} al {{ response.ventana.hasta }}.</p>
}
@if (teaData; as response) {
<section class="resumen-eeg" aria-labelledby="resumen-eeg-titulo">
<h3 id="resumen-eeg-titulo">EEG de los pacientes filtrados</h3>
<dl>
<div><dt>Normales</dt><dd>{{ response.resumen_eeg.normales }}</dd></div>
<div><dt>Anormales</dt><dd>{{ response.resumen_eeg.anormales }}</dd></div>
<div><dt>Sin EEG</dt><dd>{{ response.resumen_eeg.sin_eeg }}</dd></div>
@for (a of response.resumen_eeg.por_alteracion; track a.codigo) {
<div class="tipo"><dt>{{ a.etiqueta }}</dt><dd>{{ a.n }}</dd></div>
}
</dl>
<p>Un paciente con dos alteraciones cuenta en ambas, así que los tipos pueden sumar más que los anormales.</p>
</section>
<div class="tracking-table" role="region" aria-label="Lista de seguimiento de demostración" tabindex="0">
<table>
<caption>Resultados disponibles por paciente</caption>
<thead><tr><th scope="col">Identificador seudónimo</th><th scope="col">Grupo de edad</th><th scope="col">Estado del caso</th><th scope="col">Último EEG</th><th scope="col">Puntaje M-CHAT</th><th scope="col">CSS ADOS-2</th><th scope="col">Alteraciones EEG</th></tr></thead>
<tbody>
@for (item of response.items; track item.id_seudonimo) {
<tr class="tea-row" [class.abierta]="teaAbierto === item.id_seudonimo" (click)="alternarTea(item.id_seudonimo, $event)">
<td><button class="row-toggle" type="button" [attr.aria-expanded]="teaAbierto === item.id_seudonimo" [attr.aria-controls]="'tea-detalle-' + item.id_seudonimo"
[attr.aria-label]="(teaAbierto === item.id_seudonimo ? 'Ocultar' : 'Ver') + ' resumen del paciente ' + item.id_seudonimo" (click)="alternarTea(item.id_seudonimo, $event)">
<span class="chevron" aria-hidden="true"></span>{{ item.id_seudonimo }}</button></td>
<td>{{ item.grupo_edad }}</td>
<td><span class="estado-caso" [attr.data-estado]="item.estado_caso">{{ etiquetaEstado[item.estado_caso] }}</span>
@if (item.pendientes.length) { <small>Falta: {{ item.pendientes.join(', ') }}</small> }</td>
<td>{{ item.ultimo_eeg ?? 'No disponible' }}</td>
<td>{{ item.mchat ?? 'No disponible' }}</td>
<td>{{ item.css_ados2 ?? 'No disponible' }}@if (item.modulo_ados2) { <small>Módulo {{ item.modulo_ados2 }}</small> }</td>
<td>@if (item.alteraciones_eeg; as eeg) { <span class="eeg" [class.eeg-anormal]="eeg === 'anormal'">{{ eeg === 'anormal' ? 'Anormal' : 'Normal' }}</span> } @else { No disponible }</td></tr>
@if (teaAbierto === item.id_seudonimo) {
<tr class="tea-detalle" [id]="'tea-detalle-' + item.id_seudonimo"><td colspan="7"><app-tea-paciente-resumen [id]="item.id_seudonimo" /></td></tr>
}
} @empty { <tr><td colspan="7">No hay registros para los filtros aplicados.</td></tr> }
</tbody>
</table>
</div>
} @else if (data; as response) {
<div class="tracking-table" role="region" aria-label="Lista de seguimiento de demostración" tabindex="0">
<table>
<caption>Resultados disponibles por paciente</caption>
@@ -109,8 +51,6 @@
</tbody>
</table>
</div>
}
@if (response; as response) {
<nav aria-label="Paginación de seguimiento">
<button type="button" [disabled]="response.paginacion.page <= 1" (click)="navigate(response.paginacion.page - 1)">Anterior</button>
<span>Página {{ response.paginacion.page }} de {{ response.paginacion.total_pages }}, {{ response.paginacion.total_items }} registros</span>
@@ -15,30 +15,9 @@ caption { text-align: start; padding: 1rem; }
th, td { text-align: start; vertical-align: top; padding: 1rem; border-top: 1px solid var(--issste-border); }
th { background: var(--issste-background); font-weight: 600; }
small { display: block; margin-top: .35rem; }
.resumen-eeg { margin-bottom: 1rem; padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
.resumen-eeg h3 { margin: 0 0 .75rem; font-size: 1.1rem; }
.resumen-eeg dl { display: flex; flex-wrap: wrap; gap: 1rem 2rem; margin: 0; }
.resumen-eeg dt { color: var(--issste-text-secondary); font-size: .9rem; }
.resumen-eeg dd { margin: .2rem 0 0; font-size: 1.5rem; font-weight: 700; }
.resumen-eeg .tipo dd { font-size: 1.15rem; font-weight: 600; }
.resumen-eeg p { margin: .75rem 0 0; font-size: .85rem; }
.estado-caso { font-weight: 600; }
.estado-caso[data-estado=en_proceso] { color: #B26A00; }
.estado-caso[data-estado=fuera_protocolo] { color: var(--issste-text-secondary); }
nav { display: flex; flex-wrap: wrap; align-items: center; gap: 1rem; margin-top: 1rem; }
tbody tr[data-paciente] { cursor: pointer; transition: background-color 120ms ease; }
tbody tr[data-paciente]:hover { background-color: color-mix(in srgb, var(--issste-accent) 7%, transparent); }
tbody tr[data-paciente]:focus-within { outline: 2px solid var(--issste-accent); outline-offset: -2px; }
.patient-link { min-height: 44px; padding: .35rem .5rem; border: 0; border-radius: var(--issste-radius); background: transparent; color: var(--issste-accent); font: inherit; font-weight: 600; text-align: left; text-decoration: underline; text-underline-offset: .15em; cursor: pointer; }
.patient-link:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; }
.eeg { display: inline-block; padding: .15rem .6rem; border-radius: 999px; border: 1px solid var(--issste-border); font-weight: 600; }
.eeg-anormal { border-color: var(--issste-accent); color: var(--issste-accent); }
tbody tr.tea-row { cursor: pointer; transition: background-color 120ms ease; }
tbody tr.tea-row:hover, tbody tr.tea-row.abierta { background-color: color-mix(in srgb, var(--issste-accent) 7%, transparent); }
.row-toggle { display: inline-flex; align-items: center; gap: .5rem; min-height: 44px; padding: .35rem .5rem; border: 0; background: transparent;
color: var(--issste-text); font: inherit; font-weight: 600; text-align: left; cursor: pointer; }
.chevron { width: .5rem; height: .5rem; border-right: 2px solid currentColor; border-bottom: 2px solid currentColor; transform: rotate(-45deg); transition: transform 150ms ease; }
.row-toggle[aria-expanded=true] .chevron { transform: rotate(45deg); }
@media (prefers-reduced-motion: reduce) { .chevron, tbody tr.tea-row { transition: none; } }
tbody tr.tea-detalle > td { padding: 1rem; border-top: 0; background: var(--issste-background); }
// TEA patient window (mock: odd-numbered patients), laid out like CaCu's patient page.
@@ -10,12 +10,10 @@ import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle';
import { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state';
import { Dominio } from './indicadores.models';
import { IndicadoresService } from './indicadores.service';
import { ALTERACIONES_EEG, ESTADOS_CASO, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service';
import { TeaPacienteResumen } from './tea-paciente-resumen';
@Component({
selector: 'app-indicadores-tracking',
imports: [FormsModule, MatButtonModule, PacienteDetalleComponent, TeaPacienteResumen],
imports: [FormsModule, MatButtonModule, PacienteDetalleComponent],
providers: [PacienteDetalleState],
templateUrl: './indicadores-tracking.html',
styleUrl: './indicadores-tracking.scss',
@@ -26,7 +24,6 @@ export class IndicadoresTracking implements OnChanges {
@Input() active = false;
private readonly service = inject(CacuSeguimientoService);
private readonly indicators = inject(IndicadoresService);
private readonly teaService = inject(TeaSeguimientoService);
private readonly destroy = inject(DestroyRef);
private readonly changeDetector = inject(ChangeDetectorRef);
private readonly injector = inject(Injector);
@@ -34,36 +31,24 @@ export class IndicadoresTracking implements OnChanges {
readonly fichaPacienteAbierta = output<boolean>();
private controlPaciente?: HTMLElement;
private readonly requests = new Subject<SeguimientoQuery | null>();
private readonly teaRequests = new Subject<SeguimientoQuery | null>();
private initialized = false;
private previousDomain?: Dominio;
status: 'idle' | 'loading' | 'ready' | 'pending' | 'error' = 'idle';
message = '';
data?: SeguimientoResponse;
teaData?: TeaSeguimientoResponse;
// One open summary at a time, like an accordion.
teaAbierto?: string;
statuses: SeguimientoStatus[] = [];
private metadataLoaded = false;
categories: Record<string, { etiqueta: string; color?: string | null }> = {};
draft: SeguimientoQuery = { meses: 3, page: 1, page_size: 50 };
private applied: SeguimientoQuery = { ...this.draft };
readonly latestStudy = latestStudy;
readonly gruposEdad = GRUPOS_EDAD_TEA;
readonly rangosMchat = RANGOS_MCHAT;
readonly rangosCss = RANGOS_CSS;
readonly etiquetaEstado = ESTADOS_CASO;
readonly estadosCaso = Object.entries(ESTADOS_CASO).map(([codigo, etiqueta]) => ({ codigo, etiqueta }));
// Kept from the last answer, so the filter doesn't empty while a query is running.
tiposAlteracion: { codigo: string; etiqueta: string }[] = [];
get provisional() { return this.data?.reglas.some(r => r.estado === 'provisional'); }
get response() { return this.dominio === 'tea' ? this.teaData : this.data; }
constructor() {
const failure = (error: unknown, q: SeguimientoQuery) => of({ data: undefined, status: error instanceof HttpErrorResponse && error.status === 404 && q.page === 1 ? 'pending' as const : 'error' as const,
message: error instanceof HttpErrorResponse && error.status === 400 ? 'Revisa la fecha, la ventana y los filtros seleccionados.'
: error instanceof HttpErrorResponse && error.status === 404 ? 'El seguimiento aún no está disponible para esta consulta.' : 'No se pudo consultar el seguimiento. Intenta nuevamente.' });
this.requests.pipe(switchMap(q => q ? defer(() => this.service.consultar(q)).pipe(
map(data => ({ data, message: '', status: 'ready' as const })), catchError(error => failure(error, q))) : of(null)), takeUntilDestroyed(this.destroy)).subscribe(result => {
map(data => ({ data, message: '', status: 'ready' as const })),
catchError(error => of({ data: undefined, status: error instanceof HttpErrorResponse && error.status === 404 && q.page === 1 ? 'pending' as const : 'error' as const,
message: error instanceof HttpErrorResponse && error.status === 400 ? 'Revisa la fecha, la ventana y los filtros seleccionados.'
: error instanceof HttpErrorResponse && error.status === 404 ? 'El seguimiento aún no está disponible para esta consulta.' : 'No se pudo consultar el seguimiento. Intenta nuevamente.' }))) : of(null)), takeUntilDestroyed(this.destroy)).subscribe(result => {
if (!result) return;
this.changeDetector.markForCheck();
this.status = result.status; this.data = result.data; this.message = result.message;
@@ -81,39 +66,25 @@ export class IndicadoresTracking implements OnChanges {
}
}
});
this.teaRequests.pipe(switchMap(q => q ? defer(() => this.teaService.consultar(q)).pipe(
map(data => ({ data, message: '', status: 'ready' as const })), catchError(error => failure(error, q))) : of(null)), takeUntilDestroyed(this.destroy)).subscribe(result => {
if (!result) return;
this.changeDetector.markForCheck();
this.status = result.status; this.teaData = result.data; this.message = result.message; this.teaAbierto = undefined;
if (result.data) {
const data = result.data;
this.tiposAlteracion = data.tipos_alteracion;
this.applied = { ...this.applied, corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.alteraciones_eeg ?? undefined, page: data.paginacion.page, page_size: data.paginacion.page_size };
this.draft = { ...this.applied };
}
});
}
ngOnChanges() {
if (this.previousDomain !== this.dominio) {
if (this.pacienteDetalle.estado().tipo !== 'cerrado') this.fichaPacienteAbierta.emit(false);
this.pacienteDetalle.cerrar(); this.controlPaciente = undefined;
this.previousDomain = this.dominio; this.requests.next(null); this.teaRequests.next(null); this.data = undefined; this.teaData = undefined;
this.previousDomain = this.dominio; this.requests.next(null); this.data = undefined;
this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50 }; this.applied = { ...this.draft };
}
if (this.dominio === 'cacu' && this.active && !this.initialized) { this.initialized = true; this.load(this.applied); }
if (this.dominio === 'tea' && this.active && !this.initialized) { this.initialized = true; this.statuses = ALTERACIONES_EEG; this.load(this.applied); }
}
private load(q: SeguimientoQuery) {
if (this.dominio !== 'cacu' && this.dominio !== 'tea') return;
if (this.dominio !== 'cacu') return;
if (!validSeguimientoQuery(q)) { this.message = 'Revisa la fecha, la ventana y el tamaño de página (1 a 200).'; return; }
this.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.applied = { ...q };
(this.dominio === 'tea' ? this.teaRequests : this.requests).next(q);
this.status = 'loading'; this.message = ''; this.data = undefined; this.applied = { ...q }; this.requests.next(q);
}
apply() { this.load({ ...this.draft, page: 1 }); }
retry() { this.load(this.applied); }
navigate(page: number) {
if (!this.response || page < 1 || page > this.response.paginacion.total_pages) return;
if (!this.data || page < 1 || page > this.data.paginacion.total_pages) return;
this.load({ ...this.applied, page });
}
abrirPaciente(paciente: SeguimientoPaciente, evento: Event) {
@@ -129,12 +100,6 @@ export class IndicadoresTracking implements OnChanges {
this.pacienteDetalle.abrir(paciente, this.data.corte);
this.fichaPacienteAbierta.emit(true);
}
alternarTea(id: string, evento: Event) {
evento.stopPropagation();
// Row clicks that land on a control are left to that control.
if (evento.currentTarget instanceof HTMLTableRowElement && evento.target instanceof HTMLElement && evento.target.closest('button, a, input, select, textarea')) return;
this.teaAbierto = this.teaAbierto === id ? undefined : id;
}
volverASeguimiento() {
this.pacienteDetalle.cerrar();
this.fichaPacienteAbierta.emit(false);
@@ -137,8 +137,6 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
const before = cards(), panel = panels()[0], result = panel.result();
for (const section of ['seguimiento', 'datos'] as const) {
page.changeSection(section); await render();
// TEA's Seguimiento loads its patient list; that request is unrelated to the cards.
for (const req of http.match(r => r.url === '/tea/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' });
// Even stale geometry/observer notifications cannot activate hidden cards.
positions(cards().map(() => [200, 0])); notify(1); await idle();
expect(cards().every(card => !card.visible)).toBe(true); http.expectNone(() => true);
@@ -154,13 +152,13 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
const panel = panels()[0], chart = fixture.nativeElement.querySelector('app-plotly-chart');
positions([[-1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); window.dispatchEvent(new Event('scroll')); await idle();
const filters = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
filters.select([]); filters.year = '2025'; filters.unit = 'S1'; filters.add(); page.applyFilters(); await render();
filters.changeMode('manual'); filters.year = '2025'; filters.unit = 'S1'; filters.add(); page.applyFilters(); await render();
filters.year = '2025'; filters.unit = 'S2'; filters.add(); page.applyFilters(); page.changeTema('oscuro'); await render(); await idle();
expect(panels()[0]).toBe(panel); expect(panel.result().status).toBe('deferred');
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); http.expectNone(() => true);
positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm();
const request = http.expectOne(r => r.url.includes('/i0/figuras/'));
expect(request.request.params.get('periodos')).toBe('2025-S2'); expect(request.request.params.get('tema')).toBe('oscuro');
expect(request.request.params.get('periodos')).toBe('2025-S1,2025-S2'); expect(request.request.params.get('tema')).toBe('oscuro');
request.flush({ data: [{ y: [2] }], layout: {} }); await render(); notify(); await idle(); http.expectNone(() => true);
});
it('aplicar antes del frame de scroll relee geometría y cancela petición obsoleta sin nueva descarga', async () => {
@@ -181,16 +179,15 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
cards()[0].selectFigure('g'); await render(); http.expectNone(() => true); expect(panels()[0].result().status).toBe('deferred');
positions([[200, 0]]); notify(); await confirm(); http.expectOne(r => r.url.endsWith('/figuras/g')).flush({ data: [], layout: {} });
});
it('fijación y selección conservan componentes y descartan callbacks con geometría antigua', async () => {
it('fijación y búsqueda conservan componentes y descartan callbacks con geometría antigua', async () => {
await load(); const before = cards(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]);
const target = before[0].visibilityRegion!.nativeElement; notify(); page.togglePinned(items[4]); await render();
page.changeIndicatorSelection([items[3].id, items[4].id]); await render(); positions(cards().map((_, i) => [1200 + i * 1000, 0]));
page.changeSearchQuery('Indicador 3'); await render(); positions(cards().map((_, i) => [1200 + i * 1000, 0]));
observer().emit(target); await idle(); http.expectNone(() => true);
// The pinned indicator leads; the other selected one keeps its component.
expect(cards()).toEqual([before[4], before[3]]);
positions(cards().map((_, i) => [i === 1 ? 200 : 1200 + i * 1000, 0])); notify(); await confirm();
expect(cards()[0]).toBe(before[3]); expect(cards()[1]).toBe(before[4]); expect(cards().every(c => before.includes(c))).toBe(true);
positions(cards().map((_, i) => [i === 0 ? 200 : 1200 + i * 1000, 0])); notify(); await confirm();
http.expectOne(r => r.url.includes('/i3/figuras/')).flush({ data: [], layout: {} }); await render();
expect(cards()[1].selectedFigure).toBe('f');
expect(cards()[0].selectedFigure).toBe('f');
});
it.each([{ data: [], layout: {} }, { data: [{ y: [null, null] }], layout: { annotations: [{ text: 'Valores ocultos por supresión.' }] } }])('resultado vacío o suprimido termina skeleton y conserva JSON: %j', async figure => {
await load([items[0]]); positions([[200, 0]]); notify(); await confirm();
@@ -236,7 +233,6 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
expect(chart.host.nativeElement).toBe(host); expect(runtime.purge).not.toHaveBeenCalled();
for (const section of ['seguimiento', 'datos', 'resumen'] as const) {
page.changeSection(section); await idle();
for (const req of http.match(r => r.url === '/tea/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' });
expect(chart.host.nativeElement).toBe(host); expect(runtime.purge).not.toHaveBeenCalled();
expect(runtime.react).toHaveBeenCalledTimes(1); http.expectNone(() => true);
}
@@ -16,8 +16,6 @@ export interface Indicador {
figuras: string[];
tipos_periodo: TipoPeriodo[];
filtros?: IndicadorFiltro[];
// Tabs that show it; without this field, all of them.
vistas?: string[];
}
export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado';
export interface IndicadorFiltro { estrato: string; etiqueta: string; valores: { valor: string; etiqueta: string }[]; }
@@ -63,14 +61,6 @@ export interface PlotlyFigure {
export type Tema = 'claro' | 'oscuro';
export interface FigureSelection { dominio?: Dominio; tipoPeriodo?: TipoPeriodo; indicador: string; figura: string; tema: Tema; periodos?: string[]; }
// A measure may publish more groups next to `group` (TEA's EEG result: one per alteration). The rows without those
// of the other published groups; a row of a group nobody published stays, for the caller to refuse.
export function filasDelGrupo(data: IndicadorDatos, group: string): Record<string, unknown>[] {
const published = data['grupos'];
const others = new Set(Object.keys(published && typeof published === 'object' ? published : {}).filter(id => id !== group));
return others.size ? data.filas.filter(row => !others.has(row['grupo'] as string)) : data.filas;
}
export function parsePeriodos(value: string, tipo: TipoPeriodo = 'semestre'): string[] | null {
if (tipo !== 'semestre' && tipo !== 'mes') return null;
const parts = value.split(',').map(part => part.trim());
@@ -1,7 +1,7 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { DatosScope, Dominio, IndicadorDatos, IndicadorMetadatos, FigureSelection, Indicador, parsePeriodos, PlotlyFigure, requireDominio, TipoPeriodo } from './indicadores.models';
import { DatosScope, Dominio, IndicadorDatos, IndicadorMetadatos, FigureSelection, Indicador, parsePeriodos, PlotlyFigure, requireDominio } from './indicadores.models';
function record(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
@@ -11,116 +11,100 @@ export class IndicadoresService {
private readonly http = inject(HttpClient);
catalogo(dominio: Dominio = 'tea') {
const domain = requireDominio(dominio);
return this.http.get<unknown>(`/${domain}/indicadores`).pipe(map(catalogoValido));
return this.http.get<unknown>(`/${domain}/indicadores`).pipe(map(value => {
if (!Array.isArray(value) || !value.every(item => record(item)
&& typeof item['id'] === 'string' && item['id'].trim().length > 0 && typeof item['titulo'] === 'string'
&& typeof item['contrato'] === 'string' && Array.isArray(item['figuras'])
&& (item['version'] === undefined || typeof item['version'] === 'string')
&& item['figuras'].every((figure: unknown) => typeof figure === 'string' && figure.trim().length > 0)
&& new Set(item['figuras']).size === item['figuras'].length
&& Array.isArray(item['tipos_periodo']) && item['tipos_periodo'].length > 0
&& item['tipos_periodo'].every((tipo: unknown) => tipo === 'semestre' || tipo === 'mes')
&& new Set(item['tipos_periodo']).size === item['tipos_periodo'].length)) {
throw new Error('Respuesta de catálogo inválida');
}
if (new Set(value.map(item => item['id'])).size !== value.length) throw new Error('IDs de catálogo duplicados');
return value as Indicador[];
}));
}
metadatos(dominio: Dominio, indicador: string) {
return this.http.get<unknown>(`/${requireDominio(dominio)}/indicadores/${encodeURIComponent(indicador)}/metadatos`).pipe(map(metadatosValidos));
return this.http.get<unknown>(`/${requireDominio(dominio)}/indicadores/${encodeURIComponent(indicador)}/metadatos`).pipe(map(value => {
if (!record(value)) throw new Error('Metadatos inválidos');
const description = value['descripcion'];
if (description !== undefined && description !== null && typeof description !== 'string') throw new Error('Metadatos inválidos');
const ficha = value['ficha'];
if (ficha !== undefined && ficha !== null) {
if (!record(ficha)) throw new Error('Metadatos inválidos');
for (const field of ['codigo', 'para', 'unidad', 'pregunta', 'definicion', 'nota']) {
const content = ficha[field];
if (content !== undefined && content !== null && typeof content !== 'string') throw new Error('Metadatos inválidos');
}
}
for (const field of ['referencias', 'poblaciones']) {
const list = value[field];
if (list !== undefined && list !== null && (!Array.isArray(list) || !list.every(v => record(v) && (field === 'referencias'
? typeof v['tipo'] === 'string' && typeof v['etiqueta'] === 'string' && (v['ref'] === null || typeof v['ref'] === 'string')
: typeof v['grupo'] === 'string' && typeof v['codigo'] === 'string' && typeof v['descripcion'] === 'string')))) throw new Error('Metadatos inválidos');
}
const figureDetails = value['figuras_detalle'];
if (figureDetails !== undefined && figureDetails !== null && (!Array.isArray(figureDetails) || !figureDetails.every(v => record(v)
&& typeof v['figura'] === 'string' && v['figura'].trim().length > 0
&& (v['descripcion'] === null || typeof v['descripcion'] === 'string')
&& (v['como_leer'] === null || Array.isArray(v['como_leer']) && v['como_leer'].every(line => typeof line === 'string'))))) {
throw new Error('Metadatos inválidos');
}
if (Array.isArray(figureDetails) && new Set(figureDetails.map(item => (item as Record<string, unknown>)['figura'])).size !== figureDetails.length) {
throw new Error('Metadatos inválidos');
}
return value as IndicadorMetadatos;
}));
}
datos(dominio: Dominio, indicador: string, tipo: TipoPeriodo, periodos?: string[], scope: DatosScope = {}) {
datos(dominio: Dominio, indicador: string, tipo: 'semestre' | 'mes', periodos?: string[], scope: DatosScope = {}) {
const domain = requireDominio(dominio);
const params = datosParams(tipo, periodos, scope);
return this.http.get<unknown>(`/${domain}/indicadores/${encodeURIComponent(indicador)}/datos`, { params })
.pipe(map(value => datosValidos(value, indicador, tipo, periodos, scope)));
if (periodos && (!periodos.length || parsePeriodos(periodos.join(','), tipo) === null)) {
throw new Error('Periodos inválidos');
}
let params = new HttpParams();
if (scope.estrato) {
if (!['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado'].includes(scope.estrato)) throw new Error('Dimensión no admitida');
params = params.set('estrato', scope.estrato);
}
if (scope.filtros?.length) params = params.set('filtro', scope.filtros.join(','));
if (periodos) params = params.set('periodos', [...new Set(periodos)].join(','));
return this.http.get<unknown>(`/${domain}/indicadores/${encodeURIComponent(indicador)}/datos`, { params }).pipe(map(value => {
if (!record(value) || value['id'] !== indicador || typeof value['contrato'] !== 'string'
|| value['tipo_periodo'] !== tipo
|| !Array.isArray(value['periodos']) || !value['periodos'].every(p => typeof p === 'string')
|| !Array.isArray(value['filas']) || !value['filas'].every(record)
|| (value['notas'] !== undefined && (!Array.isArray(value['notas']) || !value['notas'].every(n => typeof n === 'string')))) {
throw new Error('Respuesta de datos inválida');
}
const publishedPeriods = value['periodos'] as string[];
if ((value['estrato'] ?? undefined) !== scope.estrato) throw new Error('Dimensión recibida distinta de la solicitada');
if ((periodos && publishedPeriods.some(p => !periodos.includes(p)))
|| value['filas'].some(row => typeof row['periodo'] !== 'string' || !publishedPeriods.includes(row['periodo']))) {
throw new Error('Los datos recibidos no corresponden a los periodos solicitados');
}
return value as unknown as IndicadorDatos;
}));
}
figura(selection: FigureSelection) {
const dominio = requireDominio(selection.dominio ?? 'tea');
if (selection.periodos !== undefined) {
if (!selection.periodos.length) throw new Error('Selección explícita vacía');
const text = selection.periodos.join(',');
const tipos = selection.tipoPeriodo ? [selection.tipoPeriodo] : (['semestre', 'mes'] as const);
if (!tipos.some(tipo => parsePeriodos(text, tipo) !== null)) {
throw new Error('Periodos inválidos o de tipos mezclados');
}
}
let params = new HttpParams().set('tema', selection.tema);
const periodos = figuraPeriodos(selection);
if (periodos) params = params.set('periodos', periodos.join(','));
if (selection.periodos?.length) params = params.set('periodos', [...new Set(selection.periodos.map(periodo => periodo.trim()))].join(','));
const url = `/${dominio}/indicadores/${encodeURIComponent(selection.indicador)}/figuras/${encodeURIComponent(selection.figura)}`;
return this.http.get<unknown>(url, { params }).pipe(map(figuraValida));
return this.http.get<unknown>(url, { params }).pipe(map(value => {
if (!record(value) || !Array.isArray(value['data']) || !value['data'].every(record)
|| !record(value['layout'])) throw new Error('Respuesta de figura inválida');
return value as unknown as PlotlyFigure;
}));
}
}
export function catalogoValido(value: unknown): Indicador[] {
if (!Array.isArray(value) || !value.every(item => record(item)
&& typeof item['id'] === 'string' && item['id'].trim().length > 0 && typeof item['titulo'] === 'string'
&& typeof item['contrato'] === 'string' && Array.isArray(item['figuras'])
&& (item['version'] === undefined || typeof item['version'] === 'string')
&& item['figuras'].every((figure: unknown) => typeof figure === 'string' && figure.trim().length > 0)
&& new Set(item['figuras']).size === item['figuras'].length
&& Array.isArray(item['tipos_periodo']) && item['tipos_periodo'].length > 0
&& item['tipos_periodo'].every((tipo: unknown) => tipo === 'semestre' || tipo === 'mes')
&& new Set(item['tipos_periodo']).size === item['tipos_periodo'].length)) {
throw new Error('Respuesta de catálogo inválida');
}
if (new Set(value.map(item => item['id'])).size !== value.length) throw new Error('IDs de catálogo duplicados');
return value as Indicador[];
}
export function metadatosValidos(value: unknown): IndicadorMetadatos {
if (!record(value)) throw new Error('Metadatos inválidos');
const description = value['descripcion'];
if (description !== undefined && description !== null && typeof description !== 'string') throw new Error('Metadatos inválidos');
const ficha = value['ficha'];
if (ficha !== undefined && ficha !== null) {
if (!record(ficha)) throw new Error('Metadatos inválidos');
for (const field of ['codigo', 'para', 'unidad', 'pregunta', 'definicion', 'nota']) {
const content = ficha[field];
if (content !== undefined && content !== null && typeof content !== 'string') throw new Error('Metadatos inválidos');
}
}
for (const field of ['referencias', 'poblaciones']) {
const list = value[field];
if (list !== undefined && list !== null && (!Array.isArray(list) || !list.every(v => record(v) && (field === 'referencias'
? typeof v['tipo'] === 'string' && typeof v['etiqueta'] === 'string' && (v['ref'] === null || typeof v['ref'] === 'string')
: typeof v['grupo'] === 'string' && typeof v['codigo'] === 'string' && typeof v['descripcion'] === 'string')))) throw new Error('Metadatos inválidos');
}
const figureDetails = value['figuras_detalle'];
if (figureDetails !== undefined && figureDetails !== null && (!Array.isArray(figureDetails) || !figureDetails.every(v => record(v)
&& typeof v['figura'] === 'string' && v['figura'].trim().length > 0
&& (v['descripcion'] === null || typeof v['descripcion'] === 'string')
&& (v['como_leer'] === null || Array.isArray(v['como_leer']) && v['como_leer'].every(line => typeof line === 'string'))))) {
throw new Error('Metadatos inválidos');
}
if (Array.isArray(figureDetails) && new Set(figureDetails.map(item => (item as Record<string, unknown>)['figura'])).size !== figureDetails.length) {
throw new Error('Metadatos inválidos');
}
return value as IndicadorMetadatos;
}
// The `/datos` query; throws on a period list or dimension the contract doesn't admit.
export function datosParams(tipo: TipoPeriodo, periodos?: string[], scope: DatosScope = {}) {
if (periodos && (!periodos.length || parsePeriodos(periodos.join(','), tipo) === null)) {
throw new Error('Periodos inválidos');
}
let params = new HttpParams();
if (scope.estrato) {
if (!['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado'].includes(scope.estrato)) throw new Error('Dimensión no admitida');
params = params.set('estrato', scope.estrato);
}
if (scope.filtros?.length) params = params.set('filtro', scope.filtros.join(','));
if (periodos) params = params.set('periodos', [...new Set(periodos)].join(','));
return params;
}
export function datosValidos(value: unknown, indicador: string, tipo: TipoPeriodo, periodos?: string[], scope: DatosScope = {}): IndicadorDatos {
if (!record(value) || value['id'] !== indicador || typeof value['contrato'] !== 'string'
|| value['tipo_periodo'] !== tipo
|| !Array.isArray(value['periodos']) || !value['periodos'].every(p => typeof p === 'string')
|| !Array.isArray(value['filas']) || !value['filas'].every(record)
|| (value['notas'] !== undefined && (!Array.isArray(value['notas']) || !value['notas'].every(n => typeof n === 'string')))) {
throw new Error('Respuesta de datos inválida');
}
const publishedPeriods = value['periodos'] as string[];
if ((value['estrato'] ?? undefined) !== scope.estrato) throw new Error('Dimensión recibida distinta de la solicitada');
if ((periodos && publishedPeriods.some(p => !periodos.includes(p)))
|| value['filas'].some(row => typeof row['periodo'] !== 'string' || !publishedPeriods.includes(row['periodo']))) {
throw new Error('Los datos recibidos no corresponden a los periodos solicitados');
}
return value as unknown as IndicadorDatos;
}
// The figure's explicit periods, trimmed and unique; throws on an empty list or mixed period types.
export function figuraPeriodos(selection: FigureSelection): string[] | undefined {
if (selection.periodos !== undefined) {
if (!selection.periodos.length) throw new Error('Selección explícita vacía');
const text = selection.periodos.join(',');
const tipos = selection.tipoPeriodo ? [selection.tipoPeriodo] : (['semestre', 'mes'] as const);
if (!tipos.some(tipo => parsePeriodos(text, tipo) !== null)) {
throw new Error('Periodos inválidos o de tipos mezclados');
}
}
return selection.periodos?.length ? [...new Set(selection.periodos.map(periodo => periodo.trim()))] : undefined;
}
export function figuraValida(value: unknown): PlotlyFigure {
if (!record(value) || !Array.isArray(value['data']) || !value['data'].every(record)
|| !record(value['layout'])) throw new Error('Respuesta de figura inválida');
return value as unknown as PlotlyFigure;
}
@@ -284,8 +284,6 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
expect(root.querySelector('app-paciente-detalle')).toBeNull();
expect(fixture.componentInstance.pacienteDetalle.estado().tipo).toBe('cerrado');
expect(root.querySelector('tbody button')).toBeNull();
// TEA loads its own list, which has no patient-detail buttons.
http.expectOne(r => r.url === '/tea/seguimiento');
http.expectNone(() => true);
});
@@ -1,104 +0,0 @@
@if (status() === 'loading') { <p role="status">Cargando resumen del paciente…</p> }
@if (status() === 'error') {
<p role="alert">No se pudo cargar el resumen del paciente.</p>
<button type="button" (click)="load()">Reintentar resumen</button>
}
@if (status() === 'ready' && detalle(); as d) {
<div class="resumen" [class.sin-eeg]="!d.eeg">
<section class="panel ados" aria-label="Resumen ADOS-2">
<h3>ADOS-2</h3>
@if (d.ados2; as a) {
<p class="meta">Módulo {{ a.modulo }} · {{ a.algoritmo }} · {{ a.fecha }}</p>
<div class="headline">
<span class="css" [attr.data-nivel]="a.nivel_css">CSS {{ a.css }}<small>de 10</small></span>
<span><strong>{{ nivelCss[a.nivel_css] }}</strong><small>Clasificación: {{ clasificacion[a.clasificacion] }}</small><small>Total del algoritmo: {{ a.total }} / {{ a.total_maximo }}</small></span>
</div>
@for (dom of a.dominios; track dom.codigo) {
<div class="dominio">
<span>{{ dom.etiqueta }} ({{ dom.codigo }})</span><span>{{ dom.puntaje }} / {{ dom.maximo }}</span>
<span class="bar" aria-hidden="true"><span [style.width.%]="pct(dom.puntaje, dom.maximo)"></span></span>
</div>
}
<details>
<summary>Puntajes por reactivo</summary>
<table class="reactivos">
<thead><tr><th scope="col">Reactivo</th><th scope="col">Puntaje</th><th scope="col">Algoritmo</th></tr></thead>
@for (dom of a.dominios; track dom.codigo) {
<tbody>
<tr><th scope="rowgroup" colspan="3">{{ dom.etiqueta }}</th></tr>
@for (r of dom.reactivos; track r.codigo) {
<tr><td>{{ r.codigo }} · {{ r.etiqueta }}</td><td>{{ r.puntaje }}</td><td>{{ r.puntaje_algoritmo }}</td></tr>
}
</tbody>
}
</table>
</details>
} @else { <p>Sin evaluación ADOS-2 registrada.</p> }
</section>
<section class="panel calidad" aria-label="Calidad del EEG">
<h3>Calidad del EEG @if (d.eeg) { <span class="mock">Datos de ejemplo</span> }</h3>
@if (d.eeg; as e) {
<p class="meta">{{ e.fecha }} · {{ e.duracion_min }} min · {{ e.canales }} canales</p>
<div class="headline">
<span class="css" [attr.data-calidad]="e.calidad"><strong>{{ calidad[e.calidad] }}</strong></span>
<small>La calificación general es la peor de sus criterios.</small>
</div>
<dl>
@for (c of e.criterios_calidad; track c.codigo) {
<dt>{{ c.etiqueta }}</dt><dd [attr.data-calidad]="c.nivel">{{ c.valor }} {{ c.unidad === 'canales' ? 'de ' + e.canales : c.unidad }}</dd>
}
</dl>
} @else { <p>Sin EEG registrado.</p> }
</section>
@if (d.eeg; as e) {
<div class="alteraciones-zona" [class.abierta]="mapaActual(e)">
<section class="panel alteraciones" aria-label="Alteraciones del EEG">
<h3>Alteraciones del EEG <span class="mock">Datos de ejemplo</span></h3>
<p class="meta">Referencia neurotípica para {{ d.grupo_edad }} y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas.</p>
@if (!alteradas(e).length) { <p class="sin-alteraciones">Sin alteraciones en las métricas evaluadas.</p> }
<ul class="metricas">
@for (m of e.alteraciones; track m.codigo) {
<li [attr.data-estado]="m.estado">
<div class="metrica">
<button type="button" class="nombre" [disabled]="m.estado === 'no_evaluable'" [attr.aria-expanded]="m.estado === 'no_evaluable' ? null : mapaActual(e)?.codigo === m.codigo"
[attr.aria-controls]="'zonas-' + d.id_seudonimo" (click)="elegirMapa(e, m.codigo)">{{ m.etiqueta }}</button>
<span class="estado">{{ estado[m.estado] }}</span>
</div>
@if (m.valor !== null) {
<p class="valor">{{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · referencia {{ m.referencia.min }}–{{ m.referencia.max }} · z = {{ m.valor_z }}</p>
} @else {
<p class="valor">Sin registro de sueño en el estudio.</p>
}
@if (m.efectos.length) {
<p class="efectos-titulo">Posibles efectos asociados</p>
<ul class="efectos">
@for (efecto of m.efectos; track efecto) { <li>{{ efecto }}</li> }
</ul>
}
</li>
}
</ul>
</section>
@if (mapaActual(e); as mapa) {
<div class="marco-mapa"><section class="mapa" [id]="'zonas-' + d.id_seudonimo" aria-label="Mapa de zonas afectadas">
<h3>Zonas más afectadas</h3>
<p class="meta">{{ mapa.metrica }} · mapa ilustrativo</p>
<p class="leyenda-mapa"><span class="azul" aria-hidden="true"></span>Azul: menos actividad <span class="rojo" aria-hidden="true"></span>Rojo: más actividad</p>
@if (figura) {
<app-plotly-chart [figure]="figura" [showNotes]="false" [style.--plot-height]="'260px'"
[label]="'Mapa topográfico del EEG del paciente ' + d.id_seudonimo" />
}
<ol class="regiones" aria-label="Regiones ordenadas por desviación">
@for (r of mapa.regiones; track r.codigo) {
<li [class.destacada]="r.valor_z >= 2 || r.valor_z <= -2"><span>{{ r.etiqueta }}</span><span>z = {{ r.valor_z }}</span></li>
}
</ol>
</section></div>
}
</div>
}
</div>
}
@@ -1,74 +0,0 @@
:host { display: block; container-type: inline-size; }
.resumen { display: grid; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); gap: .75rem; }
.panel { min-width: 0; padding: .75rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); }
h3 { margin: 0 0 .15rem; font-size: 1rem; }
.meta { margin: 0 0 .5rem; font-size: .8rem; color: var(--issste-text-secondary); }
.headline { display: flex; align-items: center; gap: .75rem; margin-bottom: .5rem; font-size: .9rem; }
.headline small { display: block; margin-top: .1rem; color: var(--issste-text-secondary); }
.css { display: inline-flex; flex-direction: column; align-items: center; justify-content: center; min-width: 3.75rem; padding: .3rem .4rem;
border: 2px solid var(--issste-border); border-radius: var(--issste-radius); font-size: 1.1rem; font-weight: 700; }
.css small { margin: 0; font-size: .7rem; font-weight: 400; }
.css[data-nivel=alto], .css[data-calidad=malo] { border-color: #B3261E; color: #B3261E; }
.css[data-nivel=moderado], .css[data-calidad=aceptable] { border-color: #B26A00; color: #B26A00; }
.css[data-nivel=bajo], .css[data-nivel=minimo], .css[data-calidad=bueno] { border-color: var(--issste-accent); }
.css[data-calidad] { flex: none; white-space: nowrap; }
dd[data-calidad=malo] { color: #B3261E; }
// The button's area covers its whole card, so the card is clickable without nesting the effects list in a button.
button.nombre { margin: 0; min-height: 0; padding: 0; border: 0; background: none; color: inherit; font: inherit; text-align: start; cursor: pointer; }
button.nombre::after { content: ''; position: absolute; inset: 0; border-radius: inherit; }
button.nombre:disabled { cursor: default; }
button.nombre:focus-visible { outline: none; }
button.nombre:focus-visible::after { outline: 2px solid var(--issste-text); outline-offset: 2px; }
.leyenda-mapa { display: flex; flex-wrap: wrap; align-items: center; gap: .35rem; margin: .25rem 0; font-size: .8rem; }
.leyenda-mapa span { width: .8rem; height: .8rem; border-radius: 2px; }
.leyenda-mapa .azul { background: #2166AC; }
.leyenda-mapa .rojo { margin-inline-start: .5rem; background: #B2182B; }
dd[data-calidad=aceptable] { color: #B26A00; }
.dominio { display: grid; grid-template-columns: 1fr auto; gap: .15rem 1rem; margin-bottom: .4rem; font-size: .85rem; }
.bar { grid-column: 1 / -1; height: .375rem; border-radius: 999px; background: var(--issste-border); overflow: hidden; }
.bar span { display: block; height: 100%; background: var(--issste-text); }
details { margin-top: .5rem; }
summary { cursor: pointer; font-weight: 600; font-size: .9rem; min-height: 44px; display: flex; align-items: center; gap: .5rem; list-style: none; }
summary::-webkit-details-marker { display: none; }
// A right-pointing triangle that turns down when the details are open.
summary::before { content: ''; flex: none; border-block: .35rem solid transparent; border-inline-start: .5rem solid currentColor; transition: transform 150ms ease; }
details[open] > summary::before { transform: rotate(90deg); }
@media (prefers-reduced-motion: reduce) { summary::before { transition: none; } }
.reactivos { width: 100%; min-width: 0; font-size: .85rem; border-collapse: collapse; }
.reactivos th, .reactivos td { padding: .25rem .4rem; border-top: 1px solid var(--issste-border); text-align: start; }
.reactivos td:not(:first-child), .reactivos thead th:not(:first-child) { text-align: end; white-space: nowrap; }
.reactivos tbody th { background: var(--issste-background); }
dl { display: grid; grid-template-columns: 1fr auto; gap: .25rem 1rem; margin: 0; font-size: .85rem; }
dt { color: var(--issste-text-secondary); } dd { margin: 0; text-align: end; font-weight: 600; }
.regiones { margin: .25rem 0 0; padding-inline-start: 1.25rem; font-size: .85rem; }
.regiones li { padding: .1rem 0; }
.regiones li span:last-child { float: inline-end; font-variant-numeric: tabular-nums; }
.regiones .destacada { font-weight: 700; }
h3 .mock { display: inline-block; white-space: nowrap; margin-inline-start: .5rem; padding: .1rem .5rem; border: 1px dashed var(--issste-border); border-radius: 999px;
font-size: .75rem; font-weight: 400; color: var(--issste-text-secondary); vertical-align: middle; }
.sin-alteraciones { margin: 0 0 .75rem; font-weight: 600; }
.metricas, .efectos { margin: 0; padding: 0; list-style: none; }
// The map has its final width from the start, because Plotly draws at the width it finds: its column only reveals it.
.alteraciones-zona { container: zona / inline-size; grid-column: 1 / -1; display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 0fr); align-items: start; transition: grid-template-columns 300ms ease; }
.alteraciones-zona.abierta { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 1rem; }
.marco-mapa { min-width: 0; overflow: hidden; }
.mapa { box-sizing: border-box; width: calc(50cqw - .5rem); padding-top: .75rem; animation: aparecer 300ms ease; }
.mapa h3 { margin-top: 0; }
@keyframes aparecer { from { opacity: 0; } }
@container (min-width: 68rem) { .alteraciones-zona { grid-column: span 2; } }
@container zona (max-width: 42rem) { .mapa { width: 100cqw; } }
@container (max-width: 42rem) { .alteraciones-zona.abierta { grid-template-columns: minmax(0, 1fr); } }
@media (prefers-reduced-motion: reduce) { .alteraciones-zona { transition: none; } .mapa { animation: none; } }
.metricas { display: grid; grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr)); gap: .5rem; align-items: start; }
.metricas > li { position: relative; padding: .5rem .6rem; border: 1px solid var(--issste-border); border-inline-start-width: 4px; border-radius: var(--issste-radius); transition: background-color 120ms ease; }
.metricas > li:has(button:not(:disabled)):hover { background: color-mix(in srgb, var(--issste-accent) 8%, transparent); }
.metricas > li:has(button[aria-expanded=true]) { border-color: var(--issste-accent); background: color-mix(in srgb, var(--issste-accent) 12%, transparent); }
.metricas > li[data-estado=aumentado], .metricas > li[data-estado=disminuido] { border-inline-start-color: #B3261E; }
.metrica { display: flex; flex-wrap: wrap; justify-content: space-between; gap: .1rem 1rem; font-size: .9rem; font-weight: 600; }
li[data-estado=aumentado] .estado, li[data-estado=disminuido] .estado { color: #B3261E; }
li[data-estado=normal] .estado { color: var(--issste-text-secondary); font-weight: 400; }
li[data-estado=no_evaluable] .estado { color: var(--issste-text-secondary); font-weight: 400; font-style: italic; }
.valor { margin: .1rem 0 0; font-size: .8rem; color: var(--issste-text-secondary); font-variant-numeric: tabular-nums; }
.efectos-titulo { margin: .3rem 0 .1rem; font-size: .8rem; font-weight: 600; }
.efectos { padding-inline-start: 1.1rem; list-style: disc; font-size: .8rem; }
button { min-height: 44px; padding: .6rem; border: 1px solid var(--issste-border); border-radius: 4px; background: var(--issste-surface); color: inherit; font: inherit; cursor: pointer; }
@@ -1,96 +0,0 @@
import { Component, DestroyRef, ElementRef, inject, Input, OnInit, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { PlotlyFigure } from './indicadores.models';
import { TeaAdos2, TeaAlteracionEstado, TeaEeg, TeaEegMapa, TeaPacienteDetalle, TeaSeguimientoService } from './tea-seguimiento.service';
const CLASIFICACION: Record<TeaAdos2['clasificacion'], string> = { autismo: 'Autismo', espectro_autista: 'Espectro autista', no_espectro: 'No espectro' };
// ADOS-2 calibrated severity score ranges.
const NIVEL_CSS: Record<TeaAdos2['nivel_css'], string> = { minimo: 'Evidencia mínima o nula', bajo: 'Nivel bajo', moderado: 'Nivel moderado', alto: 'Nivel alto' };
const CALIDAD: Record<TeaEeg['calidad'], string> = { bueno: 'Bueno', aceptable: 'Aceptable', malo: 'Malo' };
const ESTADO: Record<TeaAlteracionEstado, string> = { normal: 'Dentro de referencia', aumentado: 'Aumentado', disminuido: 'Disminuido', no_evaluable: 'No evaluable' };
const INK = '#081839';
// Shape paths have no arcs: the hole is a polygon, wound against the frame so it stays empty under either fill rule.
const HOLE = Array.from({ length: 96 }, (_, i) => -2 * Math.PI * i / 96)
.map((a, i) => `${i ? 'L' : 'M'} ${Math.cos(a).toFixed(4)} ${Math.sin(a).toFixed(4)}`).join(' ');
// A frame with a round hole hides the map outside the head, in the colour behind the map; then the head outline, nose and ears.
const headShapes = (fondo: string) => [
{ type: 'path', path: `M -2 -2 L 2 -2 L 2 2 L -2 2 Z ${HOLE} Z`, fillrule: 'evenodd', fillcolor: fondo, line: { width: 0 } },
{ type: 'circle', xref: 'x', yref: 'y', x0: -1, y0: -1, x1: 1, y1: 1, line: { color: INK, width: 2 } },
{ type: 'path', path: 'M -0.13 0.99 L 0 1.13 L 0.13 0.99', line: { color: INK, width: 2 } },
{ type: 'path', path: 'M -0.99 0.14 Q -1.1 0.12 -1.08 0 Q -1.1 -0.12 -0.99 -0.14', line: { color: INK, width: 2 } },
{ type: 'path', path: 'M 0.99 0.14 Q 1.1 0.12 1.08 0 Q 1.1 -0.12 0.99 -0.14', line: { color: INK, width: 2 } },
];
export function mapaFigure(eeg: TeaEeg, mapa: TeaEegMapa, fondo = '#FFFFFF'): PlotlyFigure {
const m = { ...eeg.ejes_mapa, z: mapa.z };
return {
data: [
{ type: 'contour', x: m.x, y: m.y, z: m.z, zmin: -3, zmax: 3, zmid: 0, colorscale: 'RdBu', connectgaps: false,
contours: { coloring: 'heatmap', showlines: true }, line: { width: .5, color: 'rgba(8,24,57,.3)' },
colorbar: { title: { text: 'z', side: 'top' }, thickness: 12, len: .8 }, hovertemplate: 'z = %{z:.2f}<extra></extra>' },
{ type: 'scatter', mode: 'markers+text', x: m.electrodos.map(e => e.x), y: m.electrodos.map(e => e.y), text: m.electrodos.map(e => e.nombre),
textposition: 'top center', textfont: { size: 9, color: INK }, marker: { size: 5, color: INK }, hoverinfo: 'text', showlegend: false },
],
layout: {
margin: { l: 8, r: 8, t: 8, b: 8 }, showlegend: false, shapes: headShapes(fondo),
paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)',
xaxis: { visible: false, range: [-1.2, 1.2], fixedrange: true },
yaxis: { visible: false, range: [-1.15, 1.2], scaleanchor: 'x', fixedrange: true },
},
config: { displayModeBar: false },
};
}
@Component({
selector: 'app-tea-paciente-resumen',
imports: [PlotlyChart],
templateUrl: './tea-paciente-resumen.html',
styleUrl: './tea-paciente-resumen.scss',
})
export class TeaPacienteResumen implements OnInit {
@Input({ required: true }) id = '';
private readonly service = inject(TeaSeguimientoService);
private readonly destroy = inject(DestroyRef);
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
readonly detalle = signal<TeaPacienteDetalle | undefined>(undefined);
figura?: PlotlyFigure;
private mapaElegido?: string;
private readonly elemento = inject<ElementRef<HTMLElement>>(ElementRef);
// The first solid background around this component: the map has no box of its own.
private fondo() {
for (let e: HTMLElement | null = this.elemento.nativeElement; e; e = e.parentElement) {
const color = getComputedStyle(e).backgroundColor;
if (/^rgb\(/.test(color)) return color;
}
return '#FFFFFF';
}
mapaActual(eeg: TeaEeg) { return eeg.mapas.find(m => m.codigo === this.mapaElegido); }
elegirMapa(eeg: TeaEeg, codigo: string) {
// The chosen card closes the map again, and the cards take the whole space back.
const mapa = codigo === this.mapaElegido ? undefined : eeg.mapas.find(m => m.codigo === codigo);
this.mapaElegido = mapa?.codigo;
this.figura = mapa && mapaFigure(eeg, mapa, this.fondo());
}
readonly clasificacion = CLASIFICACION;
readonly nivelCss = NIVEL_CSS;
readonly calidad = CALIDAD;
readonly estado = ESTADO;
ngOnInit() { this.load(); }
load() {
this.status.set('loading');
this.service.detalle(this.id).pipe(takeUntilDestroyed(this.destroy)).subscribe({
next: d => {
// Opens on the first altered metric, or on the first one if none is altered.
const e = d.eeg, inicial = e?.mapas.find(m => e.alteraciones.some(a => a.codigo === m.codigo && a.estado !== 'normal')) ?? e?.mapas[0];
this.mapaElegido = inicial?.codigo;
this.figura = e && inicial ? mapaFigure(e, inicial, this.fondo()) : undefined;
this.detalle.set(d); this.status.set('ready');
},
error: () => this.status.set('error'),
});
}
alteradas(eeg: TeaEeg) { return eeg.alteraciones.filter(m => m.estado === 'aumentado' || m.estado === 'disminuido'); }
pct(value: number, max: number) { return max > 0 ? Math.round(100 * value / max) : 0; }
}
@@ -1,56 +0,0 @@
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { IndicadorKpiPanel } from './indicador-kpi-panel';
import { TeaResumenPeriodo } from './tea-resumen-periodo';
type Result = { state: string; value?: string | number; loading?: boolean; period?: string; categorias?: Record<string, number> };
function panel(id: string, result: Result) {
return { definition: { id }, result: signal(result), retry: vi.fn() } as unknown as IndicadorKpiPanel & { result: ReturnType<typeof signal<Result>>; retry: ReturnType<typeof vi.fn> };
}
const listo = (value: string | number, period = '2025-S2'): Result => ({ state: 'Disponible', value, period });
describe('Resumen TEA por periodo', () => {
function render(paneles: IndicadorKpiPanel[]) {
const fixture = TestBed.createComponent(TeaResumenPeriodo);
fixture.componentRef.setInput('periodo', '2025-S2'); fixture.componentRef.setInput('paneles', paneles);
fixture.detectChanges();
return fixture;
}
const completos = () => [panel('M28_casos_por_estado', { ...listo(100), categorias: { EEG: 60, SOLO_MCHAT: 15, PSICOLOGIA: 15, NEUROPEDIATRIA: 10 } }), panel('M24_confirmacion_diagnostico', listo('86.5')),
panel('M25_dias_mchat_diagnostico', listo(22)), panel('M21_diagnosticados_con_eeg', listo('71.9')), panel('M22_diagnosticados_sin_eeg', listo('28.1')),
panel('M26_dias_mchat_ados2', listo(8)), panel('M27_dias_ados2_diagnostico', listo(14))];
it('redacta el párrafo con cada población y resalta los valores', () => {
const root: HTMLElement = render(completos()).nativeElement;
const text = root.textContent!.replace(/\s+/g, ' ');
expect(text).toContain('Al cierre del periodo 2025-S2, de los 100 niños en el tamizaje, 60 lo completaron con un EEG de buena calidad y 40 siguen en proceso: 15 solo con M-CHAT, 15 hasta la evaluación psicológica y 10 hasta la evaluación neuropediátrica.');
expect(text).toContain('De los niños con diagnóstico confirmado o en proceso, 86.5 % tiene diagnóstico confirmado de TEA (CIE-10 F84.0).');
expect(text).toContain('La mediana de M-CHAT a ADOS-2 fue de 8 días, de ADOS-2 a diagnóstico, de 14 días, y en total, de M-CHAT a diagnóstico, de 22 días.');
expect(text).toContain('De los niños con diagnóstico confirmado, 71.9 % tienen un EEG de buena calidad y 28.1 % todavía no.');
expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim()))
.toEqual(['2025-S2', '100', '60', '40', '15', '15', '10', '86.5 %', '8 días', '14 días', '22 días', '71.9 %', '28.1 %']);
expect(root.querySelector('button')).toBeNull();
});
it('muestra «sin dato» si falta, está oculto, es de otro periodo o no está publicado', () => {
const paneles = completos();
paneles[1].result.set({ state: 'Dato oculto por tamaño' });
paneles[2].result.set(listo(30, '2025-S1'));
const root: HTMLElement = render(paneles.filter(p => p.definition.id !== 'M22_diagnosticados_sin_eeg')).nativeElement;
const sinDato = Array.from(root.querySelectorAll('.dato.sin-dato'));
expect(sinDato.map(e => e.getAttribute('title'))).toEqual(['Dato oculto por tamaño', 'Disponible', 'Indicador no publicado']);
expect(root.textContent).not.toContain('30 días');
});
it('indica la carga y reintenta solo las consultas con error', () => {
const paneles = completos();
paneles[0].result.set({ state: 'Cargando…', loading: true });
paneles[3].result.set({ state: 'Error de consulta' });
const fixture = render(paneles);
const root: HTMLElement = fixture.nativeElement;
expect(root.querySelector('article')!.getAttribute('aria-busy')).toBe('true');
root.querySelector<HTMLButtonElement>('button')!.click();
expect(paneles[3].retry).toHaveBeenCalledOnce();
expect(paneles[0].retry).not.toHaveBeenCalled();
});
});
@@ -1,80 +0,0 @@
import { NgTemplateOutlet } from '@angular/common';
import { Component, Input } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { IndicadorKpiPanel } from './indicador-kpi-panel';
import { M28_COMPLETO, M28_EN_PROCESO } from './indicadores-kpi';
interface Valor { texto: string; estado: 'listo' | 'cargando' | 'sin_dato'; detalle?: string; }
// TEA summary for one explicit period. It reads the results of the (hidden) KPI panels, so the
// requests, contract checks and suppression rules stay those of the cards. Each sentence names
// its own population: M28, M24, M25 and M21/M22 do not count the same patients.
@Component({
selector: 'app-tea-resumen-periodo',
imports: [MatButtonModule, NgTemplateOutlet],
template: `
<article class="resumen" [attr.aria-busy]="cargando">
<p>
Al cierre del periodo <span class="dato listo">{{ periodo }}</span>, de los <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M28_casos_por_estado', '') }" /> niños en el tamizaje,
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(completo) }" /> lo completaron con un EEG de buena calidad y
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(enProceso) }" /> siguen en proceso:
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(['SOLO_MCHAT']) }" /> solo con M-CHAT,
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(['PSICOLOGIA']) }" /> hasta la evaluación psicológica y
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(['NEUROPEDIATRIA']) }" /> hasta la evaluación neuropediátrica.
De los niños con diagnóstico confirmado o en proceso, <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M24_confirmacion_diagnostico', ' %') }" />
tiene diagnóstico confirmado de TEA (CIE-10 F84.0). La mediana de M-CHAT a ADOS-2 fue de <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M26_dias_mchat_ados2', ' días') }" />, de ADOS-2 a diagnóstico, de
<ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M27_dias_ados2_diagnostico', ' días') }" />, y en total, de M-CHAT a diagnóstico, de
<ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M25_dias_mchat_diagnostico', ' días') }" />.
De los niños con diagnóstico confirmado, <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M21_diagnosticados_con_eeg', ' %') }" />
tienen un EEG de buena calidad y <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M22_diagnosticados_sin_eeg', ' %') }" /> todavía no.
</p>
@if (conError.length) {
<button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button>
}
</article>
<ng-template #dato let-v>
<span class="dato" [class.listo]="v.estado === 'listo'" [class.sin-dato]="v.estado === 'sin_dato'" [attr.title]="v.detalle ?? null">{{ v.texto }}@if (v.detalle) {<span class="visually-hidden"> ({{ v.detalle }})</span>}</span>
</ng-template>
`,
styles: `
:host { display: block; min-width: 0; }
.resumen { box-sizing: border-box; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
p { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 2.1; overflow-wrap: anywhere; }
.dato { display: inline-block; padding: 0 .5em; border-radius: var(--issste-radius); line-height: 1.6; font-weight: 700; white-space: nowrap;
background: var(--issste-background); border: 1px dashed var(--issste-border); color: var(--issste-text-secondary); }
.dato.listo { background: color-mix(in srgb, var(--issste-accent) 22%, var(--issste-surface)); border: 1px solid var(--issste-accent); color: var(--issste-text); }
.dato.sin-dato { font-weight: 400; font-style: italic; }
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
button { margin-top: var(--issste-space-4); }
`,
})
export class TeaResumenPeriodo {
@Input({ required: true }) periodo!: string;
@Input({ required: true }) paneles: readonly IndicadorKpiPanel[] = [];
// Panels render after this paragraph, so on their first pass their inputs are not set yet.
private panel(id: string) { return this.paneles.find(p => p.definition?.id === id); }
valor(id: string, sufijo: string): Valor {
const result = this.panel(id)?.result();
if (!result) return { texto: 'sin dato', estado: 'sin_dato', detalle: 'Indicador no publicado' };
if (result.loading) return { texto: '…', estado: 'cargando', detalle: 'Cargando' };
// Never show a value from another period in a sentence about this one.
if (result.state !== 'Disponible' || result.value === undefined || result.period !== this.periodo)
return { texto: 'sin dato', estado: 'sin_dato', detalle: result.state };
return { texto: result.value + sufijo, estado: 'listo' };
}
readonly completo = [M28_COMPLETO];
readonly enProceso = M28_EN_PROCESO;
// The children of M28 in some stages, under the same rules as valor().
caso(categorias: readonly string[]): Valor {
const base = this.valor('M28_casos_por_estado', '');
if (base.estado !== 'listo') return base;
const counts = this.panel('M28_casos_por_estado')?.result().categorias;
const n = categorias.map(c => counts?.[c]);
return n.some(v => v === undefined) ? { texto: 'sin dato', estado: 'sin_dato', detalle: 'Etapa no publicada' }
: { texto: String(n.reduce((s, v) => s! + v!, 0)), estado: 'listo' };
}
get cargando() { return this.paneles.some(p => p.result().loading); }
get conError() { return this.paneles.filter(p => p.result().state === 'Error de consulta'); }
reintentar() { this.conError.forEach(p => p.retry()); }
}
@@ -1,275 +0,0 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { forkJoin, map, Observable, of, shareReplay } from 'rxjs';
import { Bundle, code, codeIn, Concept, display, extension, isSimulated, Quantity, referenceId, Resource, resources } from './fhir';
import { estratoValor } from './indicadores-fhir';
import { SeguimientoQuery } from './cacu-seguimiento.models';
import { validSeguimientoQuery } from './cacu-seguimiento.service';
import {
RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad,
teaPacienteDetalle, TeaSeguimientoPaciente, teaSeguimientoResponse, TeaSeguimientoService,
} from './tea-seguimiento.service';
// TEA's follow-up list and patient summary over the WebApi's FHIR endpoint: each child's screening is an
// `EpisodeOfCare` with its resources included, and `Patient/<id>/$resumen-tea` is the summary. Both are mapped into the
// shapes the page already reads, and checked by the same rules.
interface Observation extends Resource {
code?: Concept; effectiveDateTime?: string; subject?: { reference?: string };
valueInteger?: number; valueQuantity?: Quantity; valueString?: string; valueCodeableConcept?: Concept;
interpretation?: Concept[]; dataAbsentReason?: Concept;
referenceRange?: { low?: Quantity; high?: Quantity; text?: string }[];
component?: { code?: Concept; valueInteger?: number; valueQuantity?: Quantity; valueString?: string; valueCodeableConcept?: Concept; extension?: Resource['extension'] }[];
}
interface Report extends Resource {
effectiveDateTime?: string; subject?: { reference?: string }; result?: { reference?: string }[]; conclusionCode?: Concept[];
}
interface Metric { code?: string; display?: string; property?: { code: string; valueString?: string }[] }
const MAX_COUNT = 200;
const METRICAS = 'tea-eeg-metrica';
const INTERPRETACION: Record<string, TeaAlteracionEstado> = { H: 'aumentado', L: 'disminuido', N: 'normal' };
// The 10-20 electrodes on the page's head (x left to right, y back to front, radius 1) and the regions they average.
export const ELECTRODOS: Record<string, [number, number]> = {
Fp1: [-.25, .77], Fp2: [.25, .77], F7: [-.65, .47], F3: [-.33, .4], Fz: [0, .38], F4: [.33, .4], F8: [.65, .47],
T3: [-.8, 0], C3: [-.4, 0], Cz: [0, 0], C4: [.4, 0], T4: [.8, 0],
T5: [-.65, -.47], P3: [-.33, -.4], Pz: [0, -.38], P4: [.33, -.4], T6: [.65, -.47], O1: [-.25, -.77], O2: [.25, -.77],
};
const REGIONES: [string, string, string[]][] = [
['frontal_izq', 'Frontal izquierda', ['Fp1', 'F3', 'F7']], ['frontal_der', 'Frontal derecha', ['Fp2', 'F4', 'F8']],
['central', 'Central', ['Fz', 'C3', 'Cz', 'C4']], ['temporal_izq', 'Temporal izquierda', ['T3', 'T5']],
['temporal_der', 'Temporal derecha', ['T4', 'T6']], ['parietal', 'Parietal', ['P3', 'Pz', 'P4']], ['occipital', 'Occipital', ['O1', 'O2']],
];
const EJE = Array.from({ length: 41 }, (_, i) => Math.round((-1 + i * .05) * 100) / 100);
// How far from a measured electrode the map still shows a value; beyond it, no electrode speaks for the scalp.
const ALCANCE = .45;
const round2 = (value: number) => Math.round(value * 100) / 100;
export const grupoEdad = (codigo: string | undefined) =>
!codigo ? '' : codigo === 'sin_dato' ? 'Sin dato' : `${estratoValor(codigo)} meses`;
const grupoCodigo = (etiqueta: string) => etiqueta.replace(' meses', '').replace('-', '_');
function byCode(observations: Observation[], wanted: string): Observation | undefined {
return observations.find(o => code(o.code) === wanted);
}
function component(o: Observation | undefined, wanted: string) {
return o?.component?.find(c => code(c.code) === wanted);
}
// The map of one metric's electrode z-scores: inverse-distance weights within reach of a measured electrode.
export function mapaDeElectrodos(codigo: string, etiqueta: string, valores: Record<string, number>): TeaEegMapa {
const puntos = Object.entries(valores).filter(([nombre]) => ELECTRODOS[nombre]).map(([nombre, z]) => ({ xy: ELECTRODOS[nombre], z }));
const z = EJE.map(y => EJE.map(x => {
let peso = 0, suma = 0;
for (const p of puntos) {
const d2 = (x - p.xy[0]) ** 2 + (y - p.xy[1]) ** 2;
if (d2 < 1e-9) return round2(p.z);
if (d2 > ALCANCE ** 2) continue;
peso += 1 / d2; suma += p.z / d2;
}
return peso ? round2(suma / peso) : null;
}));
const regiones = REGIONES.flatMap(([c, e, nombres]) => {
const medidos = nombres.filter(n => typeof valores[n] === 'number');
return medidos.length ? [{ codigo: c, etiqueta: e, valor_z: round2(medidos.reduce((s, n) => s + valores[n], 0) / medidos.length) }] : [];
}).sort((a, b) => Math.abs(b.valor_z) - Math.abs(a.valor_z));
return { codigo, metrica: `${etiqueta} (puntuación z)`, z, regiones };
}
export function ados2DeObservacion(o: Observation | undefined): TeaAdos2 | null {
const css = component(o, 'ados2.css')?.valueInteger;
if (!o?.effectiveDateTime || typeof css !== 'number') return null;
const modulo = code(component(o, 'ados2.modulo')?.valueCodeableConcept)?.replace(/^ados2\.modulo\.(MODULO_)?/, '') ?? '';
const clasificacion = code(component(o, 'ados2.clasificacion')?.valueCodeableConcept)?.replace('ados2.clasificacion.', '').toLowerCase();
const items = (o.component ?? []).filter(c => extension(c, 'dominio'));
const dominios: TeaAdosDominio[] = (o.component ?? []).filter(c => codeIn(c.code, 'ados2-dominio')).map(c => {
const codigo = code(c.code)!;
const reactivos = items.filter(i => extension(i, 'dominio')?.valueCode === codigo).map(i => ({
codigo: (code(i.code) ?? '').split('_').pop()!.toUpperCase(),
etiqueta: display(i.code) ?? '',
puntaje: i.valueInteger ?? 0,
puntaje_algoritmo: extension(i, 'puntaje-algoritmo')?.valueInteger ?? 0,
}));
return { codigo, etiqueta: display(c.code) ?? codigo, puntaje: c.valueInteger ?? 0, maximo: 2 * reactivos.length, reactivos };
});
return {
fecha: o.effectiveDateTime.slice(0, 10), modulo, algoritmo: component(o, 'ados2.algoritmo')?.valueString ?? '',
dominios, total: dominios.reduce((t, d) => t + d.puntaje, 0), total_maximo: dominios.reduce((t, d) => t + d.maximo, 0),
clasificacion: (clasificacion ?? 'no_espectro') as TeaAdos2['clasificacion'], css,
nivel_css: (RANGOS_CSS.find(r => css >= r.min && css <= r.max)?.codigo ?? 'minimo') as TeaAdos2['nivel_css'],
};
}
function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion {
const codigo = code(o.code) ?? '';
const metrica = metricas.find(m => m.code === codigo);
const evaluable = !o.dataAbsentReason && typeof o.valueQuantity?.value === 'number';
const estado = evaluable ? INTERPRETACION[code(o.interpretation?.[0]) ?? ''] ?? 'normal' : 'no_evaluable';
const range = o.referenceRange?.[0];
return {
codigo, etiqueta: display(o.code) ?? metrica?.display ?? codigo,
unidad: o.valueQuantity?.unit ?? metrica?.property?.find(p => p.code === 'unidad')?.valueString ?? '',
referencia: { min: range?.low?.value ?? 0, max: range?.high?.value ?? 0 },
valor: evaluable ? o.valueQuantity!.value! : null,
valor_z: evaluable ? component(o, 'z')?.valueQuantity?.value ?? null : null,
estado,
efectos: (metrica?.property ?? []).filter(p => p.code === `efecto-${estado}`).map(p => p.valueString!).filter(Boolean),
};
}
// The study EEG of `report`, with the observations it lists and the electrode maps of its metrics.
export function eegDeReporte(report: Report | undefined, observations: Observation[], metricas: Metric[]): TeaEeg | null {
if (!report?.effectiveDateTime) return null;
const ids = new Set((report.result ?? []).map(r => referenceId(r)));
const listed = observations.filter(o => ids.has(o.id));
const calidad = (concept: Concept | undefined) => (code(concept) ?? 'MALO').toLowerCase() as TeaNivelCalidad;
const alteraciones = listed.filter(o => codeIn(o.code, METRICAS)).map(o => alteracion(o, metricas));
// A metric's electrode values are `electrodos-<the metric observation's id>`.
const mapas = observations.filter(o => o.id?.startsWith('electrodos-') && ids.has(o.id.slice('electrodos-'.length)))
.map(o => {
const valores = Object.fromEntries((o.component ?? []).map(c => [code(c.code), c.valueQuantity?.value])
.filter((e): e is [string, number] => !!e[0] && typeof e[1] === 'number'));
return mapaDeElectrodos(code(o.code)!, display(o.code) ?? code(o.code)!, valores);
})
.filter(m => alteraciones.some(a => a.codigo === m.codigo && a.estado !== 'no_evaluable'));
return {
fecha: report.effectiveDateTime.slice(0, 10),
duracion_min: Math.round(extension(report, 'duracion-min')?.valueDecimal ?? 0),
canales: extension(report, 'canales')?.valueInteger ?? 0,
calidad: calidad(report.conclusionCode?.[0]),
criterios_calidad: listed.filter(o => code(o.code)?.startsWith('eeg.calidad_')).map(o => ({
codigo: code(o.code)!.replace('eeg.calidad_', ''), etiqueta: display(o.code) ?? '',
valor: o.valueInteger ?? o.valueQuantity?.value ?? 0, unidad: typeof o.valueInteger === 'number' ? 'canales' : o.valueQuantity?.unit ?? '',
nivel: calidad(o.interpretation?.[0]),
})),
alteraciones, mapas,
ejes_mapa: { x: EJE, y: EJE, electrodos: Object.entries(ELECTRODOS).map(([nombre, [x, y]]) => ({ nombre, x, y })) },
};
}
function resultadoEeg(report: Report | undefined, observations: Observation[], validadas: boolean): 'normal' | 'anormal' | null {
if (!validadas || !report || code(report.conclusionCode?.[0]) !== 'BUENO') return null;
return alteracionesDe(report, observations).length ? 'anormal' : 'normal';
}
function alteracionesDe(report: Report | undefined, observations: Observation[]): string[] {
const ids = new Set((report?.result ?? []).map(r => referenceId(r)));
return observations.filter(o => ids.has(o.id) && codeIn(o.code, METRICAS) && ['H', 'L'].includes(code(o.interpretation?.[0]) ?? ''))
.map(o => code(o.code)!);
}
// One row of the list: the episode and what the search included for its patient.
export function pacienteDeEpisodio(episode: Resource, included: Resource[], validadas: boolean): TeaSeguimientoPaciente {
const id = episode.id!;
const own = included.filter(r => referenceId((r['subject'] ?? r['patient']) as { reference?: string }) === id);
const observations = own.filter(r => r.resourceType === 'Observation') as Observation[];
const report = own.find(r => r.resourceType === 'DiagnosticReport') as Report | undefined;
const ados2 = byCode(observations, 'ados2');
const plan = own.find(r => r.resourceType === 'CarePlan') as { activity?: { detail?: { code?: Concept; status?: string } }[] } | undefined;
const modulo = code(component(ados2, 'ados2.modulo')?.valueCodeableConcept)?.replace(/^ados2\.modulo\.(MODULO_)?/, '');
return {
id_seudonimo: id,
grupo_edad: grupoEdad(extension(episode, 'grupo-edad')?.valueCoding?.code),
ultimo_eeg: report?.effectiveDateTime?.slice(0, 10) ?? null,
mchat: byCode(observations, 'mchat.puntaje')?.valueInteger ?? null,
css_ados2: component(ados2, 'ados2.css')?.valueInteger ?? null,
alteraciones_eeg: resultadoEeg(report, observations, validadas),
modulo_ados2: modulo ?? null,
estado_caso: episode['status'] === 'finished' ? 'completo' : 'en_proceso',
pendientes: (plan?.activity ?? []).filter(a => a.detail?.status !== 'completed').map(a => a.detail?.code?.text ?? display(a.detail?.code) ?? ''),
alteraciones: validadas ? alteracionesDe(report, observations) : [],
};
}
function parameter(p: Resource | undefined, name: string): number {
const found = (p?.['parameter'] as { name: string; valueInteger?: number }[] | undefined)?.find(x => x.name === name);
return found?.valueInteger ?? 0;
}
function porAlteracion(p: Resource | undefined, metricas: Metric[]) {
return ((p?.['parameter'] ?? []) as { name: string; part?: { name: string; valueCode?: string; valueInteger?: number }[] }[])
.filter(x => x.name === 'por_alteracion').map(x => {
const codigo = x.part?.find(y => y.name === 'alteracion')?.valueCode ?? '';
return { codigo, etiqueta: metricas.find(m => m.code === codigo)?.display ?? codigo, n: x.part?.find(y => y.name === 'pacientes')?.valueInteger ?? 0 };
});
}
function isoDay(date: Date) {
return date.toISOString().slice(0, 10);
}
// From `meses` before the cut-off (plus a day) to the cut-off, as CaCu's list.
export function ventana(corte: string, meses: number): { desde: string; hasta: string } {
const [y, m, d] = corte.split('-').map(Number);
const total = y * 12 + m - 1 - meses;
const year = Math.floor(total / 12), month = total % 12;
const last = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
const desde = new Date(Date.UTC(year, month, Math.min(d, last) + 1));
return { desde: isoDay(desde), hasta: corte };
}
@Injectable()
export class FhirTeaSeguimientoService extends TeaSeguimientoService {
private readonly client = inject(HttpClient);
private metricas$?: Observable<Metric[]>;
today = () => new Date();
private metricas(): Observable<Metric[]> {
this.metricas$ ??= this.client.get<{ concept?: Metric[] }>(`/tea/fhir/CodeSystem/${METRICAS}`).pipe(
map(system => system.concept ?? []), shareReplay({ bufferSize: 1, refCount: false }));
return this.metricas$;
}
override consultar(query: SeguimientoQuery) {
if (!validSeguimientoQuery(query)) throw new Error('Parámetros de seguimiento inválidos');
const corte = query.corte ?? isoDay(this.today());
const { desde, hasta } = ventana(corte, query.meses);
let params = new HttpParams().append('date', 'ge' + desde).append('date', 'le' + hasta);
if (query.estatus) params = params.set('resultado-eeg', query.estatus);
if (query.grupo_edad) params = params.set('grupo-edad', grupoCodigo(query.grupo_edad));
const mchat = RANGOS_MCHAT.find(r => r.codigo === query.mchat), css = RANGOS_CSS.find(r => r.codigo === query.css);
if (mchat) params = params.append('mchat', 'ge' + mchat.min).append('mchat', 'le' + mchat.max);
if (css) params = params.append('css', 'ge' + css.min).append('css', 'le' + css.max);
if (query.estado_caso) params = params.set('status', query.estado_caso === 'completo' ? 'finished' : 'active');
if (query.alteracion) params = params.set('alteracion', query.alteracion);
const page = params.set('_count', Math.min(query.page_size, MAX_COUNT)).set('_offset', (query.page - 1) * query.page_size).set('_include', '*');
// The list has no children out of the protocol any more: the screening ends with a good EEG.
const empty = query.estado_caso === 'fuera_protocolo';
return forkJoin({
bundle: empty ? of<Bundle>({ resourceType: 'Bundle', total: 0, entry: [] }) : this.client.get<Bundle>('/tea/fhir/EpisodeOfCare', { params: page }),
resumen: this.client.get<Resource>('/tea/fhir/EpisodeOfCare/$resumen-eeg', { params }),
metricas: this.metricas(),
}).pipe(map(({ bundle, resumen, metricas }) => {
const validadas = (resumen['parameter'] as { name: string }[] | undefined)?.some(p => p.name === 'normales') ?? false;
const episodes = (bundle.entry ?? []).filter(e => e.search?.mode !== 'include' && e.resource.resourceType === 'EpisodeOfCare').map(e => e.resource);
const included = (bundle.entry ?? []).filter(e => e.search?.mode === 'include').map(e => e.resource);
const total = empty ? 0 : bundle.total ?? episodes.length;
return teaSeguimientoResponse({
simulado: episodes.every(isSimulated),
corte, ventana: { meses: query.meses, desde, hasta },
filtros: { alteraciones_eeg: query.estatus ?? null },
paginacion: { page: query.page, page_size: query.page_size, total_items: total, total_pages: Math.ceil(total / query.page_size) },
items: episodes.map(e => pacienteDeEpisodio(e, included, validadas)),
tipos_alteracion: validadas ? metricas.map(m => ({ codigo: m.code ?? '', etiqueta: m.display ?? m.code ?? '' })) : [],
resumen_eeg: {
normales: parameter(resumen, 'normales'), anormales: parameter(resumen, 'anormales'), sin_eeg: parameter(resumen, 'sin_eeg_valido'),
por_alteracion: porAlteracion(resumen, metricas),
},
});
}));
}
override detalle(id: string) {
return forkJoin({
bundle: this.client.get<Bundle>(`/tea/fhir/Patient/${encodeURIComponent(id)}/$resumen-tea`),
metricas: this.metricas(),
}).pipe(map(({ bundle, metricas }) => {
const all = resources(bundle);
const observations = all.filter(r => r.resourceType === 'Observation') as Observation[];
const metric = observations.find(o => codeIn(o.code, METRICAS) && o.referenceRange?.[0]?.text);
const edad = metric?.referenceRange?.[0]?.text?.split(': ').pop();
return teaPacienteDetalle({
simulado: all.length > 0 && all.every(isSimulated),
id_seudonimo: id,
grupo_edad: grupoEdad(edad),
ados2: ados2DeObservacion(byCode(observations, 'ados2')),
eeg: eegDeReporte(resources(bundle, 'DiagnosticReport')[0] as Report | undefined, observations, metricas),
}, id);
}));
}
}
@@ -1,173 +0,0 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { isoDate, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
import { validSeguimientoQuery } from './cacu-seguimiento.service';
export type AlteracionesEeg = 'normal' | 'anormal';
export type EstadoCaso = 'completo' | 'en_proceso' | 'fuera_protocolo';
export interface TeaSeguimientoPaciente {
id_seudonimo: string;
grupo_edad: string;
ultimo_eeg: string | null;
mchat: number | null;
css_ados2: number | null;
alteraciones_eeg: AlteracionesEeg | null;
modulo_ados2: string | null;
estado_caso: EstadoCaso;
// What a case in process still lacks.
pendientes: string[];
// Codes of the alterations found.
alteraciones: string[];
}
export interface TeaResumenEeg {
normales: number; anormales: number; sin_eeg: number;
por_alteracion: { codigo: string; etiqueta: string; n: number }[];
}
export interface TeaSeguimientoResponse extends Pick<SeguimientoResponse, 'simulado' | 'corte' | 'ventana' | 'paginacion'> {
filtros: { alteraciones_eeg: AlteracionesEeg | null };
items: TeaSeguimientoPaciente[];
tipos_alteracion: { codigo: string; etiqueta: string }[];
// Of every patient that matches the filters, not only this page's.
resumen_eeg: TeaResumenEeg;
}
export interface TeaAdosReactivo { codigo: string; etiqueta: string; puntaje: number; puntaje_algoritmo: number }
export interface TeaAdosDominio { codigo: string; etiqueta: string; puntaje: number; maximo: number; reactivos: TeaAdosReactivo[] }
export interface TeaAdos2 {
fecha: string; modulo: string; algoritmo: string; dominios: TeaAdosDominio[]; total: number; total_maximo: number;
clasificacion: 'autismo' | 'espectro_autista' | 'no_espectro'; css: number; nivel_css: 'minimo' | 'bajo' | 'moderado' | 'alto';
}
export interface TeaEegRegion { codigo: string; etiqueta: string; valor_z: number }
// Mock: EEG metrics with placeholder reference ranges and associated effects, pending medical review.
export type TeaNivelCalidad = 'bueno' | 'aceptable' | 'malo';
export type TeaAlteracionEstado = 'normal' | 'aumentado' | 'disminuido' | 'no_evaluable';
export interface TeaEegAlteracion {
codigo: string; etiqueta: string; unidad: string; referencia: { min: number; max: number };
valor: number | null; valor_z: number | null; estado: TeaAlteracionEstado; efectos: string[];
}
export interface TeaEegMapa { codigo: string; metrica: string; z: (number | null)[][]; regiones: TeaEegRegion[] }
export interface TeaEeg {
fecha: string; duracion_min: number; canales: number;
// The overall rating is in words, like Automagic, and is the worst of its criteria, which report numbers.
calidad: TeaNivelCalidad; criterios_calidad: { codigo: string; etiqueta: string; valor: number; unidad: string; nivel: TeaNivelCalidad }[];
alteraciones: TeaEegAlteracion[];
// One map per alteration that could be evaluated, on shared axes.
mapas: TeaEegMapa[];
ejes_mapa: { x: number[]; y: number[]; electrodos: { nombre: string; x: number; y: number }[] };
}
export interface TeaPacienteDetalle { simulado: true; id_seudonimo: string; grupo_edad: string; ados2: TeaAdos2 | null; eeg: TeaEeg | null }
// TEA has no follow-up status; its third filter is the EEG result, using the CaCu status shape.
export const ESTADOS_CASO: Record<EstadoCaso, string> = { completo: 'Completo', en_proceso: 'En proceso', fuera_protocolo: 'Fuera del protocolo' };
export const GRUPOS_EDAD_TEA = ['16-23 meses', '24-29 meses', '30-36 meses'];
// M-CHAT-R/F risk bands, and the ADOS-2 calibrated severity levels used in the patient summary.
export const RANGOS_MCHAT = [
{ codigo: 'bajo', etiqueta: 'Riesgo bajo (0–2)', min: 0, max: 2 },
{ codigo: 'medio', etiqueta: 'Riesgo medio (3–7)', min: 3, max: 7 },
{ codigo: 'alto', etiqueta: 'Riesgo alto (8–20)', min: 8, max: 20 },
];
export const RANGOS_CSS = [
{ codigo: 'minimo', etiqueta: 'Evidencia mínima o nula (1–2)', min: 1, max: 2 },
{ codigo: 'bajo', etiqueta: 'Nivel bajo (3–4)', min: 3, max: 4 },
{ codigo: 'moderado', etiqueta: 'Nivel moderado (5–7)', min: 5, max: 7 },
{ codigo: 'alto', etiqueta: 'Nivel alto (8–10)', min: 8, max: 10 },
];
export const ALTERACIONES_EEG: SeguimientoStatus[] = [{ codigo: 'normal', etiqueta: 'Normal' }, { codigo: 'anormal', etiqueta: 'Anormal' }];
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
const eeg = (v: unknown) => v === null || v === 'normal' || v === 'anormal';
const score = (v: unknown, min: number, max: number) => v === null || typeof v === 'number' && Number.isSafeInteger(v) && v >= min && v <= max;
const textos = (v: unknown) => Array.isArray(v) && v.every(t => typeof t === 'string');
function validResumenEeg(r: unknown): boolean {
return record(r) && integer(r['normales']) && integer(r['anormales']) && integer(r['sin_eeg']) && Array.isArray(r['por_alteracion'])
&& r['por_alteracion'].every(a => record(a) && typeof a['codigo'] === 'string' && typeof a['etiqueta'] === 'string' && integer(a['n']));
}
export function teaSeguimientoResponse(v: unknown): TeaSeguimientoResponse {
// Same rule as CaCu: demonstration records only.
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'];
// M-CHAT-R/F totals range 0–20; ADOS-2 calibrated severity scores range 1–10.
if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta'])
|| !record(filters) || !eeg(filters['alteraciones_eeg'])
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => record(item)
&& typeof item['id_seudonimo'] === 'string' && typeof item['grupo_edad'] === 'string'
&& (item['ultimo_eeg'] === null || isoDate(item['ultimo_eeg']))
&& score(item['mchat'], 0, 20) && score(item['css_ados2'], 1, 10)
&& eeg(item['alteraciones_eeg']) && (item['modulo_ados2'] === null || typeof item['modulo_ados2'] === 'string')
&& Object.hasOwn(ESTADOS_CASO, item['estado_caso'] as string) && textos(item['pendientes']) && textos(item['alteraciones']))
|| !Array.isArray(v['tipos_alteracion']) || !v['tipos_alteracion'].every(t => record(t) && typeof t['codigo'] === 'string' && typeof t['etiqueta'] === 'string')
|| !validResumenEeg(v['resumen_eeg']))
throw new Error('Respuesta de seguimiento inválida');
return v as unknown as TeaSeguimientoResponse;
}
const finite = (v: unknown) => typeof v === 'number' && Number.isFinite(v);
const text = (v: unknown) => typeof v === 'string' && v.length > 0;
function validAdos(a: unknown): boolean {
if (a === null) return true;
if (!record(a) || !isoDate(a['fecha']) || !text(a['modulo']) || !text(a['algoritmo']) || !score(a['css'], 1, 10)
|| !['autismo', 'espectro_autista', 'no_espectro'].includes(a['clasificacion'] as string)
|| !['minimo', 'bajo', 'moderado', 'alto'].includes(a['nivel_css'] as string) || !Array.isArray(a['dominios'])) return false;
// Items score 0–3 (algorithm 0–2); each domain and the total must be the sum of their parts.
const dominios = a['dominios'] as unknown[];
const ok = dominios.every(d => record(d) && text(d['codigo']) && text(d['etiqueta']) && Array.isArray(d['reactivos'])
&& d['reactivos'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && score(r['puntaje'], 0, 3) && score(r['puntaje_algoritmo'], 0, 2))
&& d['puntaje'] === (d['reactivos'] as TeaAdosReactivo[]).reduce((t, r) => t + r.puntaje_algoritmo, 0)
&& d['maximo'] === 2 * (d['reactivos'] as unknown[]).length);
return ok && a['total'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.puntaje, 0)
&& a['total_maximo'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.maximo, 0);
}
// A metric without a value cannot be evaluated; one with a value is out of range exactly when it is altered.
function validAlteracion(a: unknown): boolean {
if (!record(a) || !text(a['codigo']) || !text(a['etiqueta']) || typeof a['unidad'] !== 'string' || !record(a['referencia'])
|| !finite(a['referencia']['min']) || !finite(a['referencia']['max']) || (a['referencia']['min'] as number) > (a['referencia']['max'] as number)
|| !Array.isArray(a['efectos']) || !a['efectos'].every(text)) return false;
const estado = a['estado'];
if (estado === 'no_evaluable') return a['valor'] === null && a['valor_z'] === null;
return finite(a['valor']) && finite(a['valor_z']) && ['normal', 'aumentado', 'disminuido'].includes(estado as string);
}
function validEeg(e: unknown): boolean {
if (e === null) return true;
const nivel = (v: unknown) => ['bueno', 'aceptable', 'malo'].includes(v as string);
if (!record(e) || !isoDate(e['fecha']) || !integer(e['duracion_min'], 1) || !integer(e['canales'], 1) || !nivel(e['calidad'])
|| !Array.isArray(e['criterios_calidad']) || !e['criterios_calidad'].every(c => record(c) && text(c['codigo']) && text(c['etiqueta']) && nivel(c['nivel']) && text(c['unidad'])
&& (c['unidad'] === 'canales' ? integer(c['valor']) && (c['valor'] as number) <= (e['canales'] as number) : finite(c['valor']) && (c['valor'] as number) >= 0))) return false;
if (!Array.isArray(e['alteraciones']) || !e['alteraciones'].every(validAlteracion)) return false;
const ejes = e['ejes_mapa'];
if (!record(ejes) || !Array.isArray(ejes['x']) || !Array.isArray(ejes['y']) || !Array.isArray(e['mapas'])) return false;
const x = ejes['x'], y = ejes['y'];
return x.every(finite) && y.every(finite)
&& Array.isArray(ejes['electrodos']) && ejes['electrodos'].every(p => record(p) && text(p['nombre']) && finite(p['x']) && finite(p['y']))
&& e['mapas'].every(m => record(m) && text(m['codigo']) && text(m['metrica']) && Array.isArray(m['z']) && m['z'].length === y.length
&& m['z'].every(row => Array.isArray(row) && row.length === x.length && row.every(v => v === null || finite(v)))
&& Array.isArray(m['regiones']) && m['regiones'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && finite(r['valor_z'])));
}
export function teaPacienteDetalle(v: unknown, id: string): TeaPacienteDetalle {
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
if (v['id_seudonimo'] !== id || typeof v['grupo_edad'] !== 'string' || !validAdos(v['ados2']) || !validEeg(v['eeg']))
throw new Error('Resumen del paciente inválido');
return v as unknown as TeaPacienteDetalle;
}
@Injectable({ providedIn: 'root' })
export class TeaSeguimientoService {
private readonly http = inject(HttpClient);
// `estatus` carries the EEG filter so the shared form and query work for both domains.
consultar(query: SeguimientoQuery) {
if (!validSeguimientoQuery(query)) throw new Error('Parámetros de seguimiento inválidos');
let params = new HttpParams().set('meses', query.meses).set('page', query.page).set('page_size', query.page_size);
if (query.corte) params = params.set('corte', query.corte);
if (query.estatus) params = params.set('alteraciones_eeg', query.estatus);
if (query.grupo_edad) params = params.set('grupo_edad', query.grupo_edad);
const mchat = RANGOS_MCHAT.find(r => r.codigo === query.mchat), css = RANGOS_CSS.find(r => r.codigo === query.css);
if (mchat) params = params.set('mchat_min', mchat.min).set('mchat_max', mchat.max);
if (css) params = params.set('css_min', css.min).set('css_max', css.max);
if (query.estado_caso) params = params.set('estado_caso', query.estado_caso);
if (query.alteracion) params = params.set('alteracion', query.alteracion);
return this.http.get<unknown>('/tea/seguimiento', { params }).pipe(map(teaSeguimientoResponse));
}
detalle(id: string) {
return this.http.get<unknown>(`/tea/seguimiento/${encodeURIComponent(id)}`).pipe(map(v => teaPacienteDetalle(v, id)));
}
}
@@ -1,313 +0,0 @@
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { teaPacienteDetalle, teaSeguimientoResponse, TeaEeg, TeaEegMapa } from './tea-seguimiento.service';
import { mapaFigure } from './tea-paciente-resumen';
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
import { IndicadoresTracking } from './indicadores-tracking';
const item = { id_seudonimo: 'T-0001', grupo_edad: '16-23 meses', ultimo_eeg: '2026-09-12', mchat: 14, css_ados2: 8, alteraciones_eeg: 'anormal',
modulo_ados2: '2', estado_caso: 'en_proceso', pendientes: ['Neuropediatría'], alteraciones: ['ritmo_posterior'] };
const data = {
simulado: true, corte: '2026-09-30', ventana: { meses: 3, desde: '2026-07-01', hasta: '2026-09-30' }, filtros: { alteraciones_eeg: null },
paginacion: { page: 1, page_size: 50, total_items: 2, total_pages: 1 },
items: [item, { ...item, id_seudonimo: 'T-0002', ultimo_eeg: null, mchat: null, css_ados2: null, alteraciones_eeg: null, modulo_ados2: null, estado_caso: 'fuera_protocolo', pendientes: [], alteraciones: [] }],
tipos_alteracion: [{ codigo: 'ritmo_posterior', etiqueta: 'Ritmo posterior' }, { codigo: 'picos_paroxisticos', etiqueta: 'Picos paroxísticos' }],
resumen_eeg: { normales: 3, anormales: 1, sin_eeg: 1, por_alteracion: [{ codigo: 'ritmo_posterior', etiqueta: 'Ritmo posterior', n: 1 }, { codigo: 'picos_paroxisticos', etiqueta: 'Picos paroxísticos', n: 0 }] },
};
const reactivo = (codigo: string, puntaje: number) => ({ codigo, etiqueta: 'Reactivo ' + codigo, puntaje, puntaje_algoritmo: Math.min(puntaje, 2) });
const metrica = (codigo: string, etiqueta: string, extra: object) => ({ codigo, etiqueta, unidad: '', referencia: { min: 1, max: 2 }, efectos: [], ...extra });
const alteraciones = [
metrica('ritmo_posterior', 'Ritmo posterior', { valor: 0.9, valor_z: -2.4, estado: 'disminuido', efectos: ['Ritmo más lento de lo esperado para la edad.'] }),
metrica('husos_sueno_n2', 'Husos de sueño N2', { valor: null, valor_z: null, estado: 'no_evaluable' }),
metrica('husos_sueno_n3', 'Husos de sueño N3', { valor: 1.4, valor_z: 0.2, estado: 'normal' }),
metrica('picos_paroxisticos', 'Picos paroxísticos', { valor: 1.5, valor_z: 0.3, estado: 'normal' }),
metrica('gradiente_anteroposterior', 'Gradiente anteroposterior', { valor: 1.2, valor_z: -0.4, estado: 'normal' }),
];
const mapa = (codigo: string, metrica: string, region: string) => ({ codigo, metrica, z: [[null, 1, null], [0, 2.1, 0], [null, 1, null]], regiones: [{ codigo: 'r', etiqueta: region, valor_z: 2.1 }] });
const detalle = {
simulado: true, id_seudonimo: 'T-0001', grupo_edad: '16-23 meses',
ados2: { fecha: '2026-08-23', modulo: '1', algoritmo: 'Pocas o ninguna palabra', total: 5, total_maximo: 8, clasificacion: 'no_espectro', css: 3, nivel_css: 'bajo',
dominios: [{ codigo: 'AS', etiqueta: 'Afecto social', puntaje: 4, maximo: 4, reactivos: [reactivo('A2', 3), reactivo('B1', 2)] },
{ codigo: 'CRR', etiqueta: 'Comportamiento restringido y repetitivo', puntaje: 1, maximo: 4, reactivos: [reactivo('D1', 1), reactivo('D2', 0)] }] },
eeg: { fecha: '2026-09-12', duracion_min: 20, canales: 19, calidad: 'aceptable',
criterios_calidad: [{ codigo: 'amplitud', etiqueta: 'Canales con amplitud extrema', valor: 1, unidad: 'canales', nivel: 'bueno' }, { codigo: 'linea', etiqueta: 'Ruido de la línea eléctrica', valor: 8, unidad: 'dB', nivel: 'aceptable' }],
alteraciones,
mapas: [mapa('ritmo_posterior', 'Ritmo posterior (puntuación z)', 'Central'), mapa('picos_paroxisticos', 'Picos paroxísticos (puntuación z)', 'Occipital')],
ejes_mapa: { x: [-1, 0, 1], y: [-1, 0, 1], electrodos: [{ nombre: 'Cz', x: 0, y: 0 }] } },
};
const anormal = { ...data, filtros: { alteraciones_eeg: 'anormal' }, paginacion: { ...data.paginacion, total_items: 1 }, items: [item] };
describe('Seguimiento TEA', () => {
let http: HttpTestingController;
beforeEach(() => {
const runtime = { react: vi.fn().mockResolvedValue(undefined), purge: vi.fn(), Plots: { resize: vi.fn().mockResolvedValue(undefined) } };
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
http = TestBed.inject(HttpTestingController);
});
function open() {
const fixture = TestBed.createComponent(IndicadoresTracking);
fixture.componentRef.setInput('domainLabel', 'TEA'); fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('active', true);
fixture.detectChanges();
return fixture;
}
const request = () => http.expectOne(r => r.url === '/tea/seguimiento');
it('muestra las siete columnas y los valores ausentes como No disponible', () => {
const fixture = open();
request().flush(data); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
expect(Array.from(root.querySelectorAll('thead th')).map(th => th.textContent)).toEqual(
['Identificador seudónimo', 'Grupo de edad', 'Estado del caso', 'Último EEG', 'Puntaje M-CHAT', 'CSS ADOS-2', 'Alteraciones EEG']);
const rows = root.querySelectorAll('tbody tr');
expect(rows).toHaveLength(2);
expect(rows[0].textContent).toContain('Anormal');
expect(rows[1].querySelectorAll('td')[3].textContent).toContain('No disponible');
expect(root.textContent).toContain('Página 1 de 1, 2 registros');
http.verify();
});
it('usa los filtros de CaCu con Alteraciones EEG en lugar del estatus', () => {
const fixture = open();
const first = request();
expect(first.request.params.get('meses')).toBe('3');
expect(first.request.params.has('alteraciones_eeg')).toBe(false);
first.flush(data); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
expect(root.querySelector('input[type=date]')).not.toBeNull();
const select = root.querySelector<HTMLSelectElement>('select[name=estatus]')!;
expect(select.closest('label')?.textContent).toContain('Alteraciones EEG');
expect(Array.from(select.options).map(o => o.textContent?.trim())).toEqual(['Todas', 'Normal', 'Anormal']);
fixture.componentInstance.draft = { ...fixture.componentInstance.draft, estatus: 'anormal', corte: '2026-08-31', meses: 6, page_size: 20 };
fixture.componentInstance.apply();
const filtered = request();
expect(filtered.request.params.get('alteraciones_eeg')).toBe('anormal');
expect(filtered.request.params.get('corte')).toBe('2026-08-31');
expect(filtered.request.params.get('meses')).toBe('6');
expect(filtered.request.params.get('page_size')).toBe('20');
expect(filtered.request.params.get('page')).toBe('1');
filtered.flush(anormal); fixture.detectChanges();
expect(root.querySelectorAll('tbody tr')).toHaveLength(1);
expect(fixture.componentInstance.draft.estatus).toBe('anormal');
http.verify();
});
it('filtra por grupo de edad, M-CHAT y CSS ADOS-2, sin prioridad, y conserva los filtros al responder y paginar', () => {
const fixture = open();
request().flush(data); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
expect(root.querySelector('select[name=prioridad]')).toBeNull();
const opciones = (name: string) => Array.from(root.querySelector<HTMLSelectElement>(`select[name=${name}]`)!.options).map(o => o.textContent?.trim());
expect(opciones('grupo_edad')).toEqual(['Todos', '16-23 meses', '24-29 meses', '30-36 meses']);
expect(opciones('mchat')).toEqual(['Todos', 'Riesgo bajo (0–2)', 'Riesgo medio (3–7)', 'Riesgo alto (8–20)']);
expect(opciones('css')).toEqual(['Todos', 'Evidencia mínima o nula (1–2)', 'Nivel bajo (3–4)', 'Nivel moderado (5–7)', 'Nivel alto (8–10)']);
const c = fixture.componentInstance;
c.draft = { ...c.draft, grupo_edad: '24-29 meses', mchat: 'alto', css: 'moderado' };
c.apply();
const filtrada = request();
const parametros = (r: typeof filtrada) => Object.fromEntries(['grupo_edad', 'mchat_min', 'mchat_max', 'css_min', 'css_max'].map(k => [k, r.request.params.get(k)]));
const esperados = { grupo_edad: '24-29 meses', mchat_min: '8', mchat_max: '20', css_min: '5', css_max: '7' };
expect(parametros(filtrada)).toEqual(esperados);
filtrada.flush({ ...data, paginacion: { ...data.paginacion, total_items: 0, total_pages: 2 }, items: [] }); fixture.detectChanges();
expect(c.draft).toMatchObject({ grupo_edad: '24-29 meses', mchat: 'alto', css: 'moderado' });
expect(root.textContent).toContain('No hay registros para los filtros aplicados.');
c.navigate(2);
expect(parametros(request())).toEqual(esperados);
http.verify();
});
it('muestra el estado del caso, lo que falta y el módulo junto al puntaje', () => {
const fixture = open();
request().flush(data); fixture.detectChanges();
const celdas = fixture.nativeElement.querySelector('tbody tr').querySelectorAll('td');
expect(celdas[2].textContent).toContain('En proceso');
expect(celdas[2].textContent).toContain('Falta: Neuropediatría');
expect(celdas[5].textContent).toContain('8');
expect(celdas[5].textContent).toContain('Módulo 2');
http.verify();
});
it('resume los EEG arriba de la tabla y filtra por estado y tipo de alteración', () => {
const fixture = open();
request().flush(data); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
expect(Array.from(root.querySelectorAll('.resumen-eeg dd')).map(d => d.textContent)).toEqual(['3', '1', '1', '1', '0']);
expect(root.querySelector('.resumen-eeg')!.textContent).toContain('Picos paroxísticos');
expect(Array.from(root.querySelector<HTMLSelectElement>('select[name=alteracion]')!.options).map(o => o.textContent?.trim())).toEqual(['Todas', 'Ritmo posterior', 'Picos paroxísticos']);
const c = fixture.componentInstance;
c.draft = { ...c.draft, estado_caso: 'completo', alteracion: 'picos_paroxisticos' };
c.apply();
const filtrada = request();
expect(filtrada.request.params.get('estado_caso')).toBe('completo');
expect(filtrada.request.params.get('alteracion')).toBe('picos_paroxisticos');
filtrada.flush(data); fixture.detectChanges();
expect(c.draft).toMatchObject({ estado_caso: 'completo', alteracion: 'picos_paroxisticos' });
http.verify();
});
it('abre con las zonas de la primera alteración, cambia al elegir otra y se cierra al repetirla', () => {
const fixture = open();
request().flush(data); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
root.querySelector<HTMLButtonElement>('button.row-toggle')!.click(); fixture.detectChanges();
http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges();
const tarjetas = root.querySelectorAll<HTMLButtonElement>('button.nombre');
expect(root.querySelector('.alteraciones-zona')!.classList.contains('abierta')).toBe(true);
expect(tarjetas[0].getAttribute('aria-expanded')).toBe('true');
const panel = () => root.querySelector('section.mapa')!;
expect(panel().classList.contains('panel')).toBe(false);
expect(panel().textContent).toContain('Azul: menos actividad');
expect(panel().textContent).toContain('Rojo: más actividad');
expect(panel().querySelector('.meta')!.textContent).toContain('Ritmo posterior');
expect(panel().querySelector('.regiones')!.textContent).toContain('Central');
tarjetas[3].click(); fixture.detectChanges();
expect(panel().querySelector('.meta')!.textContent).toContain('Picos paroxísticos');
expect(panel().querySelector('.regiones')!.textContent).toContain('Occipital');
expect(tarjetas[0].getAttribute('aria-expanded')).toBe('false');
expect(tarjetas[1].disabled).toBe(true);
expect(tarjetas[1].hasAttribute('aria-expanded')).toBe(false);
tarjetas[3].click(); fixture.detectChanges();
expect(root.querySelector('section.mapa')).toBeNull();
expect(root.querySelector('.alteraciones-zona')!.classList.contains('abierta')).toBe(false);
tarjetas[0].click(); fixture.detectChanges();
expect(root.querySelector('section.mapa')).not.toBeNull();
http.verify();
});
it('el mapa oculta lo que queda fuera de la cabeza con el color que tiene detrás', () => {
const figura = (fondo?: string) => mapaFigure(detalle.eeg as unknown as TeaEeg, detalle.eeg.mapas[0] as unknown as TeaEegMapa, fondo);
const marco = (fondo?: string) => (figura(fondo).layout['shapes'] as { fillcolor: string }[])[0].fillcolor;
expect(marco('rgb(1, 2, 3)')).toBe('rgb(1, 2, 3)');
expect(marco()).toBe('#FFFFFF');
});
it('sin alteraciones abre con la primera métrica evaluable', () => {
const fixture = open();
request().flush(data); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
root.querySelector<HTMLButtonElement>('button.row-toggle')!.click(); fixture.detectChanges();
const normales = detalle.eeg.alteraciones.map(m => m.codigo === 'ritmo_posterior' ? { ...m, estado: 'normal', efectos: [] } : m);
http.expectOne('/tea/seguimiento/T-0001').flush({ ...detalle, eeg: { ...detalle.eeg, alteraciones: normales } }); fixture.detectChanges();
expect(root.querySelector('section.mapa .meta')!.textContent).toContain('Ritmo posterior');
http.verify();
});
it('sin filtros no envía sus parámetros', () => {
open();
expect(request().request.params.keys().sort()).toEqual(['meses', 'page', 'page_size']);
http.verify();
});
it('rechaza datos reales, puntajes fuera de rango y más filas que el tamaño de página', () => {
expect(() => teaSeguimientoResponse(data)).not.toThrow();
expect(() => teaSeguimientoResponse({ ...data, simulado: false })).toThrow();
expect(() => teaSeguimientoResponse({ ...data, items: [{ ...item, mchat: 21 }] })).toThrow();
expect(() => teaSeguimientoResponse({ ...data, items: [{ ...item, css_ados2: 0 }] })).toThrow();
expect(() => teaSeguimientoResponse({ ...data, items: [{ ...item, alteraciones_eeg: 'dudoso' }] })).toThrow();
expect(() => teaSeguimientoResponse({ ...data, filtros: { alteraciones_eeg: 'dudoso' } })).toThrow();
expect(() => teaSeguimientoResponse({ ...data, paginacion: { ...data.paginacion, page_size: 1 } })).toThrow();
const fixture = open();
request().flush({ ...data, simulado: false }); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('tbody')).toBeNull();
expect(fixture.nativeElement.textContent).toContain('No se pudo consultar');
});
// Mock: odd-numbered patients open their own window; even-numbered ones expand in place.
const tres = { ...data, paginacion: { ...data.paginacion, total_items: 3 },
items: [item, { ...item, id_seudonimo: 'T-0002' }, { ...item, id_seudonimo: 'T-0004' }] };
it('el resumen se despliega en la fila, uno a la vez, y se pide al abrirlo', () => {
const fixture = open();
request().flush(tres); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
const toggles = root.querySelectorAll<HTMLButtonElement>('button.row-toggle');
expect(toggles).toHaveLength(3);
expect(toggles[0].getAttribute('aria-expanded')).toBe('false');
expect(toggles[1].getAttribute('aria-expanded')).toBe('false');
toggles[1].click(); fixture.detectChanges();
expect(toggles[1].getAttribute('aria-expanded')).toBe('true');
http.expectOne('/tea/seguimiento/T-0002').flush({ ...detalle, id_seudonimo: 'T-0002' }); fixture.detectChanges();
const panel = root.querySelector('#tea-detalle-T-0002')!;
expect(panel.textContent).toContain('CSS 3');
expect(panel.textContent).toContain('Afecto social (AS)');
expect(panel.textContent).toContain('Aceptable');
// Opens with the map of the first altered metric.
expect(panel.querySelector('app-plotly-chart')).not.toBeNull();
// Item scores start collapsed.
expect(panel.querySelector<HTMLDetailsElement>('details')!.open).toBe(false);
const metricas = panel.querySelector('[aria-label="Alteraciones del EEG"]')!;
expect(metricas.textContent).toContain('Datos de ejemplo');
expect(metricas.textContent).toContain('Disminuido');
expect(metricas.textContent).toContain('Posibles efectos asociados');
expect(metricas.textContent).toContain('Ritmo más lento de lo esperado para la edad.');
expect(metricas.textContent).toContain('Sin registro de sueño en el estudio.');
expect(Array.from(metricas.querySelectorAll('.nombre')).map(n => n.textContent)).toEqual(
['Ritmo posterior', 'Husos de sueño N2', 'Husos de sueño N3', 'Picos paroxísticos', 'Gradiente anteroposterior']);
expect(metricas.textContent).not.toContain('Sin alteraciones en las métricas evaluadas.');
(root.querySelectorAll('tbody tr.tea-row')[2] as HTMLElement).click(); fixture.detectChanges();
expect(root.querySelector('#tea-detalle-T-0002')).toBeNull();
http.expectOne('/tea/seguimiento/T-0004').flush({ ...detalle, id_seudonimo: 'T-0004', ados2: null, eeg: null }); fixture.detectChanges();
expect(root.querySelector('#tea-detalle-T-0004')?.textContent).toContain('Sin evaluación ADOS-2 registrada.');
toggles[2].click(); fixture.detectChanges();
expect(root.querySelector('tr.tea-detalle')).toBeNull();
http.verify();
});
it('todas las filas son un acordeón: se despliegan en su lugar y una a la vez', () => {
const fixture = open();
const ficha = vi.fn(); fixture.componentInstance.fichaPacienteAbierta.subscribe(ficha);
request().flush(tres); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
const toggles = root.querySelectorAll<HTMLButtonElement>('button.row-toggle');
expect(toggles).toHaveLength(tres.items.length);
toggles.forEach(toggle => expect(toggle.getAttribute('aria-expanded')).toBe('false'));
toggles[0].click(); fixture.detectChanges();
expect(toggles[0].getAttribute('aria-expanded')).toBe('true');
http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges();
expect(root.querySelector('#tea-detalle-T-0001')?.textContent).toContain('CSS 3');
(root.querySelectorAll('tbody tr.tea-row')[1] as HTMLElement).click(); fixture.detectChanges();
http.expectOne('/tea/seguimiento/T-0002').flush({ ...detalle, id_seudonimo: 'T-0002' }); fixture.detectChanges();
expect(root.querySelector('#tea-detalle-T-0001')).toBeNull();
expect(root.querySelector('#tea-detalle-T-0002')).not.toBeNull();
expect(root.querySelector('section.tea-ficha')).toBeNull();
expect(ficha).not.toHaveBeenCalled();
http.verify();
});
it('muestra un error recuperable si el resumen no es válido', () => {
const fixture = open();
request().flush(tres); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
root.querySelectorAll<HTMLButtonElement>('button.row-toggle')[1].click(); fixture.detectChanges();
http.expectOne('/tea/seguimiento/T-0002').flush({ ...detalle, id_seudonimo: 'T-0099' }); fixture.detectChanges();
expect(root.querySelector('#tea-detalle-T-0002')?.textContent).toContain('No se pudo cargar el resumen del paciente.');
http.verify();
});
it('valida que los puntajes ADOS-2 sumen y que el mapa sea rectangular', () => {
expect(() => teaPacienteDetalle(detalle, 'T-0001')).not.toThrow();
expect(() => teaPacienteDetalle({ ...detalle, simulado: false }, 'T-0001')).toThrow();
expect(() => teaPacienteDetalle({ ...detalle, ados2: { ...detalle.ados2, total: 6 } }, 'T-0001')).toThrow();
expect(() => teaPacienteDetalle({ ...detalle, ados2: { ...detalle.ados2, css: 11 } }, 'T-0001')).toThrow();
const [as, crr] = detalle.ados2.dominios;
expect(() => teaPacienteDetalle({ ...detalle, ados2: { ...detalle.ados2, dominios: [{ ...as, reactivos: [reactivo('A2', 4), as.reactivos[1]] }, crr] } }, 'T-0001')).toThrow();
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, mapas: [{ ...detalle.eeg.mapas[0], z: [[0, 0]] }] } }, 'T-0001')).toThrow();
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, calidad: 'regular' } }, 'T-0001')).toThrow();
});
it('la calidad general es una palabra, sus criterios son números y se validan', () => {
const fixture = open();
request().flush(tres); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
root.querySelectorAll<HTMLButtonElement>('button.row-toggle')[0].click(); fixture.detectChanges();
http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges();
const panel = root.querySelector('section.calidad')!;
expect(panel.querySelector('.css')!.textContent!.trim()).toBe('Aceptable');
expect(Array.from(panel.querySelectorAll('dt, dd')).map(n => n.textContent)).toEqual(['Canales con amplitud extrema', '1 de 19', 'Ruido de la línea eléctrica', '8 dB']);
expect(panel.querySelectorAll('dd')[1].getAttribute('data-calidad')).toBe('aceptable');
expect(panel.textContent).not.toMatch(/Impedancia|Artefactos|de 100/);
const conCriterios = (criterios_calidad: unknown) => ({ ...detalle, eeg: { ...detalle.eeg, criterios_calidad } });
expect(() => teaPacienteDetalle(conCriterios(undefined), 'T-0001')).toThrow();
const criterio = { codigo: 'a', etiqueta: 'A', valor: 2, unidad: 'canales', nivel: 'bueno' };
expect(() => teaPacienteDetalle(conCriterios([criterio]), 'T-0001')).not.toThrow();
expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, nivel: 'regular' }]), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, valor: null }]), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, valor: 20 }]), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, calidad: 'buena' } }, 'T-0001')).toThrow();
http.verify();
});
it('valida las alteraciones del EEG', () => {
const con = (m: object) => ({ ...detalle, eeg: { ...detalle.eeg, alteraciones: [m] } });
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, alteraciones: undefined } }, 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], estado: 'alto' }), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], valor: null }), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(con({ ...alteraciones[1], valor: 3 }), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], referencia: { min: 3, max: 1 } }), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], efectos: [''] }), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(con(alteraciones[3]), 'T-0001')).not.toThrow();
});
});
@@ -1,69 +0,0 @@
<section class="dashboard">
<header><span class="domain">Trastorno del espectro autista, investigación</span><h1>Indicadores</h1><p>Explore la información del tamizaje.</p></header>
<nav class="domain-nav" aria-label="Dominios de indicadores"><a routerLink="/indicadores/cacu">Cáncer cervicouterino</a><a routerLink="/indicadores/cama">Cáncer de mama</a><a routerLink="/indicadores/tea" aria-current="page">TEA</a></nav>
<nav class="tabs" aria-label="Secciones de TEA">
<button type="button" [attr.aria-current]="section() === 'resumen' ? 'page' : null" (click)="changeSection('resumen')">Resumen</button>
<button type="button" [attr.aria-current]="section() === 'historico' ? 'page' : null" (click)="changeSection('historico')">Histórico</button>
<button type="button" [attr.aria-current]="section() === 'seguimiento' ? 'page' : null" (click)="changeSection('seguimiento')">Seguimiento</button>
</nav>
@if (section() !== 'seguimiento') {
<section aria-label="Consulta de indicadores">
<h2>{{ section() === 'resumen' ? 'Resumen' : 'Histórico' }}</h2>
<form (ngSubmit)="section() === 'resumen' ? loadSummary() : loadHistory()">
@if (section() === 'resumen') { <label>Periodo <input name="periodo" [(ngModel)]="periodo" required placeholder="2025-S1"></label> }
@else {
<label>Indicador <select name="measure" [(ngModel)]="measureId">@for (m of measures(); track m.id) { <option [value]="m.id">{{ m.title }}</option> }</select></label>
<label>Periodos separados por coma <input name="history" [(ngModel)]="historyPeriods" required></label>
}
<label>Corte de evento <input name="evento" type="date" [(ngModel)]="eventCutoff"></label>
<label>Corte de conocimiento <input name="conocimiento" type="datetime-local" [(ngModel)]="knowledgeCutoff"></label>
<button type="submit">Consultar</button>
</form>
@if (measureState() === 'cargando' || measureState() === 'inicial') { <p role="status">Consultando indicadores…</p> }
@if (measureState() === 'error') { <p role="alert">{{ measureError() }}</p> }
@if (measureState() === 'listo' && reports().length === 0) { <p>No hay indicadores para la selección.</p> }
@for (report of reports(); track $index) {
@if (measureState() === 'listo') { <article class="card"><h3>{{ title(report) }}</h3><p>{{ report.period?.start }} a {{ report.period?.end }}</p>
@if (rows(report).length === 0) { <p>Sin datos para el periodo.</p> }
@else { <dl>@for (row of rows(report); track $index) { <div><dt>{{ row.label }}</dt><dd>{{ row.value }}</dd></div> }</dl> }
</article> }
}
</section>
}
<section [hidden]="section() !== 'seguimiento' || selected() !== null" aria-label="Seguimiento">
<h2>Seguimiento</h2><p>Consulte los episodios según la fecha de corte y los filtros seleccionados.</p>
<form (ngSubmit)="applyFilters()" class="filters">
<label>Desde <input type="date" name="desde" [(ngModel)]="filters.since"></label><label>Fecha de corte <input type="date" name="corte" [(ngModel)]="filters.cutoff"></label>
<label>Estado <select name="status" [(ngModel)]="filters.status"><option value="">Todos</option><option value="active">En seguimiento</option><option value="finished">Finalizado</option></select></label>
<label>Etapa <select name="stage" [(ngModel)]="filters.stage"><option value="">Todas</option><option value="SOLO_MCHAT">Solo M-CHAT</option><option value="PSICOLOGIA">Psicología</option><option value="NEUROPEDIATRIA">Neuropediatría</option><option value="EEG">EEG</option></select></label>
<label>Etapa desde <input type="date" name="stageFrom" [(ngModel)]="filters.stageFrom"></label><label>Etapa hasta <input type="date" name="stageTo" [(ngModel)]="filters.stageTo"></label>
<label>Edad al M-CHAT <select name="age" [(ngModel)]="filters.age"><option value="">Todas</option><option value="16_23">16 a 23 meses</option><option value="24_29">24 a 29 meses</option><option value="30_36">30 a 36 meses</option></select></label>
<label>M-CHAT mínimo <input type="number" name="mchatMin" [(ngModel)]="filters.mchatMin"></label><label>M-CHAT máximo <input type="number" name="mchatMax" [(ngModel)]="filters.mchatMax"></label>
<label>CSS mínimo <input type="number" name="cssMin" [(ngModel)]="filters.cssMin"></label><label>CSS máximo <input type="number" name="cssMax" [(ngModel)]="filters.cssMax"></label>
<label>EEG <select name="eeg" [(ngModel)]="filters.eeg"><option value="">Todos</option>@if (alterationsAvailable()) { <option value="normal">Normal</option><option value="anormal">Anormal</option> } @else { <option value="valido">Con EEG válido</option> }<option value="sin-eeg-valido">Sin EEG válido</option></select></label>
@if (alterationsAvailable() && alterationTypes().length) { <label>Alteración <select name="alteration" [(ngModel)]="filters.alteration"><option value="">Todas</option>@for (item of alterationTypes(); track item.code) { <option [value]="item.code">{{ item.display }}</option> }</select></label> }
<button type="submit">Aplicar filtros</button>
</form>
@if (episodeState() === 'cargando') { <p role="status">Consultando seguimiento…</p> }
@if (episodeState() === 'error') { <p role="alert">{{ episodeError() }}</p> }
@if (episodeState() === 'listo') {
<p>{{ episodeTotal() }} episodios</p>
@if (episodes().length === 0) { <p>No hay episodios para la selección.</p> }
@else { <table><thead><tr><th>Paciente</th><th>Etapa</th><th>Fecha de etapa</th><th>Estado</th><th></th></tr></thead><tbody>
@for (e of episodes(); track e.id) { <tr><td>{{ patientId(e) }}</td><td>{{ stage(e) }}</td><td>{{ stageDate(e) }}</td><td>{{ e.status === 'finished' ? 'Finalizado' : 'En seguimiento' }}</td><td><button type="button" [attr.data-patient]="patientId(e)" (click)="openPatient(e)">Abrir ficha</button></td></tr> }
</tbody></table> }
<div class="paging"><button type="button" [disabled]="page === 0" (click)="page = page - 1; loadEpisodes()">Anterior</button><span>Página {{ page + 1 }}</span><button type="button" [disabled]="(page + 1) * pageSize >= episodeTotal()" (click)="page = page + 1; loadEpisodes()">Siguiente</button></div>
}
</section>
@if (section() === 'seguimiento' && selected()) {
<section aria-label="Ficha del paciente"><button type="button" (click)="back()">Volver a Seguimiento</button><h2>Ficha del paciente</h2><p>{{ selected() }}</p><p>La ficha muestra la información disponible a la fecha actual.</p>
@if (patientState() === 'cargando') { <p role="status">Consultando ficha…</p> }
@if (patientState() === 'error') { <p role="alert">{{ patientError() }}</p> }
@if (patientState() === 'listo') {
<article class="card"><h3>ADOS-2</h3>@if (ados(); as ados) { <p>Fecha: {{ ados.effectiveDateTime }}</p><dl>@for (c of ados.component; track $index) { <div><dt>{{ c.code.coding?.[0]?.display || c.code.coding?.[0]?.code }}</dt><dd>{{ componentValue(c) }}</dd></div> }</dl> } @else { <p>Sin información de ADOS-2.</p> }</article>
<article class="card"><h3>EEG del estudio</h3>@if (eeg(); as eeg) { <p>Fecha: {{ eeg.effectiveDateTime }}</p><p>Calidad: {{ eegQuality() }}</p><p>Duración: {{ eegExtension('duracion-min') }} minutos. Canales: {{ eegExtension('canales') }}.</p>@if (eeg.conclusion) { <p>{{ eeg.conclusion }}</p> }<dl>@for (o of quality(); track o.id) { <div><dt>{{ o.code.coding?.[0]?.display }}</dt><dd>{{ observationValue(o) }} ({{ qualityStatus(o) }})</dd></div> }</dl> } @else { <p>Sin información de EEG.</p> }</article>
@if (alterationsAvailable() && alterations().length) { <article class="card"><h3>Métricas del EEG</h3><dl>@for (o of alterations(); track o.id) { <div><dt>{{ o.code.coding?.[0]?.display }}</dt><dd>{{ observationValue(o) }}</dd></div> }</dl></article> }
}
</section>
}
</section>
@@ -1,13 +0,0 @@
.dashboard { max-width: 1200px; margin: 0 auto; padding: 1.5rem; color: #142b3d; }
.domain { color: #24735a; font-weight: 600; }
.domain-nav, .tabs, form, .paging { display: flex; flex-wrap: wrap; gap: .8rem; align-items: end; margin: 1rem 0; }
.domain-nav a { color: #216b56; padding: .5rem; }
.tabs { border-bottom: 1px solid #c9d6d1; }
button { border: 1px solid #216b56; border-radius: .3rem; background: #fff; color: #165a47; padding: .55rem .8rem; cursor: pointer; }
button[aria-current="page"], button[type="submit"] { background: #216b56; color: white; }
button:disabled { opacity: .5; cursor: default; }
label { display: grid; gap: .25rem; font-size: .9rem; }
input, select { padding: .45rem; border: 1px solid #8ba09a; border-radius: .25rem; }
.card { border: 1px solid #d5e0dc; border-radius: .5rem; padding: 1rem; margin: 1rem 0; background: #fff; }
dl div { display: flex; gap: 1rem; justify-content: space-between; border-bottom: 1px solid #edf1ef; padding: .3rem 0; } dd { margin: 0; font-weight: 600; }
table { width: 100%; border-collapse: collapse; } th, td { text-align: left; padding: .55rem; border-bottom: 1px solid #d5e0dc; }
@@ -1,69 +0,0 @@
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { TeaStatusPage } from './tea-status-page';
const tag = { tag: [{ system: 'https://isssteleon.org/fhir/CodeSystem/etiqueta', code: 'simulado' }] };
const episode = (id: string) => ({ resourceType: 'EpisodeOfCare', id, meta: tag, patient: { reference: `Patient/${id}` }, type: [{ coding: [{ code: 'SOLO_MCHAT' }] }] });
const measure = { resourceType: 'Measure', id: 'M28-casos-por-estado', title: 'Casos por estatus', url: 'https://isssteleon.org/fhir/Measure/M28-casos-por-estado' };
const bundle = (...items: any[]) => ({ resourceType: 'Bundle', total: items.length, entry: items.map(resource => ({ resource })) });
describe('TEA FHIR journey', () => {
function setup() {
TestBed.configureTestingModule({ providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
const fixture = TestBed.createComponent(TeaStatusPage);
const c = fixture.componentInstance;
const http = TestBed.inject(HttpTestingController);
http.expectOne('/tea/fhir/Measure').flush(bundle(measure));
http.expectOne(r => r.url.endsWith('/$evaluate-measure')).flush({ measure: measure.url, period: { start: '2025-01-01', end: '2025-06-30' }, group: [{ population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 6 }] }] });
return { c, http };
}
it('distinguishes zero, missing and masked values and requests the historical periods', () => {
const { c, http } = setup();
expect(c.value({ count: 0 }, 'count')).toBe('0');
expect(c.value({}, 'count')).toBe('Sin dato');
expect(c.value({ _count: { extension: [{ valueCode: 'masked' }] } }, 'count')).toBe('Dato suprimido');
c.changeSection('historico');
const req = http.expectOne(r => r.url === '/tea/fhir/MeasureReport');
expect(req.request.params.get('periodo')).toBe('2025-01,2025-02,2025-03');
req.flush(bundle());
expect(c.reports()).toEqual([]);
http.verify();
});
it('retains filters and page and rejects a late patient response', () => {
const { c, http } = setup();
c.filters.stage = 'PSICOLOGIA'; c.filters.cutoff = '2025-12-31'; c.filters.cssMin = null as unknown as string; c.page = 1; c.changeSection('seguimiento');
const list = http.expectOne(r => r.url.endsWith('/EpisodeOfCare'));
expect(list.request.params.get('etapa')).toBe('PSICOLOGIA');
expect(list.request.params.get('_offset')).toBe('5');
expect(list.request.params.has('css')).toBe(false);
list.flush({ ...bundle(episode('a'), episode('b')), total: 8 });
c.openPatient(episode('a')); const a = http.expectOne(r => r.url.includes('/Patient/a/'));
c.openPatient(episode('b')); const b = http.expectOne(r => r.url.includes('/Patient/b/'));
b.flush(bundle({ resourceType: 'Patient', id: 'b', meta: tag }));
a.flush(bundle({ resourceType: 'Patient', id: 'a', meta: tag }));
expect(c.selected()).toBe('b'); expect(c.patientResources()[0].id).toBe('b');
c.back(); expect(c.page).toBe(1); expect(c.filters.stage).toBe('PSICOLOGIA');
http.verify();
});
it('rejects an untagged response and shows the OperationOutcome error', () => {
const { c, http } = setup();
c.changeSection('seguimiento');
http.expectOne(r => r.url.endsWith('/EpisodeOfCare')).flush(bundle({ ...episode('a'), meta: {} }));
expect(c.episodeState()).toBe('error');
c.openPatient(episode('a'));
http.expectOne(r => r.url.includes('/Patient/a/')).flush({ issue: [{ diagnostics: 'Paciente no encontrado' }] }, { status: 404, statusText: 'Not Found' });
expect(c.patientError()).toBe('Paciente no encontrado');
http.verify();
});
it('shows alteration groups only when the catalog offers M30', () => {
const { c, http } = setup();
expect(c.alterationsAvailable()).toBe(false);
c.measures.set([measure, { id: 'M30-resultado-eeg', url: 'm30', scoring: { coding: [{ code: 'proportion' }] } }]);
expect(c.alterationsAvailable()).toBe(true);
const rows = c.rows({ measure: 'm30', group: [{ population: [] }, { code: { coding: [{ code: 'ritmo', display: 'Ritmo' }] }, population: [{ code: { coding: [{ code: 'numerator' }] }, count: 0 }] }] });
expect(rows).toContainEqual({ label: 'Ritmo — Numerador', value: '0' });
http.verify();
});
});
@@ -1,185 +0,0 @@
import { HttpClient, HttpParams } from '@angular/common/http';
import { Component, ElementRef, inject, OnDestroy, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterLink } from '@angular/router';
import { forkJoin, Subscription } from 'rxjs';
type Resource = any;
type Section = 'resumen' | 'historico' | 'seguimiento';
type State = 'inicial' | 'cargando' | 'listo' | 'error';
const stages: Record<string, string> = { SOLO_MCHAT: 'Solo M-CHAT', PSICOLOGIA: 'Hasta evaluación psicológica', NEUROPEDIATRIA: 'Hasta evaluación neuropediátrica', EEG: 'Con EEG' };
const populations: Record<string, string> = { 'initial-population': 'Total', numerator: 'Numerador', denominator: 'Denominador', 'denominator-exclusion': 'Excluidos del denominador', 'measure-observation': 'Con valor', 'measure-population-exclusion': 'Sin valor' };
const code = (value: Resource) => value?.coding?.[0]?.code ?? '';
const text = (value: Resource) => value?.coding?.[0]?.display ?? value?.text ?? code(value);
const resources = (bundle: Resource): Resource[] => (bundle?.entry ?? []).map((entry: Resource) => entry.resource);
const simulated = (resource: Resource) => resource?.meta?.tag?.some((tag: Resource) => tag.system === 'https://isssteleon.org/fhir/CodeSystem/etiqueta' && tag.code === 'simulado');
@Component({
selector: 'app-tea-status-page',
imports: [FormsModule, RouterLink],
templateUrl: './tea-status-page.html',
styleUrl: './tea-status-page.scss',
})
export class TeaStatusPage implements OnDestroy {
private readonly http = inject(HttpClient);
private readonly element = inject<ElementRef<HTMLElement>>(ElementRef);
private requests: Subscription[] = [];
private revision = { measures: 0, episodes: 0, patient: 0 };
readonly section = signal<Section>('resumen');
readonly measures = signal<Resource[]>([]);
readonly alterationTypes = signal<Resource[]>([]);
readonly reports = signal<Resource[]>([]);
readonly measureState = signal<State>('inicial');
readonly measureError = signal('');
readonly episodes = signal<Resource[]>([]);
readonly episodeTotal = signal(0);
readonly episodeState = signal<State>('inicial');
readonly episodeError = signal('');
readonly selected = signal<string | null>(null);
readonly patientResources = signal<Resource[]>([]);
readonly patientState = signal<State>('inicial');
readonly patientError = signal('');
periodo = '2025-S1';
historyPeriods = '2025-01,2025-02,2025-03';
measureId = 'M28-casos-por-estado';
eventCutoff = '';
knowledgeCutoff = '';
page = 0;
pageSize = 5;
filters = { since: '', cutoff: '', status: '', stage: '', stageFrom: '', stageTo: '', age: '', mchatMin: '', mchatMax: '', cssMin: '', cssMax: '', eeg: '', alteration: '' };
readonly stages = stages;
constructor() {
this.requests.push(this.http.get<Resource>('/tea/fhir/Measure').subscribe({
next: bundle => {
this.measures.set(resources(bundle).filter(m => /^M(2[1-9]|30)-/.test(m.id)));
if (this.alterationsAvailable()) this.requests.push(this.http.get<Resource>('/tea/fhir/CodeSystem/tea-eeg-metrica').subscribe({ next: system => this.alterationTypes.set(system.concept ?? []), error: () => this.alterationTypes.set([]) }));
this.loadSummary();
},
error: () => { this.measureState.set('error'); this.measureError.set('No fue posible cargar los indicadores.'); },
}));
}
ngOnDestroy() { this.requests.forEach(s => s.unsubscribe()); }
changeSection(section: Section) {
this.section.set(section);
if (section === 'resumen') this.loadSummary();
if (section === 'historico') this.loadHistory();
if (section === 'seguimiento' && this.episodeState() === 'inicial') this.loadEpisodes();
}
private cutoffs(params: HttpParams): HttpParams {
if (this.eventCutoff) params = params.set('corte_evento', this.eventCutoff);
if (this.knowledgeCutoff) params = params.set('corte_conocimiento', new Date(this.knowledgeCutoff).toISOString());
return params;
}
loadSummary() {
const token = ++this.revision.measures;
const measures = this.measures();
if (!measures.length) { this.measureState.set('listo'); this.reports.set([]); return; }
this.measureState.set('cargando');
const params = this.cutoffs(new HttpParams().set('periodo', this.periodo));
this.requests.push(forkJoin(measures.map(m => this.http.get<Resource>(`/tea/fhir/Measure/${encodeURIComponent(m.id)}/$evaluate-measure`, { params }))).subscribe({
next: reports => { if (token === this.revision.measures) { this.reports.set(reports); this.measureState.set('listo'); } },
error: e => { if (token === this.revision.measures) { this.measureError.set(this.errorText(e)); this.measureState.set('error'); } },
}));
}
loadHistory() {
const token = ++this.revision.measures;
const measure = this.measures().find(m => m.id === this.measureId);
if (!measure) { this.measureState.set('error'); this.measureError.set('Seleccione un indicador disponible.'); return; }
this.measureState.set('cargando');
const params = this.cutoffs(new HttpParams().set('measure', measure.url).set('periodo', this.historyPeriods.replace(/\s/g, '')).set('_count', 200));
this.requests.push(this.http.get<Resource>('/tea/fhir/MeasureReport', { params }).subscribe({
next: bundle => { if (token === this.revision.measures) { const found = resources(bundle); if (bundle.total > found.length) { this.measureError.set('Seleccione como máximo 200 periodos.'); this.measureState.set('error'); return; } this.reports.set(found); this.measureState.set('listo'); } },
error: e => { if (token === this.revision.measures) { this.measureError.set(this.errorText(e)); this.measureState.set('error'); } },
}));
}
title(report: Resource) { return this.measures().find(m => report.measure?.split('|')[0] === m.url)?.title ?? report.measure; }
rows(report: Resource): { label: string; value: string }[] {
const group = report.group?.[0];
if (!group) return [];
const rows = (group.population ?? []).map((p: Resource) => ({ label: populations[code(p.code)] ?? text(p.code), value: this.value(p, 'count') }));
const measure = this.measures().find(m => report.measure?.split('|')[0] === m.url);
if (code(measure?.scoring) !== 'cohort') rows.push({ label: 'Resultado', value: group.measureScore ? this.score(group.measureScore) : 'Sin dato' });
for (const extension of group.measureScore?.extension ?? []) {
if (extension.url?.endsWith('/q1') || extension.url?.endsWith('/q3')) rows.push({ label: extension.url.endsWith('/q1') ? 'Primer cuartil' : 'Tercer cuartil', value: `${extension.valueDecimal} días` });
}
for (const stratum of group.stratifier?.[0]?.stratum ?? []) {
const name = code(stratum.value);
const label = stages[name] ?? ({ '16_23': '16 a 23 meses', '24_29': '24 a 29 meses', '30_36': '30 a 36 meses' } as Record<string, string>)[name] ?? text(stratum.value);
if (code(measure?.scoring) === 'cohort') rows.push({ label, value: this.value(stratum.population?.[0], 'count') });
else {
for (const p of stratum.population ?? []) rows.push({ label: `${label} — ${populations[code(p.code)] ?? text(p.code)}`, value: this.value(p, 'count') });
rows.push({ label: `${label} — resultado`, value: stratum.measureScore ? this.score(stratum.measureScore) : 'Sin dato' });
}
}
for (const extra of report.group?.slice(1) ?? []) {
const label = text(extra.code) || 'Grupo';
for (const p of extra.population ?? []) rows.push({ label: `${label} — ${populations[code(p.code)] ?? text(p.code)}`, value: this.value(p, 'count') });
rows.push({ label: `${label} — resultado`, value: extra.measureScore ? this.score(extra.measureScore) : 'Sin dato' });
}
return rows;
}
value(value: Resource, field: string): string {
if (value?.[`_${field}`]?.extension?.some((e: Resource) => e.valueCode === 'masked')) return 'Dato suprimido';
return value?.[field] == null ? 'Sin dato' : String(value[field]);
}
score(score: Resource): string {
if (score?._value?.extension?.some((e: Resource) => e.valueCode === 'masked')) return 'Dato suprimido';
if (score?.value == null) return 'Sin dato';
return score.unit === 'd' ? `${score.value} días` : `${(100 * score.value).toFixed(1)} %`;
}
private errorText(error: Resource) { return error?.error?.issue?.[0]?.diagnostics ?? 'No fue posible consultar la información. Intente de nuevo.'; }
applyFilters() { this.page = 0; this.loadEpisodes(); }
loadEpisodes() {
const token = ++this.revision.episodes;
this.episodeState.set('cargando');
let p = new HttpParams().set('_count', this.pageSize).set('_offset', this.page * this.pageSize).set('_include', '*');
const f = this.filters;
for (const [key, val] of [['status', f.status], ['etapa', f.stage], ['grupo-edad', f.age], ['resultado-eeg', f.eeg]] as const) if (val) p = p.set(key, val);
if (this.alterationsAvailable() && f.alteration) p = p.set('alteracion', f.alteration);
for (const [key, prefix, val] of [['date', 'ge', f.since], ['date', 'le', f.cutoff], ['fecha-etapa', 'ge', f.stageFrom], ['fecha-etapa', 'le', f.stageTo], ['mchat', 'ge', f.mchatMin], ['mchat', 'le', f.mchatMax], ['css', 'ge', f.cssMin], ['css', 'le', f.cssMax]] as const) if (val != null && val !== '') p = p.append(key, prefix + val);
this.requests.push(this.http.get<Resource>('/tea/fhir/EpisodeOfCare', { params: p }).subscribe({
next: bundle => {
if (token !== this.revision.episodes) return;
const found = resources(bundle);
if (found.some(r => !simulated(r))) { this.episodeError.set('La información recibida no está identificada como datos simulados.'); this.episodeState.set('error'); return; }
this.episodes.set(found.filter(r => r.resourceType === 'EpisodeOfCare')); this.episodeTotal.set(bundle.total ?? 0); this.episodeState.set('listo');
},
error: e => { if (token === this.revision.episodes) { this.episodeError.set(this.errorText(e)); this.episodeState.set('error'); } },
}));
}
stage(e: Resource) { const value = code(e.type?.[0]); return stages[value] ?? value ?? 'Sin dato'; }
stageDate(e: Resource) { return e.extension?.find((x: Resource) => x.url.endsWith('/fecha-etapa'))?.valueDate ?? 'Sin dato'; }
patientId(e: Resource): string { return e.patient?.reference?.startsWith('Patient/') ? e.patient.reference.slice(8) : ''; }
openPatient(e: Resource) {
const id = this.patientId(e);
if (!id) { this.episodeError.set('El episodio no identifica a un paciente.'); this.episodeState.set('error'); return; }
const token = ++this.revision.patient;
this.selected.set(id); this.patientState.set('cargando'); this.patientResources.set([]);
this.requests.push(this.http.get<Resource>(`/tea/fhir/Patient/${encodeURIComponent(id)}/$resumen-tea`).subscribe({
next: bundle => {
if (token !== this.revision.patient || this.selected() !== id) return;
const found = resources(bundle);
if (!found.some(r => r.resourceType === 'Patient' && r.id === id) || found.some(r => !simulated(r) || (r.resourceType === 'Patient' && r.id !== id) || (r.subject?.reference && r.subject.reference !== `Patient/${id}`))) {
this.patientError.set('No se pudo verificar la identidad o el origen de la ficha.'); this.patientState.set('error'); return;
}
this.patientResources.set(found); this.patientState.set('listo');
},
error: e => { if (token === this.revision.patient && this.selected() === id) { this.patientError.set(this.errorText(e)); this.patientState.set('error'); } },
}));
}
back() {
const id = this.selected(); ++this.revision.patient; this.selected.set(null);
setTimeout(() => this.element.nativeElement.querySelector<HTMLButtonElement>(`[data-patient="${id}"]`)?.focus());
}
ados() { return this.patientResources().find(r => r.resourceType === 'Observation' && code(r.code) === 'ados2'); }
eeg() { return this.patientResources().find(r => r.resourceType === 'DiagnosticReport' && code(r.code) === 'eeg'); }
eegQuality() { const quality = code(this.eeg()?.conclusionCode?.[0]); return quality === 'BUENO' ? 'Buena' : quality === 'MALO' ? 'Mala' : 'Sin dato'; }
eegExtension(name: string) { const e = this.eeg()?.extension?.find((x: Resource) => x.url.endsWith(`/${name}`)); return e?.valueDecimal ?? e?.valueInteger ?? 'Sin dato'; }
qualityStatus(observation: Resource) { const value = code(observation.interpretation?.[0]); return value === 'BUENO' ? 'buena' : value === 'MALO' ? 'mala' : 'sin dato'; }
quality() { const ids = new Set((this.eeg()?.result ?? []).map((r: Resource) => r.reference)); return this.patientResources().filter(r => r.resourceType === 'Observation' && ids.has(`Observation/${r.id}`) && code(r.code).startsWith('eeg.calidad_')); }
alterationsAvailable() { return this.measures().some(m => m.id.startsWith('M30-')); }
alterations() { return this.patientResources().filter(r => r.resourceType === 'Observation' && r.code?.coding?.[0]?.system?.endsWith('/tea-eeg-metrica') && !r.id?.startsWith('electrodos-')); }
componentValue(c: Resource) { return c.valueInteger ?? c.valueString ?? (text(c.valueCodeableConcept) || 'Sin dato'); }
observationValue(o: Resource) { return o.valueInteger ?? (o.valueQuantity ? `${o.valueQuantity.value} ${o.valueQuantity.unit ?? ''}` : 'Sin dato'); }
}
+46 -7
View File
@@ -2,6 +2,10 @@ import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import {
CohortBuildFile,
Experiment,
ExperimentDetail,
ExperimentRequest,
ModelLineage,
ModelVersion,
PromotionCheck,
@@ -12,7 +16,7 @@ import {
OcrRunSummary,
} from './governance.types';
/** `/governance/*`: model 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);
@@ -44,13 +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);
}
getExperiment(runId: string): Observable<ExperimentDetail> {
return this.http.get<ExperimentDetail>(`/governance/experiments/${runId}`);
}
/** The rendered page, served sandboxed; opened in its own tab. */
experimentPageUrl(runId: string): string {
return `/governance/experiments/${runId}/page`;
}
experimentArtifactUrl(runId: string, path: string): string {
return `/governance/experiments/${runId}/artifacts/${encodePath(path)}`;
}
listOcrJobs(): Observable<{ jobs: OcrJob[] }> {
@@ -80,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)) {
+51 -4
View File
@@ -27,19 +27,66 @@ 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;
cohorte_armado: CohorteArmado | null;
cohorte_exclusiones: CohorteExclusion[];
artifacts: ArtifactPath[];
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[];
}
/** 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;
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 ExperimentDetail extends Experiment {
artifacts: ArtifactFile[];
error: string | null;
}
export interface ExperimentRequest {
file: File;
domain: Domain;
scenario: string;
build: CohortBuildFile;
version?: string | null;
}
/** The indicator kit's cohort build the version was trained on. */
export interface CohorteArmado {
armado_id: number;
@@ -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,6 +12,11 @@
<app-model-versions-panel></app-model-versions-panel>
</div>
</mat-tab>
<mat-tab label="Notebooks">
<div class="governance__panel">
<app-experiments-panel></app-experiments-panel>
</div>
</mat-tab>
<mat-tab label="Revisión de OCR">
<div class="governance__panel">
<app-ocr-review-panel></app-ocr-review-panel>

Some files were not shown because too many files have changed in this diff Show More