Compare commits
49 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| baf5edca42 | |||
| 58ff3870be | |||
| 439a039ff4 | |||
| 049a9ca43c | |||
| f128f2e13a | |||
| 20b8c80aaf | |||
| 8e85c91f15 | |||
| 1ac8d5c258 | |||
| 23cd89e882 | |||
| 47a0ab5f1b | |||
| dc37c54938 | |||
| 2834fac85c | |||
| be77c50b45 | |||
| 40d8c8655e | |||
| 4ffd3797b6 | |||
| b42428b068 | |||
| d9009a2e1e | |||
| bb2f49be37 | |||
| b68af3a48a | |||
| 7eb144e8fe | |||
| c509cb7f87 | |||
| 5807f218b1 | |||
| 4d67b019a6 | |||
| 934a793da3 | |||
| e6abf44bef | |||
| 0ee53fd286 | |||
| 62cdb252ca | |||
| 8f2906fe6f | |||
| e8628508d8 | |||
| 53edec8692 | |||
| a1ea31039e | |||
| ef631e2c0b | |||
| 27dc7a0166 | |||
| e6353f9f4c | |||
| 3bb9c2121d | |||
| 737c6f9f14 | |||
| 8e543cbcc6 | |||
| ea7aad5067 | |||
| 09b52e6b0a | |||
| 078db53ae4 | |||
| 957f4cd024 | |||
| 1ce8d98663 | |||
| 1771cb7ec6 | |||
| b74f188b15 | |||
| 5196f20e47 | |||
| 5d4cd6f654 | |||
| a05717f92d | |||
| 123232592f | |||
| 2cbb994667 |
@@ -2,11 +2,21 @@ import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { routes } from './app.routes';
|
||||
import { IndicadoresService } from './features/indicadores/indicadores.service';
|
||||
import { IndicadoresPeriodos } from './features/indicadores/indicadores-periodos';
|
||||
import { TeaSeguimientoService } from './features/indicadores/tea-seguimiento.service';
|
||||
import { FhirIndicadoresPeriodos, FhirIndicadoresService } from './features/indicadores/indicadores-fhir';
|
||||
import { FhirTeaSeguimientoService } from './features/indicadores/tea-seguimiento-fhir';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
provideBrowserGlobalErrorListeners(),
|
||||
provideRouter(routes),
|
||||
provideHttpClient(),
|
||||
// The indicator page reads the WebApi's FHIR endpoint; without these lines it reads the indicator JSON contract
|
||||
// (`/<domain>/indicadores/<id>/datos`, `/tea/seguimiento`).
|
||||
{ provide: IndicadoresService, useClass: FhirIndicadoresService },
|
||||
{ provide: IndicadoresPeriodos, useClass: FhirIndicadoresPeriodos },
|
||||
{ provide: TeaSeguimientoService, useClass: FhirTeaSeguimientoService },
|
||||
]
|
||||
};
|
||||
|
||||
@@ -6,6 +6,12 @@ const loadIndicadores = () => import('./features/indicadores/indicadores-page').
|
||||
|
||||
export const routes: Routes = [
|
||||
{ path: '', component: Home, title: 'Análisis de información | ISSSTELEON' },
|
||||
{
|
||||
path: 'indicadores/tea-estatus',
|
||||
title: 'Casos por estatus | ISSSTELEON',
|
||||
loadComponent: () => import('./features/indicadores/tea-status-page').then(m => m.TeaStatusPage),
|
||||
data: { workspace: true, breadcrumb: 'Casos por estatus' },
|
||||
},
|
||||
{
|
||||
path: 'conectar',
|
||||
title: 'Conectar datos | ISSSTELEON',
|
||||
@@ -26,6 +32,12 @@ export const routes: Routes = [
|
||||
loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportsPage),
|
||||
data: { workspace: true, breadcrumb: 'Bitácora de cargas' },
|
||||
},
|
||||
{
|
||||
path: 'kpis',
|
||||
title: 'Indicadores | ISSSTELEON',
|
||||
loadComponent: () => import('./features/indicadores/kpis-page').then(m => m.KpisPage),
|
||||
data: { workspace: true, breadcrumb: 'Indicadores' },
|
||||
},
|
||||
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
|
||||
...DOMINIOS.map(dominio => ({
|
||||
path: `indicadores/${dominio}`,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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="Eliminar esta conexión guardada"
|
||||
matTooltip="Eliminar"
|
||||
>
|
||||
<mat-icon aria-hidden="true">close</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
<form [formGroup]="serverForm" class="db-form" (ngSubmit)="connectDatabase()">
|
||||
<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)">
|
||||
Guardar servidor, usuario y base de datos para conexiones futuras (la contraseña no se guarda)
|
||||
</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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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; page: number; page_size: number; }
|
||||
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; }
|
||||
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
|
||||
// A row names its patient with `pac_id` (a decimal string) or the legacy `id_seudonimo`.
|
||||
export interface SeguimientoPaciente {
|
||||
|
||||
@@ -16,11 +16,10 @@ 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('prioridad deshabilitada con una sola opción y sin parámetros nuevos al consultar o paginar', () => {
|
||||
it('sin selector de prioridad ni filtros de TEA, y sin parámetros nuevos al consultar o paginar', () => {
|
||||
respond();
|
||||
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']);
|
||||
expect(fixture.nativeElement.querySelector('select[name="prioridad"]')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('select[name="mchat"]')).toBeNull();
|
||||
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();
|
||||
@@ -92,14 +91,6 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow();
|
||||
open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull();
|
||||
});
|
||||
it('tea conserva su estado pendiente sin consultas de pacientes', () => {
|
||||
const dominio = 'tea';
|
||||
fixture.componentRef.setInput('dominio',dominio); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true);
|
||||
expect(fixture.nativeElement.textContent).toContain('El seguimiento aún no está disponible');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Columnas propuestas para revisión.');
|
||||
expect(fixture.nativeElement.querySelector('table')).not.toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('caption')).toBeNull();
|
||||
});
|
||||
it('valida parámetros antes del transporte sin confundir fechas del filtro general', () => {
|
||||
const service=TestBed.inject(CacuSeguimientoService);
|
||||
for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Display only codes confirmed by the cohort and CaMa catalog; preserve unknown values as received.
|
||||
const EDADES: Readonly<Record<string, string>> = {
|
||||
MENOR_40: 'Menores de 40 años', '40-49': '40 a 49 años', '50-59': '50 a 59 años', '60-69': '60 a 69 años', '70+': '70 años o más', SIN_DATO: 'Sin dato',
|
||||
MENOR_40: 'Menores de 40 años', '<40': 'Menores de 40 años', '40-49': '40 a 49 años', '50-59': '50 a 59 años', '60-69': '60 a 69 años', '70+': '70 años o más', SIN_DATO: 'Sin dato',
|
||||
};
|
||||
const BIRADS = /^BIRADS_(4[ABC]?|5|6)$/;
|
||||
const HISTOLOGIA: Readonly<Record<string, string>> = {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// The parts of FHIR R4 the WebApi's `/<domain>/fhir/` endpoints serve, read loosely: every field is optional and the
|
||||
// readers below decide what a missing one means.
|
||||
|
||||
export interface Coding { system?: string; code?: string; display?: string }
|
||||
export interface Concept { coding?: Coding[]; text?: string }
|
||||
export interface Quantity { value?: number; unit?: string }
|
||||
export interface Extension {
|
||||
url: string;
|
||||
valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number;
|
||||
valueDate?: string; valueDateTime?: string; valueCoding?: Coding; valueReference?: { reference?: string };
|
||||
extension?: Extension[];
|
||||
}
|
||||
export interface Resource {
|
||||
resourceType: string;
|
||||
id?: string;
|
||||
meta?: { tag?: Coding[] };
|
||||
extension?: Extension[];
|
||||
[field: string]: unknown;
|
||||
}
|
||||
export interface Bundle extends Resource {
|
||||
total?: number;
|
||||
entry?: { fullUrl?: string; resource: Resource; search?: { mode?: string } }[];
|
||||
}
|
||||
|
||||
export const CODE_SYSTEM = 'https://isssteleon.org/fhir/CodeSystem/';
|
||||
|
||||
export function code(concept: Concept | undefined): string | undefined {
|
||||
return concept?.coding?.[0]?.code;
|
||||
}
|
||||
export function display(concept: Concept | undefined): string | undefined {
|
||||
return concept?.coding?.[0]?.display ?? concept?.text;
|
||||
}
|
||||
// The code of a concept from `system` (a name under the project's CodeSystem base, or a full URL).
|
||||
export function codeIn(concept: Concept | undefined, system: string): string | undefined {
|
||||
const url = system.includes('://') ? system : CODE_SYSTEM + system;
|
||||
return concept?.coding?.find(c => c.system === url)?.code;
|
||||
}
|
||||
// The extensions named `name` (the last segment of their URL).
|
||||
export function extensions(owner: { extension?: Extension[] } | undefined, name: string): Extension[] {
|
||||
return (owner?.extension ?? []).filter(e => e.url === name || e.url.endsWith('/' + name));
|
||||
}
|
||||
export function extension(owner: { extension?: Extension[] } | undefined, name: string): Extension | undefined {
|
||||
return extensions(owner, name)[0];
|
||||
}
|
||||
export function resources(bundle: Bundle | undefined, type?: string): Resource[] {
|
||||
return (bundle?.entry ?? []).map(e => e.resource).filter(r => !type || r.resourceType === type);
|
||||
}
|
||||
export function isSimulated(resource: Resource): boolean {
|
||||
return !!resource.meta?.tag?.some(t => t.code === 'simulado');
|
||||
}
|
||||
// `Patient/P-1` -> `P-1`.
|
||||
export function referenceId(reference: { reference?: string } | undefined): string | undefined {
|
||||
return reference?.reference?.split('/').pop();
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
{
|
||||
"resourceType": "Bundle",
|
||||
"type": "searchset",
|
||||
"total": 1,
|
||||
"entry": [
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "MeasureReport",
|
||||
"status": "complete",
|
||||
"type": "summary",
|
||||
"measure": "cacu/CACU_DIAS_TOMA_DIAGNOSTICO|0.2.3",
|
||||
"date": "2026-11-08T06:47:32.900609+00:00",
|
||||
"period": {
|
||||
"start": "2025-07-01",
|
||||
"end": "2025-12-31"
|
||||
},
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-evento",
|
||||
"valueDate": "2026-11-08"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
|
||||
"valueDateTime": "2026-11-08T06:47:32.766239+00:00"
|
||||
}
|
||||
],
|
||||
"group": [
|
||||
{
|
||||
"id": "TOTAL",
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-observation"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 2
|
||||
}
|
||||
],
|
||||
"measureScore": {
|
||||
"value": 100.5,
|
||||
"unit": "d",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/q1",
|
||||
"valueDecimal": 70.25
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/q3",
|
||||
"valueDecimal": 130.75
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"improvementNotation": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": "decrease"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
{
|
||||
"resourceType": "Bundle",
|
||||
"type": "searchset",
|
||||
"total": 1,
|
||||
"entry": [
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "MeasureReport",
|
||||
"status": "complete",
|
||||
"type": "summary",
|
||||
"measure": "cacu/CACU_EU13|0.3.2",
|
||||
"date": "2026-11-08T00:28:51.413089+00:00",
|
||||
"period": {
|
||||
"start": "2025-01-01",
|
||||
"end": "2025-06-30"
|
||||
},
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
|
||||
"valueDateTime": "2026-11-08T00:28:51.351883+00:00"
|
||||
}
|
||||
],
|
||||
"group": [
|
||||
{
|
||||
"id": "principal",
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "denominator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "numerator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 0
|
||||
}
|
||||
],
|
||||
"measureScore": {
|
||||
"value": 0.0
|
||||
},
|
||||
"stratifier": [
|
||||
{
|
||||
"code": [
|
||||
{
|
||||
"text": "grupo_edad"
|
||||
}
|
||||
],
|
||||
"stratum": [
|
||||
{
|
||||
"value": {
|
||||
"text": "45-54"
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "denominator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "numerator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 0
|
||||
}
|
||||
],
|
||||
"measureScore": {
|
||||
"value": 0.0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
{
|
||||
"resourceType": "Bundle",
|
||||
"type": "searchset",
|
||||
"total": 2,
|
||||
"entry": [
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "MeasureReport",
|
||||
"status": "complete",
|
||||
"type": "summary",
|
||||
"measure": "cacu/CACU_EU7|0.3.3",
|
||||
"date": "2026-11-08T00:28:56.089006+00:00",
|
||||
"period": {
|
||||
"start": "2025-01-01",
|
||||
"end": "2025-06-30"
|
||||
},
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
|
||||
"valueDateTime": "2026-11-08T00:28:56.025101+00:00"
|
||||
}
|
||||
],
|
||||
"group": [
|
||||
{
|
||||
"id": "TOTAL",
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-observation"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
}
|
||||
],
|
||||
"stratifier": [
|
||||
{
|
||||
"code": [
|
||||
{
|
||||
"text": "resultado"
|
||||
}
|
||||
],
|
||||
"stratum": [
|
||||
{
|
||||
"value": {
|
||||
"text": "LIEBG"
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"value": {
|
||||
"text": "NEGATIVO"
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 2
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"value": {
|
||||
"text": "SIN_DATO"
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": [
|
||||
{
|
||||
"text": "grupo_edad"
|
||||
}
|
||||
],
|
||||
"stratum": [
|
||||
{
|
||||
"value": {
|
||||
"text": "45-54"
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "MeasureReport",
|
||||
"status": "complete",
|
||||
"type": "summary",
|
||||
"measure": "cacu/CACU_EU7|0.3.3",
|
||||
"date": "2026-11-08T00:28:56.099338+00:00",
|
||||
"period": {
|
||||
"start": "2025-07-01",
|
||||
"end": "2025-12-31"
|
||||
},
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
|
||||
"valueInteger": 2
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
|
||||
"valueDateTime": "2026-11-08T00:28:56.025101+00:00"
|
||||
}
|
||||
],
|
||||
"group": [
|
||||
{
|
||||
"id": "TOTAL",
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-observation"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
}
|
||||
],
|
||||
"stratifier": [
|
||||
{
|
||||
"code": [
|
||||
{
|
||||
"text": "resultado"
|
||||
}
|
||||
],
|
||||
"stratum": [
|
||||
{
|
||||
"value": {
|
||||
"text": "LIEAG"
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"value": {
|
||||
"text": "NEGATIVO"
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"value": {
|
||||
"text": "SIN_DATO"
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 2
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": [
|
||||
{
|
||||
"text": "grupo_edad"
|
||||
}
|
||||
],
|
||||
"stratum": [
|
||||
{
|
||||
"value": {
|
||||
"text": "45-54"
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
{
|
||||
"resourceType": "Bundle",
|
||||
"type": "searchset",
|
||||
"total": 2,
|
||||
"entry": [
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "MeasureReport",
|
||||
"status": "complete",
|
||||
"type": "summary",
|
||||
"measure": "cacu/IND1|0.3.2",
|
||||
"date": "2026-11-08T00:28:50.038223+00:00",
|
||||
"period": {
|
||||
"start": "2025-01-01",
|
||||
"end": "2025-06-30"
|
||||
},
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
|
||||
"valueDateTime": "2026-11-08T00:28:49.977023+00:00"
|
||||
}
|
||||
],
|
||||
"group": [
|
||||
{
|
||||
"id": "principal",
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "denominator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "numerator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 1
|
||||
}
|
||||
],
|
||||
"measureScore": {
|
||||
"value": 0.25
|
||||
}
|
||||
}
|
||||
],
|
||||
"improvementNotation": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": "decrease"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "MeasureReport",
|
||||
"status": "complete",
|
||||
"type": "summary",
|
||||
"measure": "cacu/IND1|0.3.2",
|
||||
"date": "2026-11-08T00:28:50.044435+00:00",
|
||||
"period": {
|
||||
"start": "2025-07-01",
|
||||
"end": "2025-12-31"
|
||||
},
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
|
||||
"valueInteger": 2
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
|
||||
"valueDateTime": "2026-11-08T00:28:49.977023+00:00"
|
||||
}
|
||||
],
|
||||
"group": [
|
||||
{
|
||||
"id": "principal",
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "denominator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "numerator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 1
|
||||
}
|
||||
],
|
||||
"measureScore": {
|
||||
"value": 0.25
|
||||
}
|
||||
}
|
||||
],
|
||||
"improvementNotation": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": "decrease"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "dimensiones": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "medidas": [{"clave": "maligno", "etiqueta": "Carcinoma in situ o invasor"}, {"clave": "invasor", "etiqueta": "Carcinoma invasor"}], "horizontes_dias": [30, 90, 180, 365], "tipos_periodo": ["mes", "semestre"], "secciones": [{"clave": "resumen", "titulo": "Indicadores de la cohorte", "estado": "disponible", "motivo": null}, {"clave": "distribucion", "titulo": "Distribución de pacientes", "estado": "disponible", "motivo": null}, {"clave": "comparacion", "titulo": "Comparación entre grupos", "estado": "disponible", "motivo": null}, {"clave": "mapa", "titulo": "Mapa entre variables", "estado": "disponible", "motivo": null}, {"clave": "tendencia", "titulo": "Tendencia en el tiempo", "estado": "disponible", "motivo": null}], "no_disponibles": [{"clave": "supervivencia", "titulo": "Supervivencia", "motivo": "No hay estado vital ni fecha de defunción en las fuentes."}, {"clave": "recaida", "titulo": "Recaída", "motivo": "No hay registro de recurrencia ni de tratamiento en las fuentes."}, {"clave": "adherencia_tratamiento", "titulo": "Adherencia al tratamiento", "motivo": "No hay tabla de tratamientos ni de visitas de seguimiento."}, {"clave": "curvas_tiempo_a_evento", "titulo": "Curvas de incidencia acumulada y de supervivencia", "motivo": "El seguimiento de quien no tuvo el evento no está registrado: no hay censura verificable ni tiempo cero común, y la muerte como riesgo competitivo no existe."}, {"clave": "riesgos_proporcionales", "titulo": "Razones de riesgo (Cox), log-rank y tiempo medio restringido", "motivo": "Dependen de las curvas anteriores."}, {"clave": "brca_estadio_tamano", "titulo": "BRCA, estadio clínico y tamaño tumoral", "motivo": "No hay registros de estas variables en las fuentes."}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "birads", "medida": "maligno", "denominador": "pacientes con resultado de biopsia conocido", "grupos": [{"estado": "suprimido", "casos": null, "total": null, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4", "etiqueta": "BI-RADS 4", "seleccion": {"birads": "BIRADS_4"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A", "seleccion": {"birads": "BIRADS_4A"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B", "seleccion": {"birads": "BIRADS_4B"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C", "seleccion": {"birads": "BIRADS_4C"}}, {"estado": "suprimido", "casos": null, "total": null, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_5", "etiqueta": "BI-RADS 5", "seleccion": {"birads": "BIRADS_5"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_6", "etiqueta": "BI-RADS 6", "seleccion": {"birads": "BIRADS_6"}}], "prueba": {"valida": false, "motivo": "Hacen falta al menos dos grupos con datos publicados.", "nombre": "Chi cuadrada de homogeneidad"}}
|
||||
@@ -0,0 +1 @@
|
||||
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "grupo_edad", "medida": "invasor", "denominador": "pacientes con resultado de biopsia conocido", "grupos": [{"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "<40", "etiqueta": "<40", "seleccion": {"grupo_edad": "<40"}}, {"estado": "disponible", "casos": 5, "total": 12, "valor": 41.67, "ic_bajo": 19.33, "ic_alto": 68.05, "codigo": "40-49", "etiqueta": "40-49", "seleccion": {"grupo_edad": "40-49"}}, {"estado": "disponible", "casos": 6, "total": 13, "valor": 46.15, "ic_bajo": 23.21, "ic_alto": 70.86, "codigo": "50-59", "etiqueta": "50-59", "seleccion": {"grupo_edad": "50-59"}}, {"estado": "disponible", "casos": 8, "total": 17, "valor": 47.06, "ic_bajo": 26.17, "ic_alto": 69.04, "codigo": "60-69", "etiqueta": "60-69", "seleccion": {"grupo_edad": "60-69"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "70+", "etiqueta": "70+", "seleccion": {"grupo_edad": "70+"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "SIN_DATO", "etiqueta": "Sin dato", "seleccion": {"grupo_edad": "SIN_DATO"}}], "prueba": {"valida": true, "estadistico": 0.0889, "gl": 2, "p": 0.9565070599102384, "nombre": "Chi cuadrada de homogeneidad"}}
|
||||
@@ -0,0 +1 @@
|
||||
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "biopsia", "total": 61, "items": [{"codigo": "BENIGNO", "etiqueta": "Benigno", "suprimido": false, "n": 21, "porcentaje": 34.43, "ic_bajo": 23.75, "ic_alto": 46.95, "seleccion": {"biopsia": "BENIGNO"}}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"biopsia": "CARCINOMA_IN_SITU"}}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"biopsia": "CARCINOMA_INVASOR"}}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"biopsia": "SIN_DATO"}}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada", "suprimido": false, "n": 19, "porcentaje": 31.15, "ic_bajo": 20.94, "ic_alto": 43.59, "seleccion": {"biopsia": "SIN_BIOPSIA"}}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "birads", "total": 61, "items": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4", "suprimido": false, "n": 33, "porcentaje": 54.1, "ic_bajo": 41.72, "ic_alto": 65.99, "seleccion": {"birads": "BIRADS_4"}}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4A"}}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4B"}}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4C"}}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"birads": "BIRADS_5"}}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"birads": "BIRADS_6"}}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "grupo_edad", "total": 61, "items": [{"codigo": "<40", "etiqueta": "<40", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "<40"}}, {"codigo": "40-49", "etiqueta": "40-49", "suprimido": false, "n": 16, "porcentaje": 26.23, "ic_bajo": 16.84, "ic_alto": 38.44, "seleccion": {"grupo_edad": "40-49"}}, {"codigo": "50-59", "etiqueta": "50-59", "suprimido": false, "n": 19, "porcentaje": 31.15, "ic_bajo": 20.94, "ic_alto": 43.59, "seleccion": {"grupo_edad": "50-59"}}, {"codigo": "60-69", "etiqueta": "60-69", "suprimido": false, "n": 26, "porcentaje": 42.62, "ic_bajo": 31.02, "ic_alto": 55.1, "seleccion": {"grupo_edad": "60-69"}}, {"codigo": "70+", "etiqueta": "70+", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "70+"}}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "SIN_DATO"}}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"simulado": true, "cohorte": "cama_birads_v1", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "escenario": "diagnostico", "corte": "2026-11-16", "umbral_supresion": 5, "unidad": "paciente", "denominador": "pacientes elegibles con última mastografía reportada BI-RADS 4 a 6", "grupos": [{"codigo": "BIRADS_4", "n": 33, "suprimido": false}, {"codigo": "BIRADS_4A", "n": 0, "suprimido": false}, {"codigo": "BIRADS_4B", "n": 0, "suprimido": false}, {"codigo": "BIRADS_4C", "n": 0, "suprimido": false}, {"codigo": "BIRADS_5", "n": null, "suprimido": true}, {"codigo": "BIRADS_6", "n": null, "suprimido": true}], "horizonte_dias": 0, "indicadores": []}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
{"error": "la selección tiene menos de 5 pacientes: su lista no se publica.", "motivo": "supresion"}
|
||||
@@ -0,0 +1 @@
|
||||
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "horizonte_dias": 90, "indicadores": [{"clave": "cohorte", "titulo": "Pacientes en la cohorte BI-RADS 4 a 6", "descripcion": "Pacientes cuya última mastografía reportada al corte es BI-RADS 4, 5 o 6.", "unidad": "pacientes", "estado": "disponible", "valor": 61, "ic_bajo": null, "ic_alto": null, "n": 61, "denominador": null, "q1": null, "q3": null, "motivo": null}, {"clave": "con_biopsia", "titulo": "Con biopsia reportada", "descripcion": "Pacientes de la cohorte con al menos un reporte de biopsia de esa mastografía, entre las de la cohorte.", "unidad": "%", "estado": "disponible", "valor": 68.85, "ic_bajo": 56.41, "ic_alto": 79.06, "n": 42, "denominador": 61, "q1": null, "q3": null, "motivo": null}, {"clave": "maligno_conocido", "titulo": "Resultado maligno entre las biopsias con resultado", "descripcion": "Carcinoma in situ o invasor entre las pacientes de la cohorte con resultado de biopsia conocido. No es incidencia: el denominador son pacientes ya biopsiadas.", "unidad": "%", "estado": "disponible", "valor": 50.0, "ic_bajo": 35.53, "ic_alto": 64.47, "n": 21, "denominador": 42, "q1": null, "q3": null, "motivo": null}, {"clave": "invasor_conocido", "titulo": "Carcinoma invasor entre las biopsias con resultado", "descripcion": "Carcinoma invasor entre las pacientes de la cohorte con resultado de biopsia conocido.", "unidad": "%", "estado": "disponible", "valor": 45.24, "ic_bajo": 31.22, "ic_alto": 60.05, "n": 19, "denominador": 42, "q1": null, "q3": null, "motivo": null}, {"clave": "biopsia_90d", "titulo": "Biopsia reportada en 90 días", "descripcion": "Pacientes cuya biopsia se reportó dentro de 90 días de la mastografía, entre las que ya cumplieron 90 días al corte.", "unidad": "%", "estado": "disponible", "valor": 75.56, "ic_bajo": 61.33, "ic_alto": 85.76, "n": 34, "denominador": 45, "q1": null, "q3": null, "motivo": null}, {"clave": "maligno_90d", "titulo": "Cáncer confirmado en 90 días", "descripcion": "Pacientes con un reporte de biopsia maligna dentro de 90 días de la mastografía, entre las que ya cumplieron 90 días al corte. No es incidencia acumulada: no hay seguimiento de quien no tuvo biopsia.", "unidad": "%", "estado": "disponible", "valor": 40.0, "ic_bajo": 27.02, "ic_alto": 54.55, "n": 18, "denominador": 45, "q1": null, "q3": null, "motivo": null}, {"clave": "dias_a_biopsia", "titulo": "Días de la mastografía al reporte de biopsia", "descripcion": "Mediana y cuartiles entre las pacientes con biopsia reportada.", "unidad": "días", "estado": "disponible", "valor": 27.5, "ic_bajo": null, "ic_alto": null, "n": 42, "denominador": null, "q1": 19.25, "q3": 30.75, "motivo": null}], "no_disponibles": [{"clave": "supervivencia", "titulo": "Supervivencia", "motivo": "No hay estado vital ni fecha de defunción en las fuentes."}, {"clave": "recaida", "titulo": "Recaída", "motivo": "No hay registro de recurrencia ni de tratamiento en las fuentes."}, {"clave": "adherencia_tratamiento", "titulo": "Adherencia al tratamiento", "motivo": "No hay tabla de tratamientos ni de visitas de seguimiento."}, {"clave": "curvas_tiempo_a_evento", "titulo": "Curvas de incidencia acumulada y de supervivencia", "motivo": "El seguimiento de quien no tuvo el evento no está registrado: no hay censura verificable ni tiempo cero común, y la muerte como riesgo competitivo no existe."}, {"clave": "riesgos_proporcionales", "titulo": "Razones de riesgo (Cox), log-rank y tiempo medio restringido", "motivo": "Dependen de las curvas anteriores."}, {"clave": "brca_estadio_tamano", "titulo": "BRCA, estadio clínico y tamaño tumoral", "motivo": "No hay registros de estas variables en las fuentes."}]}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
{"corte": "2026-11-16", "umbral_supresion": 5, "tipo_periodo": "semestre", "unidad": "reportes", "poblacion": "Reportes de mastografía con BI-RADS reportado y reportes de biopsia vinculados a una de esas mastografías, de todas las pacientes; no la cohorte de Seguimiento", "alcance_biopsias": "Solo biopsias que se pueden ligar a una mastografía con BI-RADS reportado (mastografía, orden, reporte); una biopsia sin mastografía ligada no se cuenta", "denominador": "reportes de biopsia con resultado conocido en el periodo", "periodos": [{"periodo": "2025-S1", "inicio": "2025-01-01", "fin": "2025-06-30", "incompleto": false, "reportes_mastografia": {"total": 96, "por_categoria": {"4_a_6": {"n": 31, "suprimido": false}, "otras": {"n": 65, "suprimido": false}}}, "reportes_biopsia": {"total": 24, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 15, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 16, "total": 24, "valor": 66.67, "ic_bajo": 46.71, "ic_alto": 82.03}}, {"periodo": "2025-S2", "inicio": "2025-07-01", "fin": "2025-12-31", "incompleto": false, "reportes_mastografia": {"total": 97, "por_categoria": {"4_a_6": {"n": 37, "suprimido": false}, "otras": {"n": 60, "suprimido": false}}}, "reportes_biopsia": {"total": 25, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 13, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 14, "total": 25, "valor": 56.0, "ic_bajo": 37.07, "ic_alto": 73.33}}, {"periodo": "2026-S1", "inicio": "2026-01-01", "fin": "2026-06-30", "incompleto": false, "reportes_mastografia": {"total": 97, "por_categoria": {"4_a_6": {"n": 25, "suprimido": false}, "otras": {"n": 72, "suprimido": false}}}, "reportes_biopsia": {"total": 18, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 11, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 13, "total": 18, "valor": 72.22, "ic_bajo": 49.13, "ic_alto": 87.5}}, {"periodo": "2026-S2", "inicio": "2026-07-01", "fin": "2026-12-31", "incompleto": true, "reportes_mastografia": {"total": 72, "por_categoria": {"4_a_6": {"n": 27, "suprimido": false}, "otras": {"n": 45, "suprimido": false}}}, "reportes_biopsia": {"total": 19, "por_grado": {"BENIGNO": {"n": 9, "suprimido": false}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": null, "suprimido": true}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 10, "total": 19, "valor": 52.63, "ic_bajo": 31.71, "ic_alto": 72.67}}]}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,842 @@
|
||||
{
|
||||
"resourceType": "Bundle",
|
||||
"type": "searchset",
|
||||
"total": 8,
|
||||
"link": [
|
||||
{
|
||||
"relation": "self",
|
||||
"url": "http://127.0.0.1:28091/cama/fhir/Measure?_count=50&_offset=0"
|
||||
}
|
||||
],
|
||||
"entry": [
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIOPSIAS",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-BIOPSIAS",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIOPSIAS",
|
||||
"version": "0.2.0",
|
||||
"name": "cama_biopsias",
|
||||
"title": "Distribución de resultados de biopsia",
|
||||
"status": "active",
|
||||
"description": "Cuántas biopsias reportadas en el semestre caen en cada grado histológico. Se cuenta cada biopsia, no cada paciente. «Sin dato»: el reporte no trae grado.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C2"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "cohort"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_biopsias"
|
||||
}
|
||||
}
|
||||
],
|
||||
"stratifier": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "grado"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "examen"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-BIRADS",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS",
|
||||
"version": "0.2.0",
|
||||
"name": "cama_birads",
|
||||
"title": "Distribución de BI-RADS",
|
||||
"status": "active",
|
||||
"description": "Cuántas pacientes caen en cada categoría de BI-RADS en el semestre, cada una en la más grave de sus mastografías. «Sin dato»: ninguna de sus mastografías tiene reporte con BI-RADS.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C2"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "cohort"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_birads"
|
||||
}
|
||||
}
|
||||
],
|
||||
"stratifier": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "birads"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "paciente"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS-CANCER-INVASOR",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-BIRADS-CANCER-INVASOR",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS-CANCER-INVASOR",
|
||||
"version": "0.1.0",
|
||||
"name": "cama_birads_cancer_invasor",
|
||||
"title": "BI-RADS de los cánceres invasores",
|
||||
"status": "active",
|
||||
"description": "De las pacientes con una biopsia reportada en el periodo con carcinoma invasor, cuántas tenían cada BI-RADS en la mastografía que originó su biopsia más reciente, por edad y por las características del tumor: estadio clínico, etapa, subtipo molecular y tamaño. Las características vienen de los reportes leídos por texto y son provisionales. «Sin dato»: la biopsia no se ligó a una mastografía con BI-RADS.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C2"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "cohort"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_birads_cancer_invasor"
|
||||
}
|
||||
}
|
||||
],
|
||||
"stratifier": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "birads"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "grupo_edad"
|
||||
}
|
||||
],
|
||||
"text": "grupo_edad"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "estadio"
|
||||
}
|
||||
],
|
||||
"text": "Estadio clínico"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "etapa"
|
||||
}
|
||||
],
|
||||
"text": "Etapa"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "clasificacion"
|
||||
}
|
||||
],
|
||||
"text": "Subtipo molecular"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "tamano"
|
||||
}
|
||||
],
|
||||
"text": "Tamaño tumoral (T)"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "paciente"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS456-MASTOGRAFIA",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-BIRADS456-MASTOGRAFIA",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS456-MASTOGRAFIA",
|
||||
"version": "0.2.0",
|
||||
"name": "cama_birads_456_mastografia",
|
||||
"title": "Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6",
|
||||
"status": "active",
|
||||
"description": "Cuántas mastografías tomadas en el periodo tienen BI-RADS 4, 5 o 6, cada una con su categoría.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C2"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "cohort"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_birads_456_mastografia"
|
||||
}
|
||||
}
|
||||
],
|
||||
"stratifier": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "birads"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "examen"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS456-PACIENTE",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-BIRADS456-PACIENTE",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS456-PACIENTE",
|
||||
"version": "0.2.0",
|
||||
"name": "cama_birads_456_paciente",
|
||||
"title": "Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6",
|
||||
"status": "active",
|
||||
"description": "Cuántas pacientes tienen como BI-RADS más grave del periodo un 4, 5 o 6, cada una en la más grave de sus mastografías.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C2"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "cohort"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_birads_456_paciente"
|
||||
}
|
||||
}
|
||||
],
|
||||
"stratifier": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "birads"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "paciente"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-CONFIRMACION-BIRADS45",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-CONFIRMACION-BIRADS45",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-CONFIRMACION-BIRADS45",
|
||||
"version": "0.2.0",
|
||||
"name": "cama_confirmacion_birads45",
|
||||
"title": "Tasa de confirmación histopatológica",
|
||||
"status": "active",
|
||||
"description": "De las mastografías del semestre con BI-RADS de sospecha, las que tienen una biopsia reportada originada por esa mastografía. A la fecha de corte: sin un plazo máximo, el valor puede subir mientras lleguen reportes. No dice si la biopsia confirmó cáncer.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C1"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "proportion"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "principal"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_confirmacion_birads45_denominador"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "denominator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Denominador",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_confirmacion_birads45_denominador"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "numerator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Numerador",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_confirmacion_birads45_numerador"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "episodio"
|
||||
}
|
||||
]
|
||||
},
|
||||
"improvementNotation": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": "increase"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-DIAS-TOMA-DIAGNOSTICO",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-DIAS-TOMA-DIAGNOSTICO",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-DIAS-TOMA-DIAGNOSTICO",
|
||||
"version": "0.2.2",
|
||||
"name": "cama_dias_toma_diagnostico",
|
||||
"title": "Tiempo de tamizaje a diagnóstico",
|
||||
"status": "active",
|
||||
"description": "Días naturales de la toma de cada mastografía del semestre a la primera nota médica posterior que la resuelve: un diagnóstico CIE-10 de la lista (normal, benigno, lesión o cáncer), escrito por una de las especialidades que diagnostican, dentro del horizonte y a la fecha de corte. Entran todas las mastografías, sean de tamizaje o no; se excluyen las de pacientes con un diagnóstico de cáncer de mama anterior a la toma.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C3r"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "continuous-variable"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_dias_toma_diagnostico"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-observation"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades con valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_dias_toma_diagnostico"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-population-exclusion"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades sin valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_dias_toma_diagnostico"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "examen"
|
||||
}
|
||||
]
|
||||
},
|
||||
"improvementNotation": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": "decrease"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-EU38A",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-EU38A",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-EU38A",
|
||||
"version": "0.2.1",
|
||||
"name": "cama_eu38a",
|
||||
"title": "Días de la toma de la mastografía a su resultado",
|
||||
"status": "active",
|
||||
"description": "Días naturales de la toma de cada mastografía del semestre a su resultado, a la fecha de corte. Las que aún no tienen resultado y siguen dentro del horizonte no se miden; las que lo pasaron sin resultado cuentan en los excluidos.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C3r"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "continuous-variable"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_eu38a"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-observation"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades con valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_eu38a"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-population-exclusion"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades sin valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_eu38a"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "examen"
|
||||
}
|
||||
]
|
||||
},
|
||||
"improvementNotation": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": "decrease"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
{"error": "la selección tiene menos de 5 pacientes: su lista no se publica.", "motivo": "supresion"}
|
||||
@@ -0,0 +1 @@
|
||||
{"simulado": true, "cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "a2c95b755ba3ccab288c148153e14be1e958aadff1f5a320a4d54e84b3cae745", "corte": "2026-11-17", "ventana": {"meses": 6, "desde": "2026-05-18", "hasta": "2026-11-17"}, "filtros": {"birads": "BIRADS_5", "grupo_edad": null, "biopsia": null}, "filtros_disponibles": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "columnas": [{"clave": "pac_id", "etiqueta": "Identificador de paciente"}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad"}, {"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]}, {"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de reporte"}]}], "paginacion": {"page": 1, "page_size": 50, "total_items": 16, "total_pages": 1}, "items": [{"pac_id": "251", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-11-05", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "185", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "95", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-15", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-11-14"}, {"pac_id": "188", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-04", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-20"}, {"pac_id": "126", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-27", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-04"}, {"pac_id": "52", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "220", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-19", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}, {"pac_id": "254", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-11", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-09-16"}, {"pac_id": "129", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-22", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-08-20"}, {"pac_id": "117", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-21", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-08-09"}, {"pac_id": "101", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-03", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-07-31"}, {"pac_id": "225", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-02", "biopsia": "CARCINOMA_IN_SITU", "biopsia_fecha": "2026-07-31"}, {"pac_id": "287", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-14", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-07-13"}, {"pac_id": "55", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-09", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-06-30"}, {"pac_id": "7", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-02", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "260", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-05-21", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-06-07"}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"simulado": true, "cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "a2c95b755ba3ccab288c148153e14be1e958aadff1f5a320a4d54e84b3cae745", "corte": "2026-11-17", "ventana": {"meses": 3, "desde": "2026-08-18", "hasta": "2026-11-17"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "filtros_disponibles": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "columnas": [{"clave": "pac_id", "etiqueta": "Identificador de paciente"}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad"}, {"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]}, {"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de reporte"}]}], "paginacion": {"page": 1, "page_size": 50, "total_items": 16, "total_pages": 1}, "items": [{"pac_id": "251", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-11-05", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "54", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "185", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "255", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-21", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "95", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-15", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-11-14"}, {"pac_id": "4", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-10", "biopsia": "BENIGNO", "biopsia_fecha": "2026-11-06"}, {"pac_id": "256", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-08", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "188", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-04", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-20"}, {"pac_id": "239", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-09-14", "biopsia": "BENIGNO", "biopsia_fecha": "2026-10-06"}, {"pac_id": "245", "grupo_edad": "40-49", "birads": "BIRADS_4", "mastografia_fecha": "2026-09-09", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "186", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-31", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}, {"pac_id": "282", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-29", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-10"}, {"pac_id": "126", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-27", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-04"}, {"pac_id": "31", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "52", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "220", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-19", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}]}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
@@ -3,7 +3,6 @@ import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { 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';
|
||||
@@ -28,7 +27,6 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
fixture.componentRef.setInput('indicador', { id: 'i', titulo: 'I', contrato: 'C2', figuras, tipos_periodo: ['semestre'] });
|
||||
fixture.componentRef.setInput('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(); }
|
||||
@@ -47,13 +45,9 @@ 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 selector, consulta y memoria', () => {
|
||||
it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para consulta y memoria', () => {
|
||||
fixture.destroy(); create(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c2_barras', 'fig_c2_donas', 'fig_c9_futura']);
|
||||
fixture.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 [
|
||||
@@ -62,7 +56,7 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
['fig_c2_donas', 'Donas'],
|
||||
['fig_c9_futura', 'Representación 5'],
|
||||
]) {
|
||||
select().selectionChange.emit({ source: select(), value: id }); fixture.detectChanges();
|
||||
fixture.componentInstance.selectFigure(id); fixture.detectChanges();
|
||||
const pending = request(id);
|
||||
expect(pending.request.url).toBe('/cacu/indicadores/i/figuras/' + id);
|
||||
expect(pending.request.params.get('tema')).toBe('claro');
|
||||
@@ -74,9 +68,9 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
}
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
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('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('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',
|
||||
@@ -98,9 +92,8 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
expect(cards.every(card => card.interpretation.every(line => line !== 'No debe asignarse.'))).toBe(true);
|
||||
});
|
||||
it('múltiples opciones habilitan el selector, mantienen una representación y cancelan cambios rápidos', () => {
|
||||
open(); const first = request('f'); expect(select().disabled).toBe(false);
|
||||
expect(select().options.map(o => o.value)).toEqual(['f', 'g']); expect(panels()).toHaveLength(1);
|
||||
select().selectionChange.emit({ source: select(), value: 'g' }); fixture.detectChanges();
|
||||
open(); const first = request('f'); expect(panels()).toHaveLength(1);
|
||||
fixture.componentInstance.selectFigure('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,8 +2,6 @@ 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';
|
||||
@@ -29,7 +27,7 @@ import { parConteos } from './indicadores-conteos-pareados';
|
||||
@Component({
|
||||
selector: 'app-indicador-catalog-card',
|
||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
|
||||
template: `
|
||||
<mat-card>
|
||||
<header>
|
||||
@@ -67,16 +65,6 @@ import { parConteos } from './indicadores-conteos-pareados';
|
||||
<app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
</div>
|
||||
} @else if (selectedFigure) {
|
||||
@if (!sobrio && (!pair.length || otherFigures.length)) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Representación gráfica</mat-label>
|
||||
<mat-select [value]="selectedFigure" [disabled]="indicador.figuras.length === 1"
|
||||
[attr.aria-label]="'Representación gráfica de ' + indicador.titulo" (selectionChange)="selectFigure($event.value)">
|
||||
@if (pair.length) { <mat-option [value]="pair[0]">Dona y barras</mat-option> }
|
||||
@for (figure of (pair.length ? otherFigures : indicador.figuras); track figure) { <mat-option [value]="figure">{{ figureDisplayName(figure, indicador.figuras) }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
<div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual">
|
||||
@for (figure of displayFigures; track panelIdentity(figure)) {
|
||||
<div class="representation-panel">
|
||||
@@ -156,7 +144,6 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
get tiempos() { return parTiempos(this.dominio, this.indicador.id); }
|
||||
// Exams and patients of the same finding, drawn together on the exams' card.
|
||||
get conteos() { return parConteos(this.dominio, this.indicador.id); }
|
||||
get 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() {
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
<div class="figures">
|
||||
<section class="figure"><h3>{{ par.unidades.examenes | titlecase }} por categoría, {{ m.periodo }}</h3>
|
||||
@if (total) {
|
||||
<app-plotly-chart [figure]="donutFigure!" [showNotes]="false" [label]="indicador.titulo + ', dona, ' + m.periodo" />
|
||||
<app-plotly-chart [figure]="donutFigure!" class="donut-chart" (widthChanged)="ajustarAnchoDona($event)" [showNotes]="false" [label]="indicador.titulo + ', dona, ' + m.periodo" />
|
||||
} @else { <p role="status">{{ total === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.examenes + ' en el periodo.' }}</p> }
|
||||
@if (m.sinDato) { <p class="note">Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.</p> }
|
||||
</section>
|
||||
|
||||
@@ -14,6 +14,8 @@ h3 { font-size: 1rem; font-weight: 500; line-height: 1.5; }
|
||||
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||
@media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
app-plotly-chart { --plot-height: 400px; }
|
||||
// Keep space for the outside labels and let the existing plot viewport scroll on very narrow cards.
|
||||
.donut-chart { --plot-min-width: 230px; }
|
||||
summary { cursor: pointer; padding-block: .75rem; }
|
||||
summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.table-scroll { overflow: auto; }
|
||||
|
||||
@@ -38,10 +38,7 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
|
||||
private subscription?: Subscription;
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
// On a narrow screen the donut's long label gives way to a legend under it.
|
||||
private readonly estrecha = typeof matchMedia === 'function' ? matchMedia('(max-width: 520px)') : undefined;
|
||||
private readonly alCambiarAncho = () => { if (this.model) this.draw(); };
|
||||
constructor() { this.estrecha?.addEventListener('change', this.alCambiarAncho); }
|
||||
private anchoDona = 390;
|
||||
|
||||
get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; }
|
||||
get total() { return this.model ? totalExamenes(this.model) : null; }
|
||||
@@ -108,12 +105,18 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
|
||||
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
|
||||
this.periodIndex += step; this.draw();
|
||||
}
|
||||
ajustarAnchoDona(ancho: number) {
|
||||
if (ancho === this.anchoDona) return;
|
||||
this.anchoDona = ancho;
|
||||
const m = this.model;
|
||||
if (m) this.donutFigure = donaConteos(m, this.par, this.tema, ancho);
|
||||
}
|
||||
private draw() {
|
||||
const m = this.model;
|
||||
if (!m) return;
|
||||
this.donutFigure = donaConteos(m, this.par, this.tema, this.estrecha?.matches ?? false);
|
||||
this.donutFigure = donaConteos(m, this.par, this.tema, this.anchoDona);
|
||||
this.barsFigure = barrasConteos(m, this.par, this.tema);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecha?.removeEventListener('change', this.alCambiarAncho); }
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||
}
|
||||
|
||||
@@ -83,7 +83,23 @@
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (state.status === 'ready' && state.donutLegend?.length) {
|
||||
@if (state.status === 'ready' && state.highlight; as h) {
|
||||
<div class="highlight-legend" role="group" aria-label="Resaltar partes de la figura">
|
||||
<p class="highlight-status" role="status" aria-live="polite">Selección: {{ highlightStatus }}</p>
|
||||
<button type="button" class="highlight-back" (click)="highlightBack()" [disabled]="!highlightSelection.group && !highlightSelection.item">Volver</button>
|
||||
@for (row of highlightRows(h); track row.group?.id ?? '') {
|
||||
<div class="highlight-keys" role="group" [attr.aria-label]="row.group ? row.group.label + ' y sus categorías' : 'Categorías'">
|
||||
@if (row.group; as g) {
|
||||
<button type="button" class="highlight-group" [attr.aria-pressed]="highlightSelection.group === g.id" (click)="highlight('group', g.id)"><span class="legend-swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.label }}</button>
|
||||
}
|
||||
@for (c of row.items; track c.id) {
|
||||
<button type="button" [attr.aria-pressed]="highlightSelection.item === c.id" [disabled]="!!highlightSelection.group && c.group !== highlightSelection.group"
|
||||
[attr.aria-label]="c.short ? c.label : null" (click)="highlight('item', c.id)"><span class="legend-swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.short ?? c.label }}</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
} @else if (state.status === 'ready' && state.donutLegend?.length) {
|
||||
<div class="donut-static-legend" role="list" aria-label="Leyenda de la dona">
|
||||
@for (entry of state.donutLegend; track entry.label) {
|
||||
<span class="donut-static-legend__item" role="listitem">
|
||||
@@ -94,7 +110,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 ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ', ' + selected?.id + ', ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
|
||||
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend || state.highlight ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ', ' + selected?.id + ', ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
|
||||
</div>
|
||||
}
|
||||
<div class="figure-footer" [hidden]="state.status !== 'ready'">
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
:host(.methodology-expanded) .figure-card { grid-row: auto; }
|
||||
.figure-title { display: block; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); font-family: var(--issste-font-heading); overflow-wrap: anywhere; }
|
||||
.state { padding: 1.25rem; margin: 0; overflow-wrap: anywhere; }
|
||||
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; }
|
||||
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b7d251; --mat-sys-outline: #a1aabd; }
|
||||
.figure-id { padding: .25rem 1rem 0; margin: 0; font: var(--mat-sys-body-small); opacity: .8; overflow-wrap: anywhere; }
|
||||
@media (max-width: 550px) { .methodology-detail { padding: var(--issste-space-3); } }
|
||||
|
||||
@@ -113,3 +113,16 @@
|
||||
@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,6 +12,7 @@ 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 {
|
||||
@@ -22,6 +23,10 @@ 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;
|
||||
@@ -64,7 +69,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; }
|
||||
|| JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; this.highlightSelection = {}; }
|
||||
this.currentState = value;
|
||||
if (value.status === 'ready') {
|
||||
this.updateDonut();
|
||||
@@ -87,7 +92,8 @@ 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.donutLegend ? donutSimpleView(source) : source;
|
||||
: source && this.state.highlight ? highlightFigure(source, this.state.highlight, this.highlightSelection)
|
||||
: source && this.state.donutLegend && !this.state.ownLayout ? donutSimpleView(source) : source;
|
||||
}
|
||||
expandParent(parent: string) {
|
||||
if (this.state.status !== 'ready' || !this.state.hierarchy?.parents.includes(parent)
|
||||
@@ -109,9 +115,28 @@ 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 o Todos', () => {
|
||||
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters();
|
||||
control.changeMode('manual');
|
||||
control.select([]);
|
||||
expect(control.canApply).toBe(false);
|
||||
apply();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
@@ -228,18 +228,13 @@ describe('IndicadorFigurePanel', () => {
|
||||
expect(state?.applied?.selection.mode).toBe('todos');
|
||||
apply();
|
||||
const manual = figure();
|
||||
expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
||||
expect(manual.request.params.get('periodos')).toBe('2025-S2');
|
||||
control.select([]);
|
||||
expect(manual.cancelled).toBe(false);
|
||||
expect(control.canApply).toBe(false);
|
||||
apply();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
control.changeMode('todos');
|
||||
apply();
|
||||
expect(manual.cancelled).toBe(true);
|
||||
const all = figure();
|
||||
expect(all.request.params.has('periodos')).toBe(false);
|
||||
all.flush({ data: [], layout: {} });
|
||||
manual.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 };
|
||||
@@ -300,7 +295,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.changeMode('manual');
|
||||
const control = filters(); control.select([]);
|
||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
fixture.detectChanges();
|
||||
expect(page.result().figure?.data[0]['y']).toEqual([0, null]);
|
||||
@@ -308,9 +303,9 @@ describe('IndicadorFigurePanel', () => {
|
||||
expect(fixture.nativeElement.textContent).toContain('Filtro general aplicado: Todos con reporte');
|
||||
http.expectNone(r => r.url.includes('/figuras/'));
|
||||
});
|
||||
it.each([{ periodos: ['2025-S1'] }, { periodos: ['2025-S1', '2025-S2'] }])('404 de conjunto conserva borrador y reintenta la última aplicación', ({ periodos }) => {
|
||||
it.each([{ periodos: ['2025-S1'] }])('404 de un periodo conserva borrador y reintenta la última aplicación', ({ periodos }) => {
|
||||
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025';
|
||||
const control = filters(); control.select([]); control.year = '2025';
|
||||
for (const period of periodos) { control.unit = period.slice(-2); control.add(); }
|
||||
apply();
|
||||
const req = figure();
|
||||
@@ -320,7 +315,6 @@ 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();
|
||||
@@ -333,7 +327,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.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
apply(); figure().flush({ data: [{ y: [20] }], layout: {} });
|
||||
control.unit = 'S2'; control.add();
|
||||
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
|
||||
@@ -344,17 +338,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-S1', '2025-S2']);
|
||||
expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
});
|
||||
it('descarta respuestas obsoletas de aplicaciones sucesivas', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
apply(); const old = figure();
|
||||
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-S1,2025-S2');
|
||||
expect(current.request.params.get('periodos')).toBe('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]);
|
||||
@@ -362,7 +356,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.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
fixture.detectChanges();
|
||||
const result = page.result(), filterState = state, snapshot = JSON.stringify(filterState);
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance;
|
||||
|
||||
@@ -13,6 +13,9 @@ import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { DonutHierarchy, DonutSelection, donutHierarchy, donutLegend, donutPeriod } from './indicadores-donut-drilldown';
|
||||
import { 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';
|
||||
@@ -245,6 +248,26 @@ 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.
|
||||
@@ -265,6 +288,13 @@ 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 })
|
||||
|
||||
@@ -30,22 +30,8 @@
|
||||
</nav>
|
||||
}
|
||||
@if (model; as m) {
|
||||
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}. {{ reading }}</p>
|
||||
@if (status() === 'empty') { <p role="status">No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.</p> }
|
||||
@else {
|
||||
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
|
||||
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista general de la histopatología">Volver</button>
|
||||
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
||||
@for (g of m.grupos; track g.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="!selection?.categoria && selection?.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
<div class="keys" role="group" aria-label="Categorías del anillo exterior">
|
||||
@for (c of m.categorias; track c.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="figures">
|
||||
<section class="figure rates"><h3>Por categoría BI-RADS, {{ m.periodo }}</h3>
|
||||
@if (ratesFigure) {
|
||||
@@ -61,7 +47,21 @@
|
||||
} @else { <p role="status">{{ m.conResultado === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado de biopsia en el periodo.' }}</p> }
|
||||
</section>
|
||||
</div>
|
||||
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
|
||||
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista general de la histopatología">Volver</button>
|
||||
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
||||
@for (g of m.grupos; track g.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="!selection?.categoria && selection?.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
<div class="keys" role="group" aria-label="Categorías del anillo exterior">
|
||||
@for (c of m.categorias; track c.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}. {{ reading }}</p>
|
||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<div class="table-scroll" role="region" aria-label="Tabla de pacientes por categoría BI-RADS y resultado de biopsia" tabindex="0">
|
||||
|
||||
@@ -27,9 +27,14 @@ 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'] })));
|
||||
for (const request of http.match(r => r.url.endsWith('/periodos'))) request.flush({ id: request.request.url.split('/').at(-2), periodos: periods.map(periodo => ({ tipo: 'semestre', periodo })) });
|
||||
flushPeriodos(() => periods.map(periodo => ({ tipo: 'semestre', periodo })));
|
||||
fixture.detectChanges();
|
||||
}
|
||||
// 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.
|
||||
@@ -56,7 +61,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 tres destacados y muestra conteo, porcentaje y mediana', () => {
|
||||
it('TEA consulta sus cinco destacados y muestra conteo, porcentajes y mediana', () => {
|
||||
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); http.expectOne('/cacu/indicadores').flush([]);
|
||||
load('tea'); const initial = requests();
|
||||
expect(initial.map(r => r.request.url)).toEqual(['/tea/indicadores/' + KPI_BY_DOMAIN.tea[0].id + '/datos']);
|
||||
@@ -64,8 +69,10 @@ describe('KPI integración con autoridad global', () => {
|
||||
const req = requests();
|
||||
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]]);
|
||||
expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7], ['Disponible', '40.0'], ['Disponible', '40.0']]);
|
||||
expect(panels()[1].result().info).toContain('2 de 5 pacientes con nota médica con diagnóstico CIE-10 F84.0.');
|
||||
expect(panels()[3].result().info).toBe('2 de 5 pacientes con 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);
|
||||
@@ -80,7 +87,7 @@ describe('KPI integración con autoridad global', () => {
|
||||
it('borrador no consulta; aplicar equivalente tampoco; revisión distinta cancela las tres anteriores', () => {
|
||||
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.changeMode('manual'); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
editor.select([]); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(0);
|
||||
expect(panels().map(p => p.result().value)).toEqual([5, 7]);
|
||||
expect(single.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
||||
@@ -164,7 +171,7 @@ describe('KPI integración con autoridad global', () => {
|
||||
TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cacu');
|
||||
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges();
|
||||
http.expectOne('/cacu/indicadores').flush(KPI_BY_DOMAIN.cacu.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre'] })));
|
||||
http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [] })); fixture.detectChanges();
|
||||
flushPeriodos(() => []); fixture.detectChanges();
|
||||
expect(panels()).toHaveLength(2); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true);
|
||||
http.expectNone(r => r.url.endsWith('/datos'));
|
||||
});
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Component, inject, Input, OnChanges, signal } from '@angular/core';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, PlotlyFigure } from './indicadores.models';
|
||||
import { proportionFigure } from './measure-report';
|
||||
import { MeasureReportService } from './measure-report.service';
|
||||
|
||||
/** A proportion drawn from the WebApi's FHIR `MeasureReport`s: the data comes as the standard, the figure is ours. */
|
||||
@Component({
|
||||
selector: 'app-indicador-measure-report',
|
||||
imports: [MatProgressBarModule, PlotlyChart],
|
||||
template: `
|
||||
@if (status() === 'loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando indicador" /> }
|
||||
@if (status() === 'error') { <p role="alert">No se pudo cargar el indicador.</p> }
|
||||
@if (figure(); as figure) { <app-plotly-chart [figure]="figure" [label]="titulo" /> }
|
||||
`,
|
||||
})
|
||||
export class IndicadorMeasureReport implements OnChanges {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) indicador!: string;
|
||||
@Input({ required: true }) titulo!: string;
|
||||
@Input({ required: true }) periodos!: string[];
|
||||
@Input() estrato?: string;
|
||||
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
|
||||
readonly figure = signal<PlotlyFigure | undefined>(undefined);
|
||||
private readonly service = inject(MeasureReportService);
|
||||
|
||||
ngOnChanges() {
|
||||
this.status.set('loading');
|
||||
this.service.series(this.dominio, this.indicador, this.periodos).subscribe({
|
||||
next: series => { this.figure.set(proportionFigure(series, this.titulo, this.estrato)); this.status.set('ready'); },
|
||||
error: () => { this.figure.set(undefined); this.status.set('error'); },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -49,47 +49,33 @@
|
||||
</section>
|
||||
} @else {
|
||||
<section aria-label="Editor de filtros generales del proyecto">
|
||||
@if (state.tipo === 'mes') { <p class="filter-help">Para consultar meses debes elegir periodos explícitos. Todos con reporte utiliza semestres.</p> }
|
||||
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de tiempo del borrador ya no está publicado para este proyecto. Elige un intervalo de tiempo disponible.</p> }
|
||||
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> }
|
||||
<div class="fields">
|
||||
@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>
|
||||
}
|
||||
<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>
|
||||
</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 tiempo.</p> }
|
||||
} @else if (!options.length) { <p role="status">Sin reportes disponibles para este intervalo de análisis.</p> }
|
||||
@if (entry.draft.mode === 'explicit' && unavailableSelection.length) { <p role="status">La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.</p> }
|
||||
}
|
||||
@if (!availability && entry.draft.mode !== 'todos') {
|
||||
@if (!availability) {
|
||||
<p class="filter-help">Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.</p>
|
||||
<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>
|
||||
@@ -108,7 +94,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 al menos un periodo válido para aplicar.</p> }
|
||||
@if (!canApply) { <p role="status">Selecciona un periodo válido para aplicar.</p> }
|
||||
@if (!hasPending) { <p class="pending">Sin cambios pendientes.</p> }
|
||||
@if (hasPending) { <p class="pending" 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,6 +18,10 @@ 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('en modo compacto agregar otro periodo sustituye la selección anterior', () => {
|
||||
fixture.componentRef.setInput('compact', true); fixture.detectChanges();
|
||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
@@ -25,18 +29,15 @@ describe('UX-04 control asistido', () => {
|
||||
expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
expect(control.entry.added).toEqual(['2025-S1', '2025-S2']);
|
||||
});
|
||||
it('UX-06C: valores largos del trigger preservan Todos, selección explícita y borrador vacío', async () => {
|
||||
await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('.select-value')?.textContent).toContain('Todos con reporte');
|
||||
it('UX-06C: el trigger muestra el periodo explícito y el borrador vacío no se aplica', async () => {
|
||||
fixture.componentRef.setInput('state', {
|
||||
...control.state, editors: { ...control.state.editors, semestre: {
|
||||
added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] },
|
||||
added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S2'] },
|
||||
} },
|
||||
});
|
||||
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
||||
const values = Array.from(fixture.nativeElement.querySelectorAll('.select-value') as NodeListOf<HTMLElement>);
|
||||
expect(values.map(e => e.textContent)).toContain('2025-S1, 2025-S2');
|
||||
expect(values.map(e => e.textContent)).toContain('Elegir periodos');
|
||||
expect(values.map(e => e.textContent)).toContain('2025-S2');
|
||||
fixture.componentRef.setInput('state', {
|
||||
...control.state, editors: { ...control.state.editors, semestre: {
|
||||
added: ['2025-S1', '2025-S2'], draft: { mode: 'empty' },
|
||||
@@ -50,10 +51,11 @@ describe('UX-04 control asistido', () => {
|
||||
it('UX-04A: el selector vacío no reescribe el FormControl en cada detección', async () => {
|
||||
// Bound the pre-fix reproduction: do not wait for an unstable fixture forever.
|
||||
fixture.changeDetectorRef.detach();
|
||||
control.changeMode('manual');
|
||||
control.select([]);
|
||||
fixture.detectChanges();
|
||||
await Promise.resolve();
|
||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
||||
const select = periodSelect();
|
||||
expect(select.componentInstance.multiple).toBe(false);
|
||||
const model = select.injector.get(NgModel);
|
||||
const writes = vi.spyOn(model.control, 'setValue');
|
||||
const edits = vi.spyOn(control.edited, 'emit');
|
||||
@@ -61,16 +63,16 @@ describe('UX-04 control asistido', () => {
|
||||
fixture.detectChanges();
|
||||
await Promise.resolve();
|
||||
}
|
||||
expect(model.control.value).toEqual([]);
|
||||
expect(model.control.value).toBeNull();
|
||||
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 selección múltiple', async () => {
|
||||
it('UX-04A: meses vacíos se estabilizan al abrir y cerrar el selector', async () => {
|
||||
control.changeTipo('mes');
|
||||
control.year = '2025'; control.unit = '01'; control.add(); control.select([]);
|
||||
fixture.detectChanges(); await fixture.whenStable();
|
||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
||||
const select = periodSelect();
|
||||
const model = select.injector.get(NgModel);
|
||||
const writes = vi.spyOn(model.control, 'setValue');
|
||||
for (let i = 0; i < 3; i++) {
|
||||
@@ -85,7 +87,7 @@ describe('UX-04 control asistido', () => {
|
||||
expect(control.canApply).toBe(false);
|
||||
});
|
||||
it('normaliza el año y rechaza agregar duplicados', () => {
|
||||
control.changeMode('manual');
|
||||
control.select([]);
|
||||
control.year = '1'; control.unit = 'S1'; control.add();
|
||||
expect(control.selectedPeriods).toEqual(['0001-S1']);
|
||||
control.add();
|
||||
@@ -93,7 +95,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.changeMode('manual'); control.year = year; control.unit = unit; control.add();
|
||||
control.select([]); control.year = year; control.unit = unit; control.add();
|
||||
expect(control.error).toContain('unidad válida'); expect(control.canApply).toBe(false);
|
||||
});
|
||||
it.each(['00', '13', 'S1'])('rechaza unidad mensual %s', unit => {
|
||||
@@ -101,21 +103,22 @@ describe('UX-04 control asistido', () => {
|
||||
expect(control.entry.added).toEqual([]); expect(control.canApply).toBe(false);
|
||||
});
|
||||
it('conserva borradores independientes sin convertir periodos', () => {
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.changeTipo('mes'); control.year = '2026'; control.unit = '12'; control.add();
|
||||
control.changeTipo('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('deselecciona sin eliminar opciones y elimina sin botones dentro de opciones', () => {
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
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();
|
||||
control.unit = 'S2'; control.add();
|
||||
control.select(['2025-S2']);
|
||||
expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
control.select(['2025-S1', '2025-S2']); expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
expect(control.entry.added).toEqual(['2025-S1', '2025-S2']);
|
||||
control.remove('2025-S1'); expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
fixture.detectChanges();
|
||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
||||
expect(select).toBeTruthy();
|
||||
const select = periodSelect();
|
||||
expect(select.componentInstance.multiple).toBe(false);
|
||||
expect(select.nativeElement.querySelector('button')).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).toContain('Eliminar 2025-S2');
|
||||
fixture.nativeElement.querySelector('.remove button').click();
|
||||
@@ -126,7 +129,7 @@ describe('UX-04 control asistido', () => {
|
||||
it('emite edición y aplicación por separado y explica la disponibilidad desconocida', () => {
|
||||
const edited = vi.spyOn(control.edited, 'emit');
|
||||
const apply = vi.spyOn(control.apply, 'emit');
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
expect(edited).toHaveBeenCalledTimes(2); expect(apply).not.toHaveBeenCalled();
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar');
|
||||
@@ -135,11 +138,25 @@ describe('UX-04 control asistido', () => {
|
||||
fixture.nativeElement.querySelector('button[mat-flat-button]').click();
|
||||
expect(apply).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
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');
|
||||
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']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -32,7 +32,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 multiple-select value stable so an unchanged draft can settle.
|
||||
// Keep the empty selection stable so an unchanged draft can settle.
|
||||
private readonly emptyPeriods: string[] = [];
|
||||
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; }
|
||||
@@ -45,21 +45,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();
|
||||
}
|
||||
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();
|
||||
}
|
||||
// Only one period can be chosen: cards and figures never combine periods.
|
||||
select(values: string[]) {
|
||||
const unique = [...new Set(this.compact ? values.slice(-1) : values)];
|
||||
if (unique.length > 1) return;
|
||||
if (unique.some(p => !this.options.includes(p) || parsePeriodos(p, this.state.tipo)?.[0] !== p)) return;
|
||||
this.entry.draft = unique.length ? { mode: 'explicit', periodos: unique as [string, ...string[]] } : { mode: 'empty' };
|
||||
this.edited.emit();
|
||||
@@ -73,13 +73,11 @@ 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([...selected, period]);
|
||||
this.select([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();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
|
||||
import { CeldaMapa, ComparacionAnalisis, DistribucionAnalisis, MapaAnalisis, TendenciaAnalisis } from './indicadores-analisis.service';
|
||||
|
||||
// The figures of the descriptive analysis. They draw what the answer publishes and nothing else: a suppressed or missing
|
||||
// value is left out of the drawing (a gap, never a zero) and named in the table beside it.
|
||||
const miles = (v: number) => v.toLocaleString('es-MX');
|
||||
const pct = (v: number) => v.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 }) + ' %';
|
||||
const base = (tema: Tema, alto: number, margen: Record<string, number>) => {
|
||||
const t = c2Theme(tema);
|
||||
return { autosize: true, height: alto, paper_bgcolor: t.background, plot_bgcolor: t.background, font: { color: t.text }, margin: margen, showlegend: false };
|
||||
};
|
||||
const config = { displayModeBar: false };
|
||||
|
||||
/** Share of the selection by category, with the Wilson interval of each published share as a horizontal bar. */
|
||||
export function distribucionFigura(d: DistribucionAnalisis, tema: Tema): PlotlyFigure {
|
||||
const t = c2Theme(tema);
|
||||
const items = d.items.filter(i => !i.suprimido && (i.n ?? 0) > 0 && i.porcentaje !== null);
|
||||
return {
|
||||
data: [{
|
||||
type: 'bar', orientation: 'h', y: items.map(i => i.etiqueta), x: items.map(i => i.porcentaje), customdata: items.map(i => i.codigo),
|
||||
marker: { color: C2_PALETTE.series[0] },
|
||||
error_x: { type: 'data', symmetric: false, array: items.map(i => i.ic_alto! - i.porcentaje!), arrayminus: items.map(i => i.porcentaje! - i.ic_bajo!), color: t.text },
|
||||
text: items.map(i => `${miles(i.n!)} (${pct(i.porcentaje!)})`), textposition: 'inside', insidetextanchor: 'start', textfont: { color: '#081839' }, cliponaxis: false,
|
||||
hovertemplate: items.map(i => `<b>${i.etiqueta}</b><br>${miles(i.n!)} pacientes<br>${pct(i.porcentaje!)} (IC 95 %: ${pct(i.ic_bajo!)} a ${pct(i.ic_alto!)})<extra></extra>`),
|
||||
}],
|
||||
layout: { ...base(tema, Math.max(220, 60 + 44 * items.length), { t: 24, l: 150, r: 90, b: 52 }),
|
||||
xaxis: { title: { text: 'Porcentaje de la selección' }, range: [0, 100], ticksuffix: ' %', gridcolor: t.grid, fixedrange: true },
|
||||
yaxis: { autorange: 'reversed', automargin: true, fixedrange: true } },
|
||||
config,
|
||||
};
|
||||
}
|
||||
|
||||
/** The share of cases per group as a point with its interval: groups that aren't published have no point. */
|
||||
export function comparacionFigura(c: ComparacionAnalisis, tema: Tema, medida: string): PlotlyFigure {
|
||||
const t = c2Theme(tema);
|
||||
const grupos = c.grupos.filter(g => g.estado === 'disponible');
|
||||
return {
|
||||
data: [{
|
||||
type: 'scatter', mode: 'markers', y: grupos.map(g => g.etiqueta), x: grupos.map(g => g.valor), customdata: grupos.map(g => g.codigo),
|
||||
marker: { color: C2_PALETTE.series[1], size: 11 },
|
||||
error_x: { type: 'data', symmetric: false, array: grupos.map(g => g.ic_alto! - g.valor!), arrayminus: grupos.map(g => g.valor! - g.ic_bajo!), color: t.text, thickness: 2, width: 6 },
|
||||
hovertemplate: grupos.map(g => `<b>${g.etiqueta}</b><br>${g.casos} de ${g.total} pacientes con resultado<br>${pct(g.valor!)} (IC 95 %: ${pct(g.ic_bajo!)} a ${pct(g.ic_alto!)})<extra></extra>`),
|
||||
}],
|
||||
layout: { ...base(tema, Math.max(220, 80 + 46 * grupos.length), { t: 24, l: 150, r: 28, b: 56 }),
|
||||
xaxis: { title: { text: `${medida} entre pacientes con resultado de biopsia` }, range: [0, 100], ticksuffix: ' %', gridcolor: t.grid, fixedrange: true },
|
||||
yaxis: { autorange: 'reversed', type: 'category', automargin: true, fixedrange: true } },
|
||||
config,
|
||||
};
|
||||
}
|
||||
|
||||
const textoCelda = (c: CeldaMapa, medida: string) => c.suprimido ? 'No publicado'
|
||||
: medida === 'pacientes' ? `${miles(c.n!)} pacientes` : c.resultado.estado === 'disponible' ? `${pct(c.resultado.valor!)}<br>${c.resultado.casos} de ${c.resultado.total}` : c.resultado.estado === 'suprimido' ? 'No publicado' : 'Sin pacientes con resultado';
|
||||
|
||||
/** BI-RADS by age group: the number of patients or the share of cases in each cell; hidden cells are blank. */
|
||||
export function mapaFigura(m: MapaAnalisis, tema: Tema, medida: 'pacientes' | 'resultado'): PlotlyFigure {
|
||||
const t = c2Theme(tema);
|
||||
const celdas = new Map(m.celdas.map(c => [c.fila + '\u0000' + c.columna, c]));
|
||||
const valor = (c: CeldaMapa | undefined) => !c || c.suprimido ? null : medida === 'pacientes' ? c.n : c.resultado.estado === 'disponible' ? c.resultado.valor : null;
|
||||
const z = m.filas.categorias.map(f => m.columnas.categorias.map(c => valor(celdas.get(f.codigo + '\u0000' + c.codigo))));
|
||||
return {
|
||||
data: [{
|
||||
type: 'heatmap', x: m.columnas.categorias.map(c => c.etiqueta), y: m.filas.categorias.map(f => f.etiqueta), z,
|
||||
customdata: m.filas.categorias.map(f => m.columnas.categorias.map(c => [f.codigo, c.codigo])),
|
||||
text: m.filas.categorias.map(f => m.columnas.categorias.map(c => textoCelda(celdas.get(f.codigo + '\u0000' + c.codigo)!, medida === 'pacientes' ? 'pacientes' : 'resultado'))),
|
||||
hovertemplate: '%{y}, %{x}<br>%{text}<extra></extra>', hoverongaps: false, xgap: 2, ygap: 2,
|
||||
colorscale: [[0, '#E4EEC0'], [1, '#6A8000']], zmin: 0, zmax: medida === 'resultado' ? 100 : undefined,
|
||||
colorbar: { title: { text: medida === 'resultado' ? '% de casos' : 'Pacientes' } },
|
||||
}],
|
||||
layout: { ...base(tema, Math.max(280, 90 + 40 * m.filas.categorias.length), { t: 24, l: 130, r: 28, b: 60 }),
|
||||
xaxis: { automargin: true, fixedrange: true, type: 'category' }, yaxis: { autorange: 'reversed', automargin: true, fixedrange: true, type: 'category' },
|
||||
plot_bgcolor: t.grid },
|
||||
config,
|
||||
};
|
||||
}
|
||||
|
||||
export interface FigurasTendencia { actividad: PlotlyFigure; proporcion: PlotlyFigure; }
|
||||
|
||||
/** Reports per period (bars; a hidden total is a gap) and the share of malignant results with its interval. */
|
||||
export function tendenciaFiguras(r: TendenciaAnalisis, tema: Tema, medida: string): FigurasTendencia {
|
||||
const t = c2Theme(tema);
|
||||
const x = r.periodos.map(p => p.periodo + (p.incompleto ? ' (en curso)' : ''));
|
||||
const disponibles = r.periodos.map((p, i) => ({ p, x: x[i] })).filter(({ p }) => p.maligno.estado === 'disponible');
|
||||
return {
|
||||
actividad: {
|
||||
data: [
|
||||
{ type: 'bar', name: 'Reportes de mastografía', x, y: r.periodos.map(p => p.reportes_mastografia.total), marker: { color: C2_PALETTE.series[2] },
|
||||
hovertemplate: '%{x}<br>%{y} reportes de mastografía<extra></extra>' },
|
||||
{ type: 'bar', name: 'Reportes de biopsia', x, y: r.periodos.map(p => p.reportes_biopsia.total), marker: { color: C2_PALETTE.series[3] },
|
||||
hovertemplate: '%{x}<br>%{y} reportes de biopsia<extra></extra>' },
|
||||
],
|
||||
layout: { ...base(tema, 340, { t: 24, l: 56, r: 16, b: 80 }), showlegend: true, legend: { orientation: 'h', y: -0.28 }, barmode: 'group',
|
||||
xaxis: { type: 'category', automargin: true, fixedrange: true }, yaxis: { title: { text: 'Reportes' }, gridcolor: t.grid, rangemode: 'tozero', fixedrange: true } },
|
||||
config,
|
||||
},
|
||||
proporcion: {
|
||||
data: [{
|
||||
type: 'scatter', mode: 'lines+markers', x: disponibles.map(d => d.x), y: disponibles.map(d => d.p.maligno.valor), connectgaps: false,
|
||||
line: { color: C2_PALETTE.series[1] }, marker: { color: C2_PALETTE.series[1], size: 9 },
|
||||
error_y: { type: 'data', symmetric: false, array: disponibles.map(d => d.p.maligno.ic_alto! - d.p.maligno.valor!), arrayminus: disponibles.map(d => d.p.maligno.valor! - d.p.maligno.ic_bajo!), color: t.text },
|
||||
hovertemplate: disponibles.map(d => `${d.x}<br>${d.p.maligno.casos} de ${d.p.maligno.total} reportes de biopsia con resultado<br>${pct(d.p.maligno.valor!)} (IC 95 %: ${pct(d.p.maligno.ic_bajo!)} a ${pct(d.p.maligno.ic_alto!)})<extra></extra>`),
|
||||
}],
|
||||
layout: { ...base(tema, 340, { t: 24, l: 64, r: 16, b: 64 }),
|
||||
xaxis: { type: 'category', categoryorder: 'array', categoryarray: x, automargin: true, fixedrange: true },
|
||||
yaxis: { title: { text: medida }, range: [0, 100], ticksuffix: ' %', gridcolor: t.grid, fixedrange: true } },
|
||||
config,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
// What this module covers: CaMa's descriptive analysis in the Analysis tab: the answers' validation, the cards, the
|
||||
// figures built from them, the sections the component draws, the way from a figure to Seguimiento and the states
|
||||
// without data, suppressed or not published.
|
||||
// Fixtures (`fixtures/cama_analisis_real_*.json`): answers of the WebApi's `/cama/analisis` endpoints over the local
|
||||
// installation's synthetic CaMa data at 2026-11-16, whole cohort: catalog, indicators (90 days), distribution by BI-RADS, by
|
||||
// age group and by biopsy result, comparison by age group, map, trend by semester and by month, and the 403 body.
|
||||
import { TestBed, ComponentFixture } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { IndicadoresAnalisisDescriptivo, detalleTarjeta, valorTarjeta } from './indicadores-analisis-descriptivo';
|
||||
import {
|
||||
catalogoDescriptivo, comparacionDescriptiva, distribucionDescriptiva, mapaDescriptivo, resumenDescriptivo, tendenciaDescriptiva,
|
||||
} from './indicadores-analisis.service';
|
||||
import { comparacionFigura, distribucionFigura, mapaFigura, tendenciaFiguras } from './indicadores-analisis-descriptivo-figuras';
|
||||
import catalogoData from './fixtures/cama_analisis_real_catalogo.json';
|
||||
import resumenData from './fixtures/cama_analisis_real_resumen90.json';
|
||||
import distBirads from './fixtures/cama_analisis_real_dist_birads.json';
|
||||
import distEdad from './fixtures/cama_analisis_real_dist_edad.json';
|
||||
import distBiopsia from './fixtures/cama_analisis_real_dist_biopsia.json';
|
||||
import compBirads from './fixtures/cama_analisis_real_comp_birads.json';
|
||||
import compEdad from './fixtures/cama_analisis_real_comp_edad.json';
|
||||
import mapaData from './fixtures/cama_analisis_real_mapa.json';
|
||||
import tendSem from './fixtures/cama_analisis_real_tend_sem.json';
|
||||
import tendMes from './fixtures/cama_analisis_real_tend_mes.json';
|
||||
import pequenoData from './fixtures/cama_analisis_real_pequeno.json';
|
||||
|
||||
const copia = (v: unknown) => structuredClone(v) as unknown as Record<string, any>;
|
||||
const CORTE = '2026-11-16';
|
||||
|
||||
describe('Respuestas del análisis descriptivo', () => {
|
||||
it('las respuestas reales cumplen su contrato y nombran la cohorte que describen', () => {
|
||||
// Pins down: every answer is accepted as the server sends it, names the cohort, scenario, revision and cut-off, and
|
||||
// carries no `simulado` field. Fails if the contract drifts from what the client validates.
|
||||
const todas = [catalogoDescriptivo(copia(catalogoData)), resumenDescriptivo(copia(resumenData)), distribucionDescriptiva(copia(distBirads)),
|
||||
comparacionDescriptiva(copia(compEdad)), mapaDescriptivo(copia(mapaData))];
|
||||
for (const r of todas) { expect(r.cohorte).toBe('cama_birads_v1'); expect(r.revision).toMatch(/^[0-9a-f]{64}$/); expect(r.corte).toBe(CORTE); expect('simulado' in r).toBe(false); }
|
||||
expect(new Set(todas.map(r => r.revision)).size).toBe(1);
|
||||
// The trend is activity, not the cohort: it names its cut-off, unit, population and biopsy scope, and no cohort, filters or test.
|
||||
for (const t of [tendenciaDescriptiva(copia(tendSem)), tendenciaDescriptiva(copia(tendMes))]) {
|
||||
expect(t.corte).toBe(CORTE); expect(t.unidad).toBe('reportes'); expect(t.poblacion).toBeTruthy(); expect(t.alcance_biopsias).toBeTruthy();
|
||||
expect(Object.keys(t)).not.toEqual(expect.arrayContaining(['cohorte']));
|
||||
for (const k of ['cohorte', 'revision', 'ventana', 'filtros', 'prueba', 'simulado']) expect(k in t).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('una respuesta con un conteo publicado y suprimido a la vez, o sin cohorte, se rechaza', () => {
|
||||
// Pins down: a suppressed item can't carry a count and a published one must; an answer without cohort context isn't read.
|
||||
// Fails if the client draws figures from an answer that contradicts itself.
|
||||
const d = copia(distBirads); d['items'][0].suprimido = true;
|
||||
expect(() => distribucionDescriptiva(d)).toThrow();
|
||||
const sin = copia(distBirads); delete sin['revision'];
|
||||
expect(() => distribucionDescriptiva(sin)).toThrow();
|
||||
const r = copia(resumenData); r['indicadores'][1].estado = 'suprimido';
|
||||
expect(() => resumenDescriptivo(r)).toThrow();
|
||||
});
|
||||
|
||||
it('las tarjetas escriben el valor, su intervalo y su denominador, o dicen por qué no hay cifra', () => {
|
||||
// Pins down: a proportion reads «68.9»-style with its Wilson interval and `k de n pacientes`; a median reads its quartiles;
|
||||
// a suppressed card has no value and says why. Fails if a card shows a number the answer doesn't publish.
|
||||
const r = resumenDescriptivo(copia(resumenData));
|
||||
const t = Object.fromEntries(r.indicadores.map(i => [i.clave, i]));
|
||||
expect(valorTarjeta(t['cohorte'])).toBe('61');
|
||||
expect(valorTarjeta(t['con_biopsia'])).toBe('68.9');
|
||||
expect(detalleTarjeta(t['con_biopsia'])).toContain('IC 95 %: 56.4 a 79.1 %. 42 de 61 pacientes.');
|
||||
expect(detalleTarjeta(t['dias_a_biopsia'])).toContain('Q1 a Q3: 19.3 a 30.8 días. 42 pacientes.');
|
||||
const oculta = { ...t['con_biopsia'], estado: 'suprimido' as const, valor: null, ic_bajo: null, ic_alto: null };
|
||||
expect(valorTarjeta(oculta)).toBeNull();
|
||||
expect(detalleTarjeta(oculta)).toContain('Muy pocos pacientes');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Figuras del análisis descriptivo', () => {
|
||||
it('la distribución dibuja solo las categorías publicadas, con su intervalo, y deja las suprimidas fuera', () => {
|
||||
// Pins down: BI-RADS 5 and 6 are suppressed in the real answer, so only BI-RADS 4 is drawn, at its share with its Wilson
|
||||
// interval as asymmetric error bars; a hidden category is a gap, not a zero bar. Fails if a suppressed group is drawn.
|
||||
const d = distribucionDescriptiva(copia(distBirads));
|
||||
const [traza] = distribucionFigura(d, 'claro').data as Record<string, any>[];
|
||||
expect(traza['y']).toEqual(['BI-RADS 4']);
|
||||
expect(traza['x']).toEqual([54.1]);
|
||||
expect(traza['error_x']['array'][0] + traza['x'][0]).toBeCloseTo(d.items[0].ic_alto!, 5);
|
||||
});
|
||||
|
||||
it('la comparación dibuja un punto por grupo publicado con su intervalo', () => {
|
||||
// Pins down: by age group three groups have enough patients with a result; each point is its share and the interval is
|
||||
// asymmetric. Fails if a group without data or a hidden one gets a point.
|
||||
const c = comparacionDescriptiva(copia(compEdad));
|
||||
const [traza] = comparacionFigura(c, 'claro', 'Carcinoma invasor').data as Record<string, any>[];
|
||||
expect(traza['y']).toEqual(['40 a 49 años', '50 a 59 años', '60 a 69 años'].map(e => expect.stringContaining(e.split(' ')[0])));
|
||||
expect(traza['x']).toHaveLength(3);
|
||||
expect(c.grupos.filter(g => g.estado === 'disponible').map(g => g.casos)).toEqual([5, 6, 8]);
|
||||
});
|
||||
|
||||
it('el mapa deja en blanco las celdas que no se publican y conserva la posición de cada celda publicada', () => {
|
||||
// Pins down: a hidden cell is `null` in the matrix (blank), never zero; published cells keep their row and column and carry
|
||||
// the key that opens their patients. Fails if suppression turns into a zero or shifts a cell.
|
||||
const m = mapaDescriptivo(copia(mapaData));
|
||||
const [traza] = mapaFigura(m, 'claro', 'pacientes').data as Record<string, any>[];
|
||||
const iFila = m.filas.categorias.findIndex(f => f.codigo === 'BIRADS_4'), iCol = m.columnas.categorias.findIndex(c => c.codigo === '50-59');
|
||||
expect(traza['z'][iFila][iCol]).toBeNull();
|
||||
const publicada = m.celdas.find(c => !c.suprimido && (c.n ?? 0) > 0)!;
|
||||
const f = m.filas.categorias.findIndex(x => x.codigo === publicada.fila), c = m.columnas.categorias.findIndex(x => x.codigo === publicada.columna);
|
||||
expect(traza['z'][f][c]).toBe(publicada.n);
|
||||
expect(traza['customdata'][f][c]).toEqual([publicada.fila, publicada.columna]);
|
||||
});
|
||||
|
||||
it('la tendencia dibuja los periodos y el porcentaje solo donde se publica, y marca el periodo en curso', () => {
|
||||
// Pins down: by semester four periods carry a share with an interval; by month the months with fewer than five biopsies
|
||||
// have no point; the period the cut-off cuts is labelled. Fails if an unpublished period gets a point.
|
||||
const sem = tendenciaFiguras(tendenciaDescriptiva(copia(tendSem)), 'claro', 'x');
|
||||
expect((sem.proporcion.data[0] as Record<string, any>)['x']).toHaveLength(4);
|
||||
const mes = tendenciaDescriptiva(copia(tendMes));
|
||||
const figuras = tendenciaFiguras(mes, 'claro', 'x');
|
||||
const publicados = mes.periodos.filter(p => p.maligno.estado === 'disponible').length;
|
||||
expect((figuras.proporcion.data[0] as Record<string, any>)['x']).toHaveLength(publicados);
|
||||
expect((figuras.actividad.data[0] as Record<string, any>)['x'].at(-1)).toContain('(en curso)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Análisis descriptivo de CaMa (componente)', () => {
|
||||
let fixture: ComponentFixture<IndicadoresAnalisisDescriptivo>, http: HttpTestingController;
|
||||
let emitidas: { seleccion: any; origen: HTMLElement | null }[];
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresAnalisisDescriptivo], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
fixture = TestBed.createComponent(IndicadoresAnalisisDescriptivo); http = TestBed.inject(HttpTestingController);
|
||||
emitidas = []; fixture.componentInstance.verPacientes.subscribe(e => emitidas.push(e));
|
||||
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('corte', CORTE);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
const pide = (ruta: string) => http.expectOne(r => r.url === `/cama/analisis${ruta}`);
|
||||
async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); }
|
||||
async function abrir() {
|
||||
fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
||||
pide('').flush(catalogoData); pide('/resumen').flush(resumenData); pide('/distribucion').flush(distBirads);
|
||||
pide('/comparacion').flush(compBirads); pide('/mapa').flush(mapaData); pide('/tendencia').flush(tendSem);
|
||||
await asentar();
|
||||
}
|
||||
const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement;
|
||||
|
||||
it('no pide nada hasta que la pestaña se abre y entonces pide sus seis respuestas con el corte y la selección', async () => {
|
||||
// Pins down: nothing before the tab is open; then the catalog, indicators (90-day horizon), distribution by BI-RADS,
|
||||
// comparison by age group, map and semester trend, all at the cut-off and the whole cohort. Fails if a section is
|
||||
// asked early or without the selection.
|
||||
http.expectNone(() => true);
|
||||
fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
||||
const parametros = (ruta: string) => { const r = pide(ruta); const p = Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)])); r.flush({}, { status: 404, statusText: 'x' }); return p; };
|
||||
expect(parametros('')).toEqual({ corte: CORTE, meses: '0' });
|
||||
expect(parametros('/resumen')).toEqual({ corte: CORTE, meses: '0', horizonte: '90' });
|
||||
expect(parametros('/distribucion')).toEqual({ corte: CORTE, meses: '0', por: 'birads' });
|
||||
expect(parametros('/comparacion')).toEqual({ corte: CORTE, meses: '0', por: 'grupo_edad', medida: 'maligno' });
|
||||
expect(parametros('/mapa')).toEqual({ corte: CORTE, meses: '0', filas: 'birads', columnas: 'grupo_edad', medida: 'maligno' });
|
||||
expect(parametros('/tendencia')).toEqual({ corte: CORTE, tipo: 'semestre', periodos: '6' });
|
||||
});
|
||||
|
||||
it('dibuja las tarjetas, las tablas y la lista de lo que no se puede calcular, con las mismas 61 pacientes en todas partes', async () => {
|
||||
// Pins down: the cohort card, the distribution's total and its caption agree on 61 patients; the unavailable analyses
|
||||
// are listed with their reasons; nothing says the data is simulated, provisional or a test. Fails if two parts of the tab
|
||||
// count different patients or a banner of that kind appears.
|
||||
await abrir();
|
||||
const texto = root().textContent!;
|
||||
expect(root().querySelectorAll('app-indicador-kpi-card')).toHaveLength(7);
|
||||
expect(root().querySelector('app-indicador-kpi-card .value')?.textContent).toContain('61');
|
||||
expect(root().querySelector('#desc-dist ~ div table caption, section[aria-labelledby="desc-dist"] caption')?.textContent).toContain('61 pacientes');
|
||||
expect(texto).toContain('No disponible con las fuentes actuales');
|
||||
for (const titulo of ['Supervivencia', 'Recaída', 'Adherencia al tratamiento']) expect(texto).toContain(titulo);
|
||||
expect(texto).toContain('No hay estado vital');
|
||||
expect(texto).not.toMatch(/simulad|demostraci|provisional|prueba de concepto|modo de desarrollo|datos de prueba/i);
|
||||
});
|
||||
|
||||
it('una categoría suprimida dice «No publicado» sin botón y una publicada abre sus pacientes con la selección completa', async () => {
|
||||
// Pins down: BI-RADS 5 (suppressed) has no «Ver pacientes» button; BI-RADS 4 has one and its click emits the filter, the
|
||||
// label, the cut-off, the patients counted and the cohort context to quote back. Fails if a hidden group can be opened or
|
||||
// the list would open another selection.
|
||||
await abrir();
|
||||
const fila = (codigo: string) => root().querySelector<HTMLElement>(`tr[data-codigo="${codigo}"]`)!;
|
||||
expect(fila('BIRADS_5').textContent).toContain('No publicado'); expect(fila('BIRADS_5').querySelector('button')).toBeNull();
|
||||
fila('BIRADS_4').querySelector<HTMLButtonElement>('button.ver')!.click();
|
||||
expect(emitidas).toHaveLength(1);
|
||||
expect(emitidas[0].seleccion).toMatchObject({ filtros: { birads: 'BIRADS_4' }, etiqueta: 'BI-RADS 4', corte: CORTE, esperados: 33,
|
||||
contexto: { cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: (distBirads as any).revision } });
|
||||
});
|
||||
|
||||
it('cambiar la dimensión de la distribución vuelve a pedir solo esa sección', async () => {
|
||||
// Pins down: choosing «Grupo de edad» asks `distribucion?por=grupo_edad` and nothing else, and its answer replaces the
|
||||
// table. Fails if a choice in one section reloads the rest.
|
||||
await abrir();
|
||||
boton('Grupo de edad').click(); fixture.detectChanges();
|
||||
const r = pide('/distribucion'); expect(r.request.params.get('por')).toBe('grupo_edad'); r.flush(distEdad); await asentar();
|
||||
expect([...root().querySelectorAll('tr[data-codigo]')].map(tr => tr.getAttribute('data-codigo'))).toEqual(['<40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO']);
|
||||
http.expectNone(() => true);
|
||||
boton('Resultado de la biopsia').click(); fixture.detectChanges(); pide('/distribucion').flush(distBiopsia); await asentar();
|
||||
expect(root().querySelector('tr[data-codigo="SIN_BIOPSIA"]')?.textContent).toContain('19');
|
||||
});
|
||||
|
||||
it('un grupo sin suficientes pacientes dice por qué, un 503 lo dice y un 404 queda pendiente, sin pantalla vacía', async () => {
|
||||
// Pins down: a 403 on the distribution shows the fixed message; the indicators' 503 says the cohort isn't available and
|
||||
// offers a retry; a 404 is «pendiente», not an error. Fails if a failure leaves the section empty or shows the body.
|
||||
fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
||||
pide('').flush(catalogoData);
|
||||
pide('/resumen').flush({}, { status: 503, statusText: 'x' });
|
||||
pide('/distribucion').flush(pequenoData, { status: 403, statusText: 'x' });
|
||||
pide('/comparacion').flush({}, { status: 404, statusText: 'x' });
|
||||
pide('/mapa').flush(mapaData); pide('/tendencia').flush(tendSem);
|
||||
await asentar();
|
||||
expect(root().textContent).toContain('La cohorte no está disponible en este momento.');
|
||||
expect(root().querySelector('#desc-dist')!.parentElement!.querySelector('[role=alert]')?.textContent).toContain('muy pocos pacientes');
|
||||
expect(root().querySelector('#desc-dist')!.parentElement!.textContent).not.toContain('menos de 5 pacientes: su lista');
|
||||
expect(root().querySelector('[aria-labelledby="desc-comp"] table')).toBeNull();
|
||||
});
|
||||
|
||||
it('la comparación sin prueba válida lo dice; con prueba válida da el estadístico y su p', async () => {
|
||||
// Pins down: by BI-RADS no table supports the test and the page says «No disponible» with the reason; by age group it
|
||||
// gives chi-square, degrees of freedom and p. Fails if a p-value appears on a table the server called invalid.
|
||||
await abrir();
|
||||
expect(root().querySelector('[aria-labelledby="desc-comp"] .nota[role=status]')?.textContent).toContain('No disponible. Hacen falta al menos dos grupos');
|
||||
const c = fixture.componentInstance;
|
||||
c.cambiarComparacion('grupo_edad', 'invasor'); fixture.detectChanges();
|
||||
pide('/comparacion').flush(compEdad); await asentar();
|
||||
expect(root().querySelector('[aria-labelledby="desc-comp"] .nota[role=status]')?.textContent).toMatch(/χ² 0.089, 2 gl, p 0.957/);
|
||||
});
|
||||
|
||||
it('la tendencia marca el periodo en curso y deja sin cifra el porcentaje que no se publica', async () => {
|
||||
// Pins down: by month the table says «No publicado» where a month has too few biopsies and labels the current month.
|
||||
// Fails if a hidden share is written as a number or the partial period looks whole.
|
||||
await abrir();
|
||||
fixture.componentInstance.cambiarTendencia('mes', 12); fixture.detectChanges(); pide('/tendencia').flush(tendMes); await asentar();
|
||||
const tabla = root().querySelector('[aria-labelledby="desc-tend"] table')!;
|
||||
expect(tabla.textContent).toContain('(en curso)');
|
||||
expect(tabla.textContent).toContain('No publicado');
|
||||
expect(new Set([...tabla.querySelectorAll('tbody tr')].map(tr => tr.children[3].textContent!.trim())).has('No publicado')).toBe(true);
|
||||
});
|
||||
|
||||
it('la actividad de reportes conserva su definición: solo cambia con el corte, nunca con la ventana ni los filtros', async () => {
|
||||
// Pins down: «Aplicar» with another window and filters reloads the cohort sections with them but not the trend, and a new
|
||||
// cut-off reloads the trend with only that cut-off, the period type and the count. Fails if the trend takes a filter or
|
||||
// window it doesn't apply, or isn't refreshed when the cut-off changes.
|
||||
await abrir();
|
||||
const c = fixture.componentInstance;
|
||||
c.meses = 3; c.filtros = { grupo_edad: '50-59' }; c.aplicar(); fixture.detectChanges();
|
||||
const d = pide('/distribucion'); expect(d.request.params.get('meses')).toBe('3'); expect(d.request.params.get('grupo_edad')).toBe('50-59');
|
||||
d.flush({}, { status: 404, statusText: 'x' });
|
||||
for (const ruta of ['', '/resumen', '/comparacion', '/mapa']) pide(ruta).flush({}, { status: 404, statusText: 'x' });
|
||||
http.expectNone(r => r.url.endsWith('/tendencia'));
|
||||
fixture.componentRef.setInput('corte', '2026-10-31'); await asentar();
|
||||
const t = http.expectOne(r => r.url === '/cama/analisis/tendencia');
|
||||
expect(Object.fromEntries(t.request.params.keys().map(k => [k, t.request.params.get(k)]))).toEqual({ corte: '2026-10-31', tipo: 'semestre', periodos: '6' });
|
||||
t.flush({}, { status: 404, statusText: 'x' });
|
||||
for (const ruta of ['', '/resumen', '/distribucion', '/comparacion', '/mapa']) pide(ruta).flush({}, { status: 404, statusText: 'x' });
|
||||
});
|
||||
|
||||
it('la actividad de reportes se presenta con su población, la unidad y el alcance de las biopsias, y sin prueba estadística', async () => {
|
||||
// Pins down: the section names what it counts (reports, not patients), over whom, the scope of the biopsies and that the
|
||||
// cohort selection doesn't apply; it has no chi-square paragraph. Fails if the text attributes the filters or implies a test.
|
||||
await abrir();
|
||||
const seccion = root().querySelector('[aria-labelledby="desc-tend"]')!.textContent!;
|
||||
expect(seccion).toContain('Actividad de reportes en el tiempo');
|
||||
expect(seccion).toContain('no depende de la cohorte, la ventana ni los filtros');
|
||||
expect(seccion).toContain('Cuenta reportes, no pacientes');
|
||||
expect(seccion).toContain((tendSem as any).alcance_biopsias);
|
||||
expect(seccion).toContain('Reportes de biopsia');
|
||||
expect(seccion).not.toMatch(/χ²|p-valor|prueba de homogeneidad/i);
|
||||
});
|
||||
|
||||
it.each([0, 1, 3, 6, 12])('una barra de la distribución con la ventana de %i meses y filtros abre la lista con esa misma ventana', async (m) => {
|
||||
// Pins down: the selection a published bar emits carries the window the analysis was computed over, the filters applied,
|
||||
// the cut-off and the cohort context. Fails if a window turns into the whole cohort when the patients are opened.
|
||||
await abrir();
|
||||
const c = fixture.componentInstance;
|
||||
c.meses = m; c.filtros = { grupo_edad: '50-59' }; c.aplicar(); fixture.detectChanges();
|
||||
pide('').flush({}, { status: 404, statusText: 'x' }); pide('/resumen').flush({}, { status: 404, statusText: 'x' });
|
||||
pide('/distribucion').flush({ ...(distBirads as any), ventana: { ...(distBirads as any).ventana, meses: m }, filtros: { birads: null, grupo_edad: '50-59', biopsia: null } });
|
||||
pide('/comparacion').flush({}, { status: 404, statusText: 'x' }); pide('/mapa').flush({}, { status: 404, statusText: 'x' });
|
||||
await asentar();
|
||||
root().querySelector<HTMLButtonElement>('tr[data-codigo="BIRADS_4"] button.ver')!.click();
|
||||
expect(emitidas.at(-1)!.seleccion).toMatchObject({ filtros: { grupo_edad: '50-59', birads: 'BIRADS_4' }, corte: CORTE, meses: m, esperados: 33,
|
||||
contexto: { cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: (distBirads as any).revision } });
|
||||
});
|
||||
|
||||
it('«No disponible con las fuentes actuales» es una sección plegable, cerrada al inicio, con todo su contenido al abrirla', async () => {
|
||||
// Pins down: the unavailable analyses sit in a native disclosure (keyboard and screen reader for free), closed at first,
|
||||
// with its heading as the summary and every title and reason in the list inside it; opening it shows the same text as
|
||||
// before. Fails if it starts open, loses an entry or stops being reachable from the keyboard.
|
||||
await abrir();
|
||||
const plegable = root().querySelector<HTMLDetailsElement>('details[data-plegable="no-disponibles"]')!;
|
||||
const resumen = plegable.querySelector('summary')!;
|
||||
expect(plegable.open).toBe(false);
|
||||
expect(resumen.querySelector('h2')!.textContent).toBe('No disponible con las fuentes actuales');
|
||||
expect(root().querySelector('section[aria-labelledby="desc-no"] h2')!.id).toBe('desc-no');
|
||||
expect(resumen.tabIndex).toBeGreaterThanOrEqual(0);
|
||||
const entradas = [...plegable.querySelectorAll('li')].map(li => li.textContent);
|
||||
expect(entradas.length).toBe((resumenData as any).no_disponibles.length);
|
||||
for (const n of (resumenData as any).no_disponibles) expect(entradas.some(t => t!.includes(n.titulo) && t!.includes('No disponible. ' + n.motivo))).toBe(true);
|
||||
resumen.dispatchEvent(new MouseEvent('click', { bubbles: true })); fixture.detectChanges();
|
||||
expect(plegable.open).toBe(true);
|
||||
resumen.dispatchEvent(new MouseEvent('click', { bubbles: true })); fixture.detectChanges();
|
||||
expect(plegable.open).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,368 @@
|
||||
import { Component, DestroyRef, effect, inject, input, output, signal, untracked, WritableSignal } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { Observable, Subscription } from 'rxjs';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import {
|
||||
AnalisisCatalogoDescriptivo, AnalisisDescriptivoService, AnalisisSeleccion, CeldaMapa, ComparacionAnalisis, DistribucionAnalisis, MapaAnalisis,
|
||||
PedidoDescriptivo, ResumenAnalisis, TarjetaAnalisis, TendenciaAnalisis,
|
||||
} from './indicadores-analisis.service';
|
||||
import { comparacionFigura, distribucionFigura, FigurasTendencia, mapaFigura, tendenciaFiguras } from './indicadores-analisis-descriptivo-figuras';
|
||||
import { Dominio, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import type { SeleccionPacientes } from './indicadores-analisis';
|
||||
|
||||
type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estado: 'error'; mensaje: string } | { estado: 'pendiente' } | { estado: 'no-disponible' };
|
||||
const VACIA = { data: [], layout: {} } as PlotlyFigure;
|
||||
const miles = (v: number) => v.toLocaleString('es-MX');
|
||||
const decimal = (v: number) => v.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 });
|
||||
|
||||
/** The card's value as the page writes it: a share with its interval, a median with its quartiles, or a count. */
|
||||
export function valorTarjeta(t: TarjetaAnalisis): string | null {
|
||||
if (t.estado !== 'disponible' || t.valor === null) return null;
|
||||
return t.unidad === '%' ? decimal(t.valor) : t.unidad === 'días' ? decimal(t.valor) : miles(t.valor);
|
||||
}
|
||||
export function detalleTarjeta(t: TarjetaAnalisis): string {
|
||||
if (t.estado === 'suprimido') return 'Muy pocos pacientes para publicar esta cifra. ' + t.descripcion;
|
||||
if (t.estado === 'sin_datos') return 'No hay pacientes en esta base para calcularla. ' + t.descripcion;
|
||||
const partes: string[] = [];
|
||||
if (t.unidad === '%' && t.ic_bajo !== null && t.ic_alto !== null) partes.push(`IC 95 %: ${decimal(t.ic_bajo)} a ${decimal(t.ic_alto)} %. ${miles(t.n ?? 0)} de ${miles(t.denominador ?? 0)} pacientes.`);
|
||||
if (t.unidad === 'días' && t.q1 !== null && t.q3 !== null) partes.push(`Q1 a Q3: ${decimal(t.q1)} a ${decimal(t.q3)} días. ${miles(t.n ?? 0)} pacientes.`);
|
||||
partes.push(t.descripcion);
|
||||
return partes.join(' ');
|
||||
}
|
||||
|
||||
// Descriptive analysis of the BI-RADS cohort: its indicators, its distribution, a comparison between groups, the map
|
||||
// between two variables and the trend over time. Every figure is drawn from the endpoint's answer; what the data cannot
|
||||
// hold is listed as not available, with its reason. Nothing is requested until the tab is first opened.
|
||||
@Component({
|
||||
selector: 'app-indicadores-analisis-descriptivo',
|
||||
imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart, IndicadorKpiCard],
|
||||
template: `
|
||||
<section class="bloque" aria-labelledby="desc-resumen">
|
||||
<h2 id="desc-resumen">Indicadores de la cohorte</h2>
|
||||
<p class="nota">Pacientes cuya última mastografía reportada al corte es BI-RADS 4, 5 o 6. Descriptivos: describen a estas pacientes, no la incidencia en una población.</p>
|
||||
<form class="controles" (ngSubmit)="aplicar()">
|
||||
<label>Ventana
|
||||
<select name="meses" [(ngModel)]="meses">
|
||||
<option [ngValue]="0">Toda la cohorte</option><option [ngValue]="1">Último mes</option><option [ngValue]="3">Últimos 3 meses</option>
|
||||
<option [ngValue]="6">Últimos 6 meses</option><option [ngValue]="12">Últimos 12 meses</option>
|
||||
</select></label>
|
||||
<label>Categoría BI-RADS
|
||||
<select name="birads" [(ngModel)]="filtros['birads']"><option [ngValue]="undefined">Todas</option>
|
||||
@for (o of opciones('birads'); track o.codigo) { <option [ngValue]="o.codigo">{{ o.etiqueta }}</option> }</select></label>
|
||||
<label>Grupo de edad
|
||||
<select name="grupo_edad" [(ngModel)]="filtros['grupo_edad']"><option [ngValue]="undefined">Todos</option>
|
||||
@for (o of opciones('grupo_edad'); track o.codigo) { <option [ngValue]="o.codigo">{{ o.etiqueta }}</option> }</select></label>
|
||||
<label>Horizonte del seguimiento diagnóstico
|
||||
<select name="horizonte" [(ngModel)]="horizonte">
|
||||
@for (h of horizontes(); track h) { <option [ngValue]="h">{{ h }} días</option> }</select></label>
|
||||
<button type="submit" mat-stroked-button [disabled]="cargando()">Aplicar</button>
|
||||
</form>
|
||||
@switch (resumen().estado) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando los indicadores" /> }
|
||||
@case ('pendiente') { <p role="status">Funcionalidad pendiente de publicación.</p> }
|
||||
@case ('no-disponible') { <p role="status">La cohorte no está disponible en este momento.</p><button type="button" mat-stroked-button (click)="aplicar()">Reintentar consulta</button> }
|
||||
@case ('error') { <div role="alert"><p>{{ $any(resumen()).mensaje }}</p><button type="button" mat-stroked-button (click)="aplicar()">Reintentar consulta</button></div> }
|
||||
}
|
||||
@if (r(); as res) {
|
||||
<p class="contexto">Fecha de corte: {{ res.corte }}. Ventana: {{ res.ventana.meses === 0 ? 'toda la cohorte' : res.ventana.desde + ' al ' + res.ventana.hasta }}.</p>
|
||||
<div class="tarjetas">
|
||||
@for (t of res.indicadores; track t.clave) {
|
||||
<app-indicador-kpi-card [title]="t.titulo" [value]="valor(t)" [unit]="t.unidad === 'pacientes' ? '' : t.unidad === 'días' ? 'días (mediana)' : '%'"
|
||||
[state]="t.estado === 'disponible' ? 'Disponible' : t.estado === 'suprimido' ? 'Dato oculto por tamaño' : 'Sin valor disponible'"
|
||||
[quietWhenAvailable]="true" [additionalInfo]="detalle(t)" />
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="bloque" aria-labelledby="desc-dist">
|
||||
<h2 id="desc-dist">Distribución de pacientes</h2>
|
||||
<div class="selector" role="group" aria-label="Distribuir por">
|
||||
@for (d of dimensionesDist; track d.clave) {
|
||||
<button type="button" mat-stroked-button [class.activo]="por() === d.clave" [attr.aria-pressed]="por() === d.clave" (click)="cambiarPor(d.clave)">{{ d.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
@switch (distribucion().estado) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando la distribución" /> }
|
||||
@case ('error') { <div role="alert"><p>{{ $any(distribucion()).mensaje }}</p></div> }
|
||||
}
|
||||
@if (dist(); as d) {
|
||||
@if (d.total === 0) { <p role="status">No hay pacientes en esta cohorte para el corte seleccionado.</p> }
|
||||
@else {
|
||||
<app-plotly-chart [style.--plot-height]="'auto'" [showNotes]="false" [figure]="figuraDist()" label="Distribución de pacientes" (plotClick)="clicDist($event)" />
|
||||
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Distribución de pacientes, tabla">
|
||||
<table><caption>{{ miles(d.total) }} pacientes en la selección</caption>
|
||||
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col">Porcentaje (IC 95 %)</th><th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
|
||||
<tbody>@for (i of d.items; track i.codigo) {
|
||||
<tr [attr.data-codigo]="i.codigo"><th scope="row">{{ i.etiqueta }}</th>
|
||||
<td>{{ i.suprimido ? 'No publicado' : miles(i.n!) }}</td>
|
||||
<td>{{ i.suprimido || i.porcentaje === null ? 'No disponible' : decimal(i.porcentaje) + ' % (' + decimal(i.ic_bajo!) + ' a ' + decimal(i.ic_alto!) + ')' }}</td>
|
||||
<td>@if (!i.suprimido && i.n) { <button type="button" class="ver" (click)="abrir(i.seleccion, i.etiqueta, i.n, d, $event.currentTarget)"
|
||||
[attr.aria-label]="'Ver pacientes de ' + i.etiqueta + ' en Seguimiento'">Ver pacientes</button> }</td></tr>
|
||||
}</tbody></table>
|
||||
</div>
|
||||
@if (d.items.some(i => i.suprimido)) { <p class="nota">Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica; para que su cifra no se pueda deducir, otra categoría puede quedar sin publicar.</p> }
|
||||
}
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="bloque" aria-labelledby="desc-comp">
|
||||
<h2 id="desc-comp">Comparación entre grupos</h2>
|
||||
<p class="nota">Porcentaje de pacientes con el resultado elegido entre las que tienen resultado de biopsia conocido, por grupo. Es una comparación descriptiva dentro de la cohorte.</p>
|
||||
<div class="controles">
|
||||
<label>Comparar por
|
||||
<select name="comp-por" [ngModel]="compPor()" (ngModelChange)="cambiarComparacion($event, compMedida())">
|
||||
<option value="birads">Categoría BI-RADS</option><option value="grupo_edad">Grupo de edad</option></select></label>
|
||||
<label>Resultado
|
||||
<select name="comp-medida" [ngModel]="compMedida()" (ngModelChange)="cambiarComparacion(compPor(), $event)">
|
||||
<option value="maligno">Carcinoma in situ o invasor</option><option value="invasor">Carcinoma invasor</option></select></label>
|
||||
</div>
|
||||
@switch (comparacion().estado) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando la comparación" /> }
|
||||
@case ('error') { <div role="alert"><p>{{ $any(comparacion()).mensaje }}</p></div> }
|
||||
}
|
||||
@if (comp(); as c) {
|
||||
@if (hayComparables()) { <app-plotly-chart [showNotes]="false" [figure]="figuraComp()" label="Comparación entre grupos" /> }
|
||||
@else { <p role="status">Ningún grupo tiene suficientes pacientes con resultado de biopsia para publicar su porcentaje.</p> }
|
||||
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Comparación entre grupos, tabla">
|
||||
<table><caption>{{ c.denominador }}</caption>
|
||||
<thead><tr><th scope="col">Grupo</th><th scope="col">Con el resultado</th><th scope="col">Con resultado conocido</th><th scope="col">Porcentaje (IC 95 %)</th></tr></thead>
|
||||
<tbody>@for (g of c.grupos; track g.codigo) {
|
||||
<tr><th scope="row">{{ g.etiqueta }}</th>
|
||||
<td>{{ g.estado === 'disponible' ? miles(g.casos!) : g.estado === 'suprimido' ? 'No publicado' : '0' }}</td>
|
||||
<td>{{ g.estado === 'disponible' ? miles(g.total!) : g.estado === 'suprimido' ? 'No publicado' : '0' }}</td>
|
||||
<td>{{ g.estado === 'disponible' ? decimal(g.valor!) + ' % (' + decimal(g.ic_bajo!) + ' a ' + decimal(g.ic_alto!) + ')' : 'No disponible' }}</td></tr>
|
||||
}</tbody></table>
|
||||
</div>
|
||||
<p class="nota" role="status">{{ textoPrueba(c.prueba) }}</p>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="bloque" aria-labelledby="desc-mapa">
|
||||
<h2 id="desc-mapa">Mapa entre variables: categoría BI-RADS y grupo de edad</h2>
|
||||
<div class="selector" role="group" aria-label="Medida del mapa">
|
||||
<button type="button" mat-stroked-button [class.activo]="mapaMedida() === 'pacientes'" [attr.aria-pressed]="mapaMedida() === 'pacientes'" (click)="cambiarMapa('pacientes')">Pacientes</button>
|
||||
<button type="button" mat-stroked-button [class.activo]="mapaMedida() === 'resultado'" [attr.aria-pressed]="mapaMedida() === 'resultado'" (click)="cambiarMapa('resultado')">Porcentaje con carcinoma</button>
|
||||
</div>
|
||||
@switch (mapa().estado) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando el mapa" /> }
|
||||
@case ('error') { <div role="alert"><p>{{ $any(mapa()).mensaje }}</p></div> }
|
||||
}
|
||||
@if (m(); as mm) {
|
||||
<app-plotly-chart [showNotes]="false" [figure]="figuraMapa()" label="Mapa entre variables" (plotClick)="clicMapa($event)" />
|
||||
<p class="nota">Las celdas en blanco no se publican (menos de {{ mm.umbral_supresion }} pacientes, o se ocultan para que otra no se pueda deducir). Una celda publicada abre sus pacientes en Seguimiento.</p>
|
||||
<details><summary>Valores publicados</summary>
|
||||
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Mapa entre variables, tabla">
|
||||
<table><thead><tr><th scope="col">BI-RADS</th><th scope="col">Grupo de edad</th><th scope="col">Pacientes</th><th scope="col">Con carcinoma entre los de resultado conocido</th></tr></thead>
|
||||
<tbody>@for (c of celdasPublicadas(mm); track c.fila + c.columna) {
|
||||
<tr><th scope="row">{{ etiqueta(mm.filas.categorias, c.fila) }}</th><td>{{ etiqueta(mm.columnas.categorias, c.columna) }}</td><td>{{ miles(c.n!) }}</td>
|
||||
<td>{{ c.resultado.estado === 'disponible' ? c.resultado.casos + ' de ' + c.resultado.total + ' (' + decimal(c.resultado.valor!) + ' %)' : 'No disponible' }}</td></tr>
|
||||
}</tbody></table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="bloque" aria-labelledby="desc-tend">
|
||||
<h2 id="desc-tend">Actividad de reportes en el tiempo</h2>
|
||||
<p class="nota">Reportes de mastografía con BI-RADS y de biopsia ligada a esas mastografías en cada periodo, de todas las pacientes, y el porcentaje de resultados con carcinoma entre los reportes de biopsia con resultado. Es la actividad general: no depende de la cohorte, la ventana ni los filtros de arriba. Cuenta reportes, no pacientes; una paciente con varios reportes se cuenta varias veces.</p>
|
||||
<div class="controles">
|
||||
<label>Periodo
|
||||
<select name="tend-tipo" [ngModel]="tendTipo()" (ngModelChange)="cambiarTendencia($event, tendPeriodos())"><option value="semestre">Semestral</option><option value="mes">Mensual</option></select></label>
|
||||
<label>Periodos a mostrar
|
||||
<select name="tend-n" [ngModel]="tendPeriodos()" (ngModelChange)="cambiarTendencia(tendTipo(), $event)"><option [ngValue]="4">4</option><option [ngValue]="6">6</option><option [ngValue]="12">12</option><option [ngValue]="24">24</option></select></label>
|
||||
</div>
|
||||
@switch (tendencia().estado) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando la tendencia" /> }
|
||||
@case ('error') { <div role="alert"><p>{{ $any(tendencia()).mensaje }}</p></div> }
|
||||
}
|
||||
@if (t(); as tt) {
|
||||
<div class="par">
|
||||
<app-plotly-chart [showNotes]="false" [figure]="figurasTend().actividad" label="Reportes de mastografía y de biopsia por periodo" />
|
||||
<app-plotly-chart [showNotes]="false" [figure]="figurasTend().proporcion" label="Porcentaje de resultados con carcinoma por periodo" />
|
||||
</div>
|
||||
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Tendencia, tabla">
|
||||
<table><thead><tr><th scope="col">Periodo</th><th scope="col">Reportes de mastografía</th><th scope="col">Reportes de biopsia</th><th scope="col">Con carcinoma (IC 95 %)</th></tr></thead>
|
||||
<tbody>@for (p of tt.periodos; track p.periodo) {
|
||||
<tr><th scope="row">{{ p.periodo }}@if (p.incompleto) { <span class="nota"> (en curso)</span> }</th>
|
||||
<td>{{ p.reportes_mastografia.total === null ? 'No publicado' : miles(p.reportes_mastografia.total) }}</td>
|
||||
<td>{{ p.reportes_biopsia.total === null ? 'No publicado' : miles(p.reportes_biopsia.total) }}</td>
|
||||
<td>{{ p.maligno.estado === 'disponible' ? p.maligno.casos + ' de ' + p.maligno.total + ' (' + decimal(p.maligno.valor!) + ' %; ' + decimal(p.maligno.ic_bajo!) + ' a ' + decimal(p.maligno.ic_alto!) + ')' : p.maligno.estado === 'suprimido' ? 'No publicado' : 'Sin reportes de biopsia con resultado' }}</td></tr>
|
||||
}</tbody></table>
|
||||
</div>
|
||||
<p class="nota" role="status">{{ tt.alcance_biopsias }}. Los periodos en curso están incompletos y se marcan.</p>
|
||||
}
|
||||
</section>
|
||||
|
||||
@if (r(); as res) {
|
||||
<section class="bloque" aria-labelledby="desc-no">
|
||||
<!-- Closed at first; the native disclosure gives the keyboard (Enter and Space) and the screen reader its state. -->
|
||||
<details class="plegable" data-plegable="no-disponibles">
|
||||
<summary><h2 id="desc-no">No disponible con las fuentes actuales</h2></summary>
|
||||
<ul class="no-disponibles">
|
||||
@for (n of res.no_disponibles; track n.clave) { <li><strong>{{ n.titulo }}</strong>: No disponible. {{ n.motivo }}</li> }
|
||||
</ul>
|
||||
</details>
|
||||
</section>
|
||||
}
|
||||
`,
|
||||
styles: `
|
||||
:host { display: flex; flex-direction: column; gap: var(--issste-space-4); min-width: 0; }
|
||||
.bloque { 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, ul { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
|
||||
.nota, .contexto { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
.tarjetas { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-4); }
|
||||
@media (min-width: 700px) { .tarjetas { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
@media (min-width: 1100px) { .tarjetas { grid-template-columns: repeat(4, minmax(0, 1fr)); } .par { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
.par { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
|
||||
.controles { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); margin-top: var(--issste-space-3); }
|
||||
.selector { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); margin-top: var(--issste-space-3); }
|
||||
.selector .activo { background: var(--issste-accent, #A8C243); color: #081839; }
|
||||
label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; }
|
||||
select { color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 4px; padding: .6rem; min-height: 44px; font: inherit; }
|
||||
select:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
app-plotly-chart { margin-top: var(--issste-space-3); }
|
||||
.tabla-scroll { overflow-x: auto; margin-top: var(--issste-space-4); }
|
||||
table { width: 100%; min-width: 28rem; border-collapse: collapse; font: var(--mat-sys-body-medium); }
|
||||
caption { text-align: left; font: var(--mat-sys-title-small); padding-bottom: var(--issste-space-2); }
|
||||
th, td { padding: var(--issste-space-2) var(--issste-space-3); border-bottom: 1px solid var(--issste-border); text-align: left; vertical-align: top; }
|
||||
td { font-variant-numeric: tabular-nums; }
|
||||
.ver { min-height: 44px; padding: 0 .5rem; border: 0; background: none; color: inherit; text-decoration: underline; cursor: pointer; font: inherit; }
|
||||
.ver:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
details { margin-top: var(--issste-space-3); } summary { cursor: pointer; }
|
||||
.no-disponibles { padding-left: 1.2rem; color: var(--issste-text-secondary); }
|
||||
.plegable > summary { display: list-item; list-style-position: inside; cursor: pointer; border-radius: var(--issste-radius); }
|
||||
.plegable > summary h2 { display: inline; }
|
||||
.plegable > summary:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
|
||||
`,
|
||||
})
|
||||
export class IndicadoresAnalisisDescriptivo {
|
||||
readonly dominio = input.required<Dominio>();
|
||||
readonly tema = input.required<Tema>();
|
||||
readonly corte = input.required<string>();
|
||||
readonly active = input(false);
|
||||
readonly verPacientes = output<{ seleccion: SeleccionPacientes; origen: HTMLElement | null }>();
|
||||
readonly miles = miles; readonly decimal = decimal;
|
||||
readonly valor = valorTarjeta; readonly detalle = detalleTarjeta;
|
||||
readonly dimensionesDist = [{ clave: 'birads', etiqueta: 'Categoría BI-RADS' }, { clave: 'grupo_edad', etiqueta: 'Grupo de edad' }, { clave: 'biopsia', etiqueta: 'Resultado de la biopsia' }];
|
||||
|
||||
meses = 0; horizonte = 90; filtros: Record<string, string | undefined> = {};
|
||||
readonly por = signal('birads');
|
||||
readonly compPor = signal('grupo_edad'); readonly compMedida = signal('maligno');
|
||||
readonly mapaMedida = signal<'pacientes' | 'resultado'>('pacientes');
|
||||
readonly tendTipo = signal('semestre'); readonly tendPeriodos = signal(6);
|
||||
|
||||
readonly catalogo = signal<Carga<AnalisisCatalogoDescriptivo>>({ estado: 'cargando' });
|
||||
readonly resumen = signal<Carga<ResumenAnalisis>>({ estado: 'cargando' });
|
||||
readonly distribucion = signal<Carga<DistribucionAnalisis>>({ estado: 'cargando' });
|
||||
readonly comparacion = signal<Carga<ComparacionAnalisis>>({ estado: 'cargando' });
|
||||
readonly mapa = signal<Carga<MapaAnalisis>>({ estado: 'cargando' });
|
||||
readonly tendencia = signal<Carga<TendenciaAnalisis>>({ estado: 'cargando' });
|
||||
readonly figuraDist = signal<PlotlyFigure>(VACIA); readonly figuraComp = signal<PlotlyFigure>(VACIA);
|
||||
readonly figuraMapa = signal<PlotlyFigure>(VACIA);
|
||||
readonly figurasTend = signal<FigurasTendencia>({ actividad: VACIA, proporcion: VACIA });
|
||||
private readonly service = inject(AnalisisDescriptivoService);
|
||||
private readonly destroy = inject(DestroyRef);
|
||||
private readonly suscripciones = new Map<string, Subscription>();
|
||||
private abierto = false; private corteCargado = ''; private tendCorte = '';
|
||||
// The filters and window the sections were last asked with: one selection for all of them.
|
||||
private pedidoVigente: PedidoDescriptivo = { corte: '', meses: 0, filtros: {} };
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const activa = this.active(), corte = this.corte();
|
||||
if (!activa) return;
|
||||
untracked(() => { if (!this.abierto || corte !== this.corteCargado) { this.abierto = true; this.corteCargado = corte; this.aplicar(); } });
|
||||
});
|
||||
}
|
||||
|
||||
// Each accessor gives the loaded data or nothing: the template draws only what the endpoint answered.
|
||||
r() { const c = this.resumen(); return c.estado === 'listo' ? c.datos : undefined; }
|
||||
dist() { const c = this.distribucion(); return c.estado === 'listo' ? c.datos : undefined; }
|
||||
comp() { const c = this.comparacion(); return c.estado === 'listo' ? c.datos : undefined; }
|
||||
m() { const c = this.mapa(); return c.estado === 'listo' ? c.datos : undefined; }
|
||||
t() { const c = this.tendencia(); return c.estado === 'listo' ? c.datos : undefined; }
|
||||
cargando() { return [this.resumen(), this.distribucion(), this.comparacion(), this.mapa(), this.tendencia()].some(c => c.estado === 'cargando'); }
|
||||
opciones(clave: string) { const c = this.catalogo(); return c.estado === 'listo' ? c.datos.dimensiones.find(d => d.clave === clave)?.opciones ?? [] : []; }
|
||||
horizontes() { const c = this.catalogo(); return c.estado === 'listo' ? c.datos.horizontes_dias : [90]; }
|
||||
hayComparables() { return !!this.comp()?.grupos.some(g => g.estado === 'disponible'); }
|
||||
celdasPublicadas(m: MapaAnalisis): CeldaMapa[] { return m.celdas.filter(c => !c.suprimido && (c.n ?? 0) > 0); }
|
||||
etiqueta(categorias: { codigo: string; etiqueta: string }[], codigo: string) { return categorias.find(c => c.codigo === codigo)?.etiqueta ?? codigo; }
|
||||
textoPrueba(p: { valida: boolean; motivo?: string; estadistico?: number; gl?: number; p?: number; nombre: string }) {
|
||||
if (!p.valida) return `${p.nombre}: No disponible. ${p.motivo ?? ''}`.trim();
|
||||
const valor = p.p! < 0.001 ? '< 0.001' : p.p!.toLocaleString('es-MX', { minimumFractionDigits: 3, maximumFractionDigits: 3 });
|
||||
return `${p.nombre}: χ² ${p.estadistico!.toLocaleString('es-MX')}, ${p.gl} gl, p ${valor}. Describe diferencias en estas pacientes; no es una estimación causal.`;
|
||||
}
|
||||
|
||||
private pedido(): PedidoDescriptivo {
|
||||
return { corte: this.corte(), meses: this.meses, filtros: { ...this.filtros } };
|
||||
}
|
||||
/** Asks every section for the selection in the form: the first time, on a new cut-off and on «Aplicar». */
|
||||
aplicar() {
|
||||
this.pedidoVigente = this.pedido();
|
||||
const p = this.pedidoVigente;
|
||||
this.cargar('catalogo', this.catalogo, this.service.catalogo(this.dominio(), p));
|
||||
this.cargar('resumen', this.resumen, this.service.resumen(this.dominio(), p, this.horizonte));
|
||||
this.recargarDist(); this.recargarComp(); this.recargarMapa();
|
||||
// The trend depends only on the cut-off: «Aplicar» with other filters or window leaves it as it is.
|
||||
if (this.corte() !== this.tendCorte) { this.tendCorte = this.corte(); this.recargarTend(); }
|
||||
}
|
||||
private recargarDist() { this.cargar('dist', this.distribucion, this.service.distribucion(this.dominio(), this.pedidoVigente, this.por()), d => this.figuraDist.set(distribucionFigura(d, this.tema()))); }
|
||||
private recargarComp() { this.cargar('comp', this.comparacion, this.service.comparacion(this.dominio(), this.pedidoVigente, this.compPor(), this.compMedida()), c => this.figuraComp.set(comparacionFigura(c, this.tema(), this.compMedida() === 'invasor' ? 'Carcinoma invasor' : 'Carcinoma in situ o invasor'))); }
|
||||
private recargarMapa() { this.cargar('mapa', this.mapa, this.service.mapa(this.dominio(), this.pedidoVigente, 'birads', 'grupo_edad', 'maligno'), m => this.figuraMapa.set(mapaFigura(m, this.tema(), this.mapaMedida()))); }
|
||||
private recargarTend() { this.cargar('tend', this.tendencia, this.service.tendencia(this.dominio(), this.corte(), this.tendTipo(), this.tendPeriodos()), t => this.figurasTend.set(tendenciaFiguras(t, this.tema(), 'Con carcinoma entre biopsias con resultado'))); }
|
||||
cambiarPor(clave: string) { this.por.set(clave); this.recargarDist(); }
|
||||
cambiarComparacion(por: string, medida: string) { this.compPor.set(por); this.compMedida.set(medida); this.recargarComp(); }
|
||||
cambiarMapa(medida: 'pacientes' | 'resultado') { this.mapaMedida.set(medida); const m = this.m(); if (m) this.figuraMapa.set(mapaFigura(m, this.tema(), medida)); }
|
||||
cambiarTendencia(tipo: string, periodos: number) { this.tendTipo.set(tipo); this.tendPeriodos.set(periodos); this.recargarTend(); }
|
||||
|
||||
private cargar<T>(clave: string, destino: WritableSignal<Carga<T>>, fuente: Observable<T>, alListo?: (d: T) => void) {
|
||||
this.suscripciones.get(clave)?.unsubscribe();
|
||||
destino.set({ estado: 'cargando' });
|
||||
this.suscripciones.set(clave, fuente.pipe(takeUntilDestroyed(this.destroy)).subscribe({
|
||||
next: datos => { destino.set({ estado: 'listo', datos }); alListo?.(datos); },
|
||||
error: error => destino.set(this.fallo(error)),
|
||||
}));
|
||||
}
|
||||
private fallo(error: unknown): Carga<never> {
|
||||
if (error instanceof HttpErrorResponse) {
|
||||
if (error.status === 404) return { estado: 'pendiente' };
|
||||
if (error.status === 503) return { estado: 'no-disponible' };
|
||||
if (error.status === 403) return { estado: 'error', mensaje: 'La selección tiene muy pocos pacientes para publicar sus resultados.' };
|
||||
if (error.status === 409) return { estado: 'error', mensaje: 'La cohorte cambió. Consulta de nuevo.' };
|
||||
if (error.status === 400) return { estado: 'error', mensaje: 'El servicio rechazó la selección. Revisa la ventana y los filtros.' };
|
||||
if (error.status === 0) return { estado: 'error', mensaje: 'No se pudo conectar con el servicio. Revisa la conexión y vuelve a intentar.' };
|
||||
if (error.status >= 500) return { estado: 'error', mensaje: 'El servicio encontró un error interno. Intenta nuevamente más tarde.' };
|
||||
}
|
||||
return { estado: 'error', mensaje: 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.' };
|
||||
}
|
||||
|
||||
/** The patients of a published group or cell, for the page to open them in Seguimiento. */
|
||||
abrir(seleccion: Record<string, string>, etiqueta: string, n: number | null, base: AnalisisSeleccion, origen?: EventTarget | null) {
|
||||
if (!n) return;
|
||||
const activos = Object.fromEntries(Object.entries(base.filtros).filter(([, v]) => v !== null)) as Record<string, string>;
|
||||
this.verPacientes.emit({
|
||||
origen: origen instanceof HTMLElement ? origen : null,
|
||||
seleccion: { filtros: { ...activos, ...seleccion }, etiqueta, corte: base.corte, meses: base.ventana.meses, esperados: n, contexto: { cohorte: base.cohorte, escenario: base.escenario, revision: base.revision } },
|
||||
});
|
||||
}
|
||||
clicDist(evento: unknown) {
|
||||
const codigo = (evento as { points?: { customdata?: unknown }[] } | undefined)?.points?.[0]?.customdata;
|
||||
const d = this.dist(), item = d?.items.find(i => i.codigo === codigo && !i.suprimido);
|
||||
if (d && item) this.abrir(item.seleccion, item.etiqueta, item.n, d);
|
||||
}
|
||||
clicMapa(evento: unknown) {
|
||||
const c = (evento as { points?: { customdata?: unknown; z?: unknown }[] } | undefined)?.points?.[0];
|
||||
const [fila, columna] = Array.isArray(c?.customdata) ? c.customdata as string[] : [];
|
||||
const mm = this.m(), celda = mm?.celdas.find(x => x.fila === fila && x.columna === columna && !x.suprimido);
|
||||
if (mm && celda) this.abrir(celda.seleccion, `${this.etiqueta(mm.filas.categorias, celda.fila)}, ${this.etiqueta(mm.columnas.categorias, celda.columna)}`, celda.n, mm);
|
||||
}
|
||||
}
|
||||
@@ -55,3 +55,119 @@ export class AnalisisService {
|
||||
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/indicadores`, { params: new HttpParams().set('corte', corte) }).pipe(map(analisisAgregado));
|
||||
}
|
||||
}
|
||||
|
||||
// The descriptive analysis (`/<dominio>/analisis/...`): counts and proportions of the cohort at a cut-off, with the
|
||||
// window and filters of the follow-up list. Every answer names the cohort it describes, so a figure can open its patients.
|
||||
export interface AnalisisSeleccion {
|
||||
cohorte: string; escenario: string; revision: string; corte: string; umbral_supresion: number;
|
||||
ventana: { meses: number; desde: string; hasta: string };
|
||||
filtros: Record<string, string | null>;
|
||||
}
|
||||
export type EstadoDato = 'disponible' | 'suprimido' | 'sin_datos';
|
||||
export interface Proporcion { estado: EstadoDato; casos: number | null; total: number | null; valor: number | null; ic_bajo: number | null; ic_alto: number | null; }
|
||||
export interface DimensionAnalisis { clave: string; etiqueta: string; opciones: { codigo: string; etiqueta: string }[]; }
|
||||
export interface NoDisponible { clave: string; titulo: string; motivo: string; }
|
||||
export interface AnalisisCatalogoDescriptivo extends AnalisisSeleccion {
|
||||
dimensiones: DimensionAnalisis[]; medidas: { clave: string; etiqueta: string }[]; horizontes_dias: number[]; tipos_periodo: string[];
|
||||
secciones: { clave: string; titulo: string; estado: string; motivo: string | null }[]; no_disponibles: NoDisponible[];
|
||||
}
|
||||
export interface TarjetaAnalisis {
|
||||
clave: string; titulo: string; descripcion: string; unidad: string; estado: EstadoDato; valor: number | null; ic_bajo: number | null; ic_alto: number | null;
|
||||
n: number | null; denominador: number | null; q1: number | null; q3: number | null; motivo: string | null;
|
||||
}
|
||||
export interface ResumenAnalisis extends AnalisisSeleccion { horizonte_dias: number; indicadores: TarjetaAnalisis[]; no_disponibles: NoDisponible[]; }
|
||||
export interface ItemDistribucion { codigo: string; etiqueta: string; suprimido: boolean; n: number | null; porcentaje: number | null; ic_bajo: number | null; ic_alto: number | null; seleccion: Record<string, string>; }
|
||||
export interface DistribucionAnalisis extends AnalisisSeleccion { por: string; total: number; items: ItemDistribucion[]; }
|
||||
export interface Prueba { nombre: string; valida: boolean; motivo?: string; estadistico?: number; gl?: number; p?: number; }
|
||||
export interface GrupoComparacion extends Proporcion { codigo: string; etiqueta: string; seleccion: Record<string, string>; }
|
||||
export interface ComparacionAnalisis extends AnalisisSeleccion { por: string; medida: string; denominador: string; grupos: GrupoComparacion[]; prueba: Prueba; }
|
||||
export interface CeldaMapa { fila: string; columna: string; suprimido: boolean; n: number | null; seleccion: Record<string, string>; resultado: Proporcion; }
|
||||
export interface EjeMapa { por: string; categorias: { codigo: string; etiqueta: string }[]; }
|
||||
export interface MapaAnalisis extends AnalisisSeleccion { filas: EjeMapa; columnas: EjeMapa; medida: string; celdas: CeldaMapa[]; }
|
||||
export interface ConteoPeriodo { n: number | null; suprimido: boolean; }
|
||||
export interface PeriodoTendencia {
|
||||
periodo: string; inicio: string; fin: string; incompleto: boolean;
|
||||
reportes_mastografia: { total: number | null; por_categoria: Record<string, ConteoPeriodo> };
|
||||
reportes_biopsia: { total: number | null; por_grado: Record<string, ConteoPeriodo> };
|
||||
maligno: Proporcion;
|
||||
}
|
||||
// The trend is general activity, not the cohort: it carries no cohort, window or filters, only what it counts and over whom.
|
||||
export interface TendenciaAnalisis {
|
||||
corte: string; umbral_supresion: number; tipo_periodo: string; unidad: string; poblacion: string; alcance_biopsias: string;
|
||||
denominador: string; periodos: PeriodoTendencia[];
|
||||
}
|
||||
export interface PedidoDescriptivo { corte: string; meses: number; filtros: Record<string, string | undefined>; contexto?: { cohorte: string; escenario: string; revision: string }; }
|
||||
|
||||
const numOnulo = (v: unknown) => v === null || (typeof v === 'number' && Number.isFinite(v));
|
||||
const estadoOk = (v: unknown) => v === 'disponible' || v === 'suprimido' || v === 'sin_datos';
|
||||
const proporcionOk = (v: unknown) => record(v) && estadoOk(v['estado']) && numOnulo(v['valor']) && numOnulo(v['ic_bajo']) && numOnulo(v['ic_alto'])
|
||||
&& numOnulo(v['casos']) && numOnulo(v['total']) && (v['estado'] === 'disponible' ? v['valor'] !== null && v['casos'] !== null : v['valor'] === null);
|
||||
const seleccionOk = (v: unknown): v is Record<string, unknown> => record(v) && text(v['cohorte']) && text(v['escenario']) && text(v['revision']) && text(v['corte'])
|
||||
&& typeof v['umbral_supresion'] === 'number' && record(v['ventana']) && record(v['filtros']);
|
||||
const invalidoDescriptivo = (): never => { throw new Error('Respuesta de análisis inválida'); };
|
||||
|
||||
export function catalogoDescriptivo(v: unknown): AnalisisCatalogoDescriptivo {
|
||||
if (!seleccionOk(v) || !Array.isArray(v['dimensiones']) || !v['dimensiones'].every(d => record(d) && text(d['clave']) && Array.isArray(d['opciones']))
|
||||
|| !Array.isArray(v['no_disponibles']) || !Array.isArray(v['horizontes_dias']) || !Array.isArray(v['tipos_periodo'])) invalidoDescriptivo();
|
||||
return v as unknown as AnalisisCatalogoDescriptivo;
|
||||
}
|
||||
export function resumenDescriptivo(v: unknown): ResumenAnalisis {
|
||||
if (!seleccionOk(v) || !Array.isArray(v['indicadores']) || !v['indicadores'].every(t => record(t) && text(t['clave']) && text(t['titulo']) && estadoOk(t['estado'])
|
||||
&& numOnulo(t['valor']) && (t['estado'] === 'disponible' ? t['valor'] !== null : t['valor'] === null))) invalidoDescriptivo();
|
||||
return v as unknown as ResumenAnalisis;
|
||||
}
|
||||
export function distribucionDescriptiva(v: unknown): DistribucionAnalisis {
|
||||
if (!seleccionOk(v) || typeof v['total'] !== 'number' || !Array.isArray(v['items'])
|
||||
|| !v['items'].every(i => record(i) && text(i['codigo']) && typeof i['suprimido'] === 'boolean' && numOnulo(i['n']) && (i['suprimido'] ? i['n'] === null : i['n'] !== null)
|
||||
&& record(i['seleccion']))) invalidoDescriptivo();
|
||||
return v as unknown as DistribucionAnalisis;
|
||||
}
|
||||
export function comparacionDescriptiva(v: unknown): ComparacionAnalisis {
|
||||
if (!seleccionOk(v) || !Array.isArray(v['grupos']) || !v['grupos'].every(g => record(g) && text(g['codigo']) && proporcionOk(g))
|
||||
|| !record(v['prueba']) || typeof v['prueba']['valida'] !== 'boolean') invalidoDescriptivo();
|
||||
return v as unknown as ComparacionAnalisis;
|
||||
}
|
||||
export function mapaDescriptivo(v: unknown): MapaAnalisis {
|
||||
if (!seleccionOk(v) || !record(v['filas']) || !record(v['columnas']) || !Array.isArray(v['celdas'])
|
||||
|| !v['celdas'].every(c => record(c) && text(c['fila']) && text(c['columna']) && typeof c['suprimido'] === 'boolean' && numOnulo(c['n'])
|
||||
&& (c['suprimido'] ? c['n'] === null : c['n'] !== null) && record(c['resultado']) && estadoOk(c['resultado']['estado']))) invalidoDescriptivo();
|
||||
return v as unknown as MapaAnalisis;
|
||||
}
|
||||
export function tendenciaDescriptiva(v: unknown): TendenciaAnalisis {
|
||||
if (!record(v) || !text(v['corte']) || v['unidad'] !== 'reportes' || !text(v['poblacion']) || !text(v['alcance_biopsias']) || !text(v['tipo_periodo'])
|
||||
|| !Array.isArray(v['periodos']) || !v['periodos'].every(p => record(p) && text(p['periodo']) && typeof p['incompleto'] === 'boolean'
|
||||
&& record(p['reportes_mastografia']) && record(p['reportes_biopsia']) && proporcionOk(p['maligno']))) invalidoDescriptivo();
|
||||
return v as unknown as TendenciaAnalisis;
|
||||
}
|
||||
|
||||
function paramsDe(pedido: PedidoDescriptivo, extra: Record<string, string | number | undefined> = {}) {
|
||||
let params = new HttpParams().set('corte', pedido.corte).set('meses', pedido.meses);
|
||||
for (const [k, v] of Object.entries(pedido.filtros)) if (v) params = params.set(k, v);
|
||||
if (pedido.contexto) for (const [k, v] of Object.entries(pedido.contexto)) params = params.set(k, v);
|
||||
for (const [k, v] of Object.entries(extra)) if (v !== undefined) params = params.set(k, v);
|
||||
return params;
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AnalisisDescriptivoService {
|
||||
private readonly http = inject(HttpClient);
|
||||
private url(dominio: Dominio, ruta: string) { return `/${requireDominio(dominio)}/analisis${ruta}`; }
|
||||
catalogo(d: Dominio, p: PedidoDescriptivo) { return this.http.get<unknown>(this.url(d, ''), { params: paramsDe(p) }).pipe(map(catalogoDescriptivo)); }
|
||||
resumen(d: Dominio, p: PedidoDescriptivo, horizonte: number) {
|
||||
return this.http.get<unknown>(this.url(d, '/resumen'), { params: paramsDe(p, { horizonte }) }).pipe(map(resumenDescriptivo));
|
||||
}
|
||||
distribucion(d: Dominio, p: PedidoDescriptivo, por: string) {
|
||||
return this.http.get<unknown>(this.url(d, '/distribucion'), { params: paramsDe(p, { por }) }).pipe(map(distribucionDescriptiva));
|
||||
}
|
||||
comparacion(d: Dominio, p: PedidoDescriptivo, por: string, medida: string) {
|
||||
return this.http.get<unknown>(this.url(d, '/comparacion'), { params: paramsDe(p, { por, medida }) }).pipe(map(comparacionDescriptiva));
|
||||
}
|
||||
mapa(d: Dominio, p: PedidoDescriptivo, filas: string, columnas: string, medida: string) {
|
||||
return this.http.get<unknown>(this.url(d, '/mapa'), { params: paramsDe(p, { filas, columnas, medida }) }).pipe(map(mapaDescriptivo));
|
||||
}
|
||||
/** The trend takes only the cut-off, the period type and the number of periods: never the window, filters or context. */
|
||||
tendencia(d: Dominio, corte: string, tipo: string, periodos: number) {
|
||||
const params = new HttpParams().set('corte', corte).set('tipo', tipo).set('periodos', periodos);
|
||||
return this.http.get<unknown>(this.url(d, '/tendencia'), { params }).pipe(map(tendenciaDescriptiva));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { Component, output } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideHttpClient, withInterceptors } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadoresAnalisis, MOTIVO_GRUPO_SUPRIMIDO, SeleccionPacientes, hoyIso, motivoSinLista, seleccionDeGrupo } from './indicadores-analisis';
|
||||
import { etiquetaBirads, grupoDelClic, gruposFigura } from './indicadores-analisis-figuras';
|
||||
import { analisisAgregado } from './indicadores-analisis.service';
|
||||
import { agregado, agregadoJson, CONTEXTO, CORTE } from './indicadores-analisis.testing';
|
||||
import { agregado, agregadoJson, CONTEXTO, CORTE, sinAnalisisDescriptivo } from './indicadores-analisis.testing';
|
||||
|
||||
// Covers the «Análisis epidemiológico» tab of breast cancer as the cohort API publishes it today: the guard of its answer
|
||||
// (an aggregate, never patient rows, nothing published under the threshold), the figure, the selection a published group
|
||||
@@ -80,7 +80,7 @@ class ChartStub { readonly plotClick = output<unknown>(); }
|
||||
describe('Pestaña Análisis epidemiológico', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresAnalisis>>, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(withInterceptors([sinAnalisisDescriptivo])), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadoresAnalisis, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
fixture = TestBed.createComponent(IndicadoresAnalisis); http = TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('tema', 'claro');
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
// Fixtures of the analysis tab and of its journey to Seguimiento, shaped like the answers of the cohort API
|
||||
// (`GET /cama/analisis/indicadores?corte=` and the list `GET /cama/seguimiento` of a cohort).
|
||||
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
|
||||
import { throwError } from 'rxjs';
|
||||
import { AnalisisAgregado } from './indicadores-analisis.service';
|
||||
|
||||
export const REVISION = 'dae23030398f86a24e8ad910471d27ce02502ac6b174063c98e5163dea0ce7a7';
|
||||
@@ -45,3 +47,12 @@ export function listaCohorte(o: { corte?: string; filtros?: Record<string, strin
|
||||
|
||||
/** What the API sends on the wire: the aggregate plus the fields of the prototype it leaves empty. */
|
||||
export const agregadoJson = (extra: Record<string, unknown> = {}) => ({ ...agregado(), horizonte_dias: 0, indicadores: [], ...extra });
|
||||
|
||||
/**
|
||||
* For specs of the analysis tab that are about its BI-RADS aggregate and its way to Seguimiento: the descriptive sections
|
||||
* below it (catalog, indicators, distribution, comparison, map, trend) answer «not published» and never reach the test
|
||||
* backend, so those specs keep counting only the requests they are about.
|
||||
*/
|
||||
export const sinAnalisisDescriptivo: HttpInterceptorFn = (req, next) =>
|
||||
/^\/[a-z]+\/analisis(\/(resumen|distribucion|comparacion|mapa|tendencia))?$/.test(req.url)
|
||||
? throwError(() => new HttpErrorResponse({ status: 404, url: req.url })) : next(req);
|
||||
|
||||
@@ -7,6 +7,7 @@ import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import { IndicadoresAnalisisDescriptivo } from './indicadores-analisis-descriptivo';
|
||||
import { isoDate } from './cacu-seguimiento.models';
|
||||
import { grupoDelClic, gruposFigura } from './indicadores-analisis-figuras';
|
||||
import { etiquetaBirads } from './etiquetas-cohorte';
|
||||
@@ -20,7 +21,7 @@ type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estad
|
||||
* name the selection, the cut-off and the cohort the group was counted in (the list quotes it back), and how many
|
||||
* patients the analysis counts there.
|
||||
*/
|
||||
export interface SeleccionPacientes { filtros: Record<string, string>; etiqueta: string; corte: string; esperados: number | null; contexto: ContextoCohorte; }
|
||||
export interface SeleccionPacientes { filtros: Record<string, string>; etiqueta: string; corte: string; meses?: number; esperados: number | null; contexto: ContextoCohorte; }
|
||||
|
||||
export const MOTIVO_GRUPO_SUPRIMIDO = 'El grupo tiene muy pocos pacientes: su lista no se publica.';
|
||||
|
||||
@@ -54,7 +55,7 @@ function contenedorDeScroll(el: HTMLElement): HTMLElement {
|
||||
// a suppressed one says why it does not. Nothing is requested until the tab is first opened.
|
||||
@Component({
|
||||
selector: 'app-indicadores-analisis',
|
||||
imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart, IndicadorKpiCard],
|
||||
imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart, IndicadorKpiCard, IndicadoresAnalisisDescriptivo],
|
||||
template: `
|
||||
<section class="analisis" aria-labelledby="analisis-titulo">
|
||||
<h2 id="analisis-titulo">Análisis epidemiológico</h2>
|
||||
@@ -112,6 +113,7 @@ function contenedorDeScroll(el: HTMLElement): HTMLElement {
|
||||
}
|
||||
</article>
|
||||
</section>
|
||||
<app-indicadores-analisis-descriptivo [dominio]="dominio()" [tema]="tema()" [corte]="corteConsultado()" [active]="active()" (verPacientes)="abrirDescriptivo($event)" />
|
||||
`,
|
||||
styles: `
|
||||
:host { display: block; min-width: 0; }
|
||||
@@ -166,6 +168,8 @@ export class IndicadoresAnalisis {
|
||||
private ultimo?: string;
|
||||
private retorno?: { origen: HTMLElement | null; area: HTMLElement; arriba: number };
|
||||
corte = this.hoy;
|
||||
// The cut-off of the last query: the descriptive sections follow it.
|
||||
readonly corteConsultado = signal(this.hoy);
|
||||
readonly carga = signal<Carga<AnalisisAgregado>>({ estado: 'cargando' });
|
||||
// Why the last click on a bar opened nothing.
|
||||
readonly aviso = signal('');
|
||||
@@ -206,6 +210,7 @@ export class IndicadoresAnalisis {
|
||||
consultar() {
|
||||
if (!isoDate(this.corte)) { this.carga.set({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); return; }
|
||||
this.ultimo = this.corte;
|
||||
this.corteConsultado.set(this.corte);
|
||||
this.pedidos.next(this.corte);
|
||||
}
|
||||
reintentar() { this.pedidos.next(this.ultimo ?? this.corte); }
|
||||
@@ -229,6 +234,12 @@ export class IndicadoresAnalisis {
|
||||
this.retorno = { origen: el, area, arriba: area.scrollTop };
|
||||
this.verPacientes.emit(seleccion);
|
||||
}
|
||||
// The patients of a figure of the descriptive sections: the same way back as a bar of the BI-RADS table.
|
||||
abrirDescriptivo(evento: { seleccion: SeleccionPacientes; origen: HTMLElement | null }) {
|
||||
const area = contenedorDeScroll(this.host.nativeElement);
|
||||
this.retorno = { origen: evento.origen, area, arriba: area.scrollTop };
|
||||
this.verPacientes.emit(evento.seleccion);
|
||||
}
|
||||
/** Back from Seguimiento: the scroll where it was and the focus on the control that opened the list. */
|
||||
restaurar() {
|
||||
const r = this.retorno;
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones';
|
||||
import { FigureSelection, IndicadorDatos } from './indicadores.models';
|
||||
|
||||
const fila = (grupo: string, numerador: number, denominador: number, extra: object = {}) => ({
|
||||
periodo: '2025-S2', grupo, estrato: null, suprimido: 0, numerador, denominador, valor: 0, ic_bajo: null, ic_alto: null,
|
||||
n_sin_evento: denominador - numerador, n_excluido: 0, ...extra,
|
||||
});
|
||||
const datos = (filas: Record<string, unknown>[] = [fila('TOTAL', 11, 20), fila('ritmo_posterior', 5, 20), fila('picos_paroxisticos', 0, 20)]): IndicadorDatos => ({
|
||||
id: 'M30_resultado_eeg', titulo: 'Porcentaje de EEG normal y anormal', contrato: 'C1', unidad: 'paciente',
|
||||
tipo_periodo: 'semestre', periodos: ['2025-S2'], estrato: null, valores_estrato: [],
|
||||
grupos: { TOTAL: 'Total', ritmo_posterior: 'Ritmo posterior', picos_paroxisticos: 'Picos paroxísticos' },
|
||||
grupos_de_categoria: {}, notas: ['Datos ficticios.'], filas,
|
||||
});
|
||||
const selection: FigureSelection = { dominio: 'tea', indicador: 'M30_resultado_eeg', figura: 'fig_c1_barras_alteracion', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] };
|
||||
|
||||
describe('Barras por alteración para C1', () => {
|
||||
it('solo aplica a C1 con la figura por alteración', () => {
|
||||
expect(c1AlterationCapability('C1', 'fig_c1_barras_alteracion')).toBe(true);
|
||||
expect(c1AlterationCapability('C2', 'fig_c1_barras_alteracion')).toBe(false);
|
||||
expect(c1AlterationCapability('C1', 'fig_c1_barras_edad')).toBe(false);
|
||||
});
|
||||
it('una barra por alteración tras la de alguna alteración, con su porcentaje y sus conteos', () => {
|
||||
const result = c1AlterationFigure(datos(), selection);
|
||||
if (result.status !== 'supported') throw new Error(result.reason);
|
||||
const [trace] = result.figure.data as Record<string, unknown>[];
|
||||
expect(result.figure.data.length).toBe(1);
|
||||
expect(trace['x']).toEqual(['Alguna alteración', 'Ritmo posterior', 'Picos paroxísticos']);
|
||||
expect(trace['y']).toEqual([55, 25, 0]);
|
||||
expect(trace['text']).toEqual(['55.0 %', '25.0 %', '0.0 %']);
|
||||
expect(trace['customdata']).toEqual([[11, 20], [5, 20], [0, 20]]);
|
||||
expect(result.total).toBe(20);
|
||||
expect(result.notes).toEqual(['Datos ficticios.']);
|
||||
expect(result.highlight.items.map(i => i.id)).toEqual(['TOTAL', 'ritmo_posterior', 'picos_paroxisticos']);
|
||||
expect((result.figure.layout['title'] as { text: string }).text).toBe('Porcentaje de EEG normal y anormal, 2025-S2');
|
||||
});
|
||||
it('varios periodos se dibujan lado a lado, uno por serie', () => {
|
||||
const otro = (grupo: string, n: number, d: number) => fila(grupo, n, d, { periodo: '2025-S1' });
|
||||
const data = { ...datos([otro('TOTAL', 2, 8), otro('ritmo_posterior', 1, 8), otro('picos_paroxisticos', 1, 8), ...datos().filas]), periodos: ['2025-S1', '2025-S2'] };
|
||||
const result = c1AlterationFigure(data, { ...selection, periodos: ['2025-S1', '2025-S2'] });
|
||||
if (result.status !== 'supported') throw new Error(result.reason);
|
||||
const traces = result.figure.data as Record<string, unknown>[];
|
||||
expect(traces.map(t => t['name'])).toEqual(['2025-S1', '2025-S2']);
|
||||
expect(traces[0]['y']).toEqual([25, 12.5, 12.5]);
|
||||
expect(result.figure.layout['showlegend']).toBe(true);
|
||||
expect(result.total).toBe(28);
|
||||
expect(result.highlight.items[1].points).toEqual([{ trace: 0, index: 1 }, { trace: 1, index: 1 }]);
|
||||
});
|
||||
it('un periodo sin niños con EEG bueno no dibuja ceros', () => {
|
||||
const result = c1AlterationFigure(datos([fila('TOTAL', 0, 0), fila('ritmo_posterior', 0, 0), fila('picos_paroxisticos', 0, 0)]), selection);
|
||||
if (result.status !== 'supported') throw new Error(result.reason);
|
||||
expect((result.figure.data[0] as Record<string, unknown>)['y']).toEqual([null, null, null]);
|
||||
expect(result.total).toBe(0);
|
||||
});
|
||||
it('rechaza datos que no son los grupos por alteración de la selección', () => {
|
||||
expect(c1AlterationFigure({ ...datos(), grupos: { TOTAL: 'Total' } }, selection).status).toBe('unsupported');
|
||||
expect(c1AlterationFigure({ ...datos(), estrato: 'grupo_edad' }, selection).status).toBe('unsupported');
|
||||
expect(c1AlterationFigure(datos([fila('TOTAL', 11, 20), fila('ritmo_posterior', 5, 20)]), selection).status).toBe('unsupported');
|
||||
expect(c1AlterationFigure(datos([fila('TOTAL', 11, 20), fila('ritmo_posterior', 25, 20), fila('picos_paroxisticos', 0, 20)]), selection).status).toBe('unsupported');
|
||||
expect(c1AlterationFigure(datos([fila('TOTAL', 11, 20), fila('ritmo_posterior', 5, 20, { suprimido: 1 }), fila('picos_paroxisticos', 0, 20)]), selection).status).toBe('unsupported');
|
||||
expect(c1AlterationFigure(datos(), { ...selection, periodos: ['2025-S1'] }).status).toBe('unsupported');
|
||||
expect(c1AlterationFigure(datos(), { ...selection, figura: 'fig_c1_barras_edad' }).status).toBe('unsupported');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { percentNumber } from './indicadores-format';
|
||||
import { FigureHighlight } from './indicadores-highlight';
|
||||
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
|
||||
import { FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models';
|
||||
|
||||
// fig_c1_barras_alteracion: a C1 proportion whose groups are the alterations of the EEG. One bar per alteration with
|
||||
// the share of the period's children that have it, after a first bar for the children with any of them (the TOTAL
|
||||
// group). A child counts in every alteration it has, so the bars don't add up. Several periods draw side by side.
|
||||
export const C1_ALTERATION_BARS = 'fig_c1_barras_alteracion';
|
||||
const TOTAL = 'TOTAL';
|
||||
const ANY_LABEL = 'Alguna alteración';
|
||||
|
||||
export type C1AlterationResult = { status: 'unsupported'; reason: string }
|
||||
| { status: 'supported'; figure: PlotlyFigure; highlight: FigureHighlight; total: number; notes: string[] };
|
||||
export function c1AlterationCapability(contract: string, representation: string): boolean {
|
||||
return contract === 'C1' && representation === C1_ALTERATION_BARS;
|
||||
}
|
||||
|
||||
const count = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
|
||||
const escape = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
// The any-alteration bar uses the second series colour; 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] : [] };
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,161 @@
|
||||
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'],
|
||||
};
|
||||
// Olive for the event, the next series colour for its complement; age groups keep their own colours.
|
||||
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, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
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 } };
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { c2Capability, c2Descendants, c2Figure } from './indicadores-c2-adapter';
|
||||
import { c2Color, C2_PALETTE } from './indicadores-c2-palette';
|
||||
import { c2Color, C2_PALETTE, seriesColors } from './indicadores-c2-palette';
|
||||
import { c2Fixture } from './indicadores-c2-adapter.testing';
|
||||
import { FigureSelection } from './indicadores.models';
|
||||
import { donutFixture } from './indicadores-donut-drilldown.testing';
|
||||
@@ -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: '#7184A2' }, { label: 'B', color: '#A4B88A' }, { label: 'C', color: '#D0B778' },
|
||||
{ label: 'A', color: C2_PALETTE.series[0] }, { label: 'B', color: C2_PALETTE.series[1] }, { label: 'C', color: C2_PALETTE.series[2] },
|
||||
]);
|
||||
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] });
|
||||
@@ -158,15 +158,18 @@ describe('C2: datos publicados a Plotly', () => {
|
||||
});
|
||||
|
||||
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 => {
|
||||
it.each(['claro','oscuro'] as const)('sustituye tonos ajenos al logo 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', '#A4B88A', '#D0B778']);
|
||||
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual(['#D98E4A', C2_PALETTE.series[1], C2_PALETTE.series[2]]);
|
||||
expect(seriesColors(['#D98E4A', undefined, undefined])).toEqual(['#D98E4A', C2_PALETTE.series[1], C2_PALETTE.series[2]]);
|
||||
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('#7184A2'); expect(c2Color(undefined, 1)).toBe('#A4B88A');
|
||||
expect(c2Color(undefined, 2)).toBe('#D0B778'); expect(c2Color(undefined, 3)).toBe('#B78B8E');
|
||||
expect(c2Color(undefined, 0)).toBe(C2_PALETTE.series[0]); expect(c2Color(undefined, 1)).toBe(C2_PALETTE.series[1]);
|
||||
expect(c2Color(undefined, 2)).toBe(C2_PALETTE.series[2]); expect(c2Color(undefined, 3)).toBe(C2_PALETTE.series[3]);
|
||||
expect(c2Color('#D98E4A', 0)).toBe('#D98E4A');
|
||||
expect(c2Color(C2_PALETTE.edades[0], 0)).toBe(C2_PALETTE.edades[0]);
|
||||
expect(figure.config?.['responsive']).not.toBe(false); expect(figure.layout['width']).toBeUndefined();
|
||||
});
|
||||
it('mantiene contraste de texto legible y separadores suaves en ambos temas', () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { FigureSelection, IndicadorDatos, parsePeriodos, PlotlyFigure } from './indicadores.models';
|
||||
import { DonutHierarchy } from './indicadores-donut-drilldown';
|
||||
import { c2Color, c2Theme } from './indicadores-c2-palette';
|
||||
import { c2Theme, groupBase, seriesColors } from './indicadores-c2-palette';
|
||||
|
||||
export interface C2Category { id: string; label: string; parentId?: string; value: number; color?: string; }
|
||||
// Normalized presentation nodes and a selection path are independent of Plotly.
|
||||
@@ -81,7 +81,7 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
|
||||
const nodes: C2Node[] = [...parents, ...categories.map(c => ({ id: 'category:' + c.id, label: c.label, parentId: c.parentId ? 'group:' + c.parentId : undefined }))];
|
||||
const model: C2Distribution = { period, unit: data['unidad'], title: data['titulo'], categories, parents, nodes, total, notes: [...data.notas] };
|
||||
const theme = c2Theme(selection.tema), values = categories.map(c => c.value), labels = categories.map(c => c.label);
|
||||
const colors = categories.map((c, i) => c2Color(c.color, i));
|
||||
const colors = seriesColors(categories.map(c => c.color));
|
||||
const emptyMessage = !rows.length ? 'No hay filas publicadas para este periodo.' : total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined;
|
||||
const layout: Record<string, unknown> = { title: { text: model.title + ', ' + period }, autosize: true,
|
||||
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text, family: 'Roboto, sans-serif', size: 14 },
|
||||
@@ -109,7 +109,7 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
|
||||
hovertemplate: '%{label}<br>%{value} ' + model.unit + '<br>%{percent} de los ' + total + ' ' + model.unit + ' publicados<extra></extra>' }];
|
||||
if (parents.length) figure.data.push({ type: 'pie', labels: parents.map(p => p.label),
|
||||
values: parentIds.map(p => categories.filter(c => c.parentId === p).reduce((sum, c) => sum + c.value, 0)),
|
||||
marker: { colors: parents.map((_, i) => c2Color(undefined, i)), line: { color: theme.outline, width: 0.7 } },
|
||||
marker: { colors: parents.map((_, i) => groupBase(i)), line: { color: theme.outline, width: 0.7 } },
|
||||
hole: 0.55, sort: false, name: period + ', grupos', textinfo: 'none', domain: { x: [0.14, 0.58], y: [0.29, 0.71] } });
|
||||
}
|
||||
const hierarchy = selection.figura === 'fig_c2_donas' && parents.length && total > 0
|
||||
|
||||
@@ -19,7 +19,9 @@ 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: ['#A4B88A', '#D0B778'] } });
|
||||
const marker = source.data[0]['marker'] as { color: string[] }, labels = source.data[0]['y'] as string[];
|
||||
expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'],
|
||||
marker: { color: ['B', 'C'].map(label => marker.color[labels.indexOf(label)]) } });
|
||||
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');
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { C2_PALETTE, groupBase, institutionalize, isHarmoniousColor, paintByGroup, recolorFigure } from './indicadores-c2-palette';
|
||||
|
||||
describe('paleta del logo ISSSTELEON', () => {
|
||||
it('combina varios matices del logo y del verde azulado, sin repetir el mismo color', () => {
|
||||
expect(new Set(C2_PALETTE.series).size).toBe(C2_PALETTE.series.length);
|
||||
for (const color of C2_PALETTE.series) expect(isHarmoniousColor(color)).toBe(true);
|
||||
expect(institutionalize(['#a8c243'])).toEqual(['#a8c243']);
|
||||
expect(C2_PALETTE.series[0]).not.toBe(C2_PALETTE.series[1]);
|
||||
});
|
||||
|
||||
it('reemplaza mezclas de partido por entradas distintas y conserva el gris de sin dato', () => {
|
||||
const [azul, rojo, naranja, amarillo, guinda, sinDato, edad] = institutionalize([
|
||||
'#0044CC', '#C41E3A', '#FF6B00', '#FFD100', '#7A2E0E', '#C9CDD2', '#2F6DB3',
|
||||
]);
|
||||
expect([azul, rojo, naranja, amarillo, guinda]).toEqual(C2_PALETTE.series.slice(0, 5));
|
||||
expect(edad).toBe('#2F6DB3');
|
||||
expect(sinDato).toBe('#C9CDD2');
|
||||
});
|
||||
|
||||
it('da a cada grupo un matiz y a sus categorías pasos distintos de ese matiz', () => {
|
||||
const colors = paintByGroup(['benigno', 'benigno', 'benigno', 'maligno']);
|
||||
expect(new Set(colors.slice(0, 3)).size).toBe(3);
|
||||
expect(colors[3]).toBe(groupBase(1));
|
||||
expect(colors[0]).not.toBe(colors[3]);
|
||||
expect(groupBase(0)).toBe(C2_PALETTE.series[0]);
|
||||
});
|
||||
|
||||
it('pinta la tinta categórica, deja una escala continua y no toca texto ni fondo', () => {
|
||||
const figure = recolorFigure({
|
||||
data: [{
|
||||
type: 'scatter', marker: { color: '#B55A1F' }, error_x: { color: 'rgba(0,68,204,0.4)' }, line: { color: '#C9CDD2' },
|
||||
colorscale: [[0, '#0d0887'], [0.5, '#ed7953'], [1, '#f0f921']],
|
||||
}],
|
||||
layout: { font: { color: '#081839' }, paper_bgcolor: '#FFFFFF', colorway: ['#EF553B', '#636efa'] },
|
||||
});
|
||||
expect((figure.data[0]['marker'] as { color: string }).color).toBe(C2_PALETTE.series[0]);
|
||||
expect(figure.data[0]['error_x']).toMatchObject({ color: expect.stringMatching(/^rgba\(\d+,\d+,\d+,0\.4\)$/) });
|
||||
expect((figure.data[0]['error_x'] as { color: string }).color).not.toContain('0,68,204');
|
||||
expect((figure.data[0]['line'] as { color: string }).color).toBe('#C9CDD2');
|
||||
const scale = figure.data[0]['colorscale'] as [number, string][];
|
||||
expect(scale.map(stop => stop[0])).toEqual([0, 0.5, 1]);
|
||||
expect(scale[0][1]).not.toBe('#0d0887');
|
||||
expect(scale[0][1]).not.toBe(scale[1][1]);
|
||||
expect(figure.layout['font']).toEqual({ color: '#081839' });
|
||||
expect(figure.layout['paper_bgcolor']).toBe('#FFFFFF');
|
||||
expect(figure.layout['colorway']).toEqual(C2_PALETTE.series.slice(2, 4));
|
||||
expect(new Set([
|
||||
(figure.data[0]['marker'] as { color: string }).color,
|
||||
...(figure.layout['colorway'] as string[]),
|
||||
]).size).toBe(3);
|
||||
expect(recolorFigure(figure)).toBe(figure);
|
||||
});
|
||||
});
|
||||
@@ -1,15 +1,223 @@
|
||||
import { Tema } from './indicadores.models';
|
||||
import { PlotlyFigure, 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.
|
||||
// Categorical palette anchored on the logo lime (#a8c243) and the theme teal (#5f9ea0).
|
||||
// Neighboring entries differ in hue so series stay distinct, and none is a party colour:
|
||||
// no royal blue, red, orange, yellow or guinda. Neutrals stay neutral.
|
||||
// Sequential fills (heatmaps) use SCALE, from pale lime to deep teal.
|
||||
export const C2_PALETTE = Object.freeze({
|
||||
series: Object.freeze(['#7184A2', '#A4B88A', '#D0B778', '#B78B8E']),
|
||||
series: Object.freeze([
|
||||
'#5c7014', '#0e7568', '#6a6448', '#3d6b38',
|
||||
'#5a6170', '#3a5a48', '#3e5c6a', '#4a5a38',
|
||||
]),
|
||||
scale: Object.freeze(['#e4eed4', '#a8c243', '#2f6f68', '#1a3330']),
|
||||
// Age groups of the EEG indicators (M21, M22). Kept apart from the series on purpose.
|
||||
edades: Object.freeze(['#2F6DB3', '#E0A526', '#A23E8C']),
|
||||
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' }),
|
||||
});
|
||||
export function c2Theme(tema: Tema) { return C2_PALETTE[tema]; }
|
||||
export function c2Color(published: string | undefined, index: number): string {
|
||||
return published ?? C2_PALETTE.series[index % C2_PALETTE.series.length];
|
||||
const ageKeys = new Set(C2_PALETTE.edades.map(color => parseColor(color)?.key).filter((key): key is string => !!key));
|
||||
export function isAgeColor(color: string): boolean {
|
||||
const key = parseColor(color)?.key;
|
||||
return !!key && ageKeys.has(key);
|
||||
}
|
||||
export function c2Color(published: string | undefined, index: number): string {
|
||||
// A published swatch stays. The series only fills a category that arrived without one.
|
||||
if (published && (/^#[0-9a-f]{6}$/i.test(published) || isAgeColor(published))) return published;
|
||||
return C2_PALETTE.series[index % C2_PALETTE.series.length];
|
||||
}
|
||||
|
||||
/** One base hue per group, then lighter and darker steps so siblings stay related but distinct. */
|
||||
export function paintByGroup(groups: readonly string[]): string[] {
|
||||
const order = [...new Set(groups)];
|
||||
const counts = new Map(order.map(id => [id, groups.filter(g => g === id).length]));
|
||||
const stairs = new Map(order.map((id, i) => [id, steps(C2_PALETTE.series[i % C2_PALETTE.series.length], counts.get(id)!)]));
|
||||
const cursor = new Map<string, number>();
|
||||
return groups.map(id => {
|
||||
const index = cursor.get(id) ?? 0;
|
||||
cursor.set(id, index + 1);
|
||||
return stairs.get(id)![index];
|
||||
});
|
||||
}
|
||||
export function groupBase(index: number): string {
|
||||
return C2_PALETTE.series[index % C2_PALETTE.series.length];
|
||||
}
|
||||
|
||||
/** Replace inharmonious hues. Same source colour keeps the same slot; grays and palette hues stay. */
|
||||
export function institutionalize(colors: readonly string[]): string[] {
|
||||
const parsed = colors.map(parseColor);
|
||||
const foreign: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const item of parsed) {
|
||||
if (!item || item.kind !== 'foreign' || ageKeys.has(item.key) || seen.has(item.key)) continue;
|
||||
seen.add(item.key);
|
||||
foreign.push(item.key);
|
||||
}
|
||||
const assigned = new Map(foreign.map((key, i) => [key, C2_PALETTE.series[i % C2_PALETTE.series.length]]));
|
||||
return colors.map((color, i) => {
|
||||
const item = parsed[i];
|
||||
const next = item && assigned.get(item.key);
|
||||
return item && next ? formatAs(item, next) : color;
|
||||
});
|
||||
}
|
||||
|
||||
/** Keep a published colour; only a missing one takes the next series entry. */
|
||||
export function seriesColors(published: readonly (string | undefined)[]): string[] {
|
||||
return published.map((color, index) => c2Color(color, index));
|
||||
}
|
||||
|
||||
const NAMED: Record<string, [number, number, number]> = {
|
||||
black: [0, 0, 0], white: [255, 255, 255], gray: [128, 128, 128], grey: [128, 128, 128], silver: [192, 192, 192],
|
||||
red: [255, 0, 0], blue: [0, 0, 255], green: [0, 128, 0], orange: [255, 165, 0], yellow: [255, 255, 0],
|
||||
purple: [128, 0, 128], brown: [165, 42, 42], pink: [255, 192, 203], cyan: [0, 255, 255], magenta: [255, 0, 255],
|
||||
gold: [255, 215, 0], navy: [0, 0, 128], teal: [0, 128, 128], maroon: [128, 0, 0], lime: [0, 255, 0], olive: [128, 128, 0],
|
||||
};
|
||||
interface Parsed { r: number; g: number; b: number; a: number; key: string; hue: number; sat: number; lum: number; kind: 'neutral' | 'harmonious' | 'foreign'; explicitAlpha: boolean; }
|
||||
function parseColor(input: string): Parsed | undefined {
|
||||
const text = input.trim();
|
||||
let r = 0, g = 0, b = 0, a = 1, explicitAlpha = false;
|
||||
const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(text);
|
||||
const rgb = /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*([\d.]+)\s*)?\)$/i.exec(text);
|
||||
if (hex) {
|
||||
const raw = hex[1].length === 3 ? hex[1].split('').map(c => c + c).join('') : hex[1];
|
||||
r = parseInt(raw.slice(0, 2), 16); g = parseInt(raw.slice(2, 4), 16); b = parseInt(raw.slice(4, 6), 16);
|
||||
} else if (rgb) {
|
||||
r = Number(rgb[1]); g = Number(rgb[2]); b = Number(rgb[3]);
|
||||
if (rgb[4] !== undefined) { a = Number(rgb[4]); explicitAlpha = true; }
|
||||
if ([r, g, b].some(v => v > 255) || !Number.isFinite(a)) return undefined;
|
||||
} else if (NAMED[text.toLowerCase()]) {
|
||||
[r, g, b] = NAMED[text.toLowerCase()];
|
||||
} else return undefined;
|
||||
const max = Math.max(r, g, b), min = Math.min(r, g, b), d = max - min;
|
||||
const sat = max === 0 ? 0 : d / max;
|
||||
let hue = 0;
|
||||
if (d !== 0) {
|
||||
if (max === r) hue = ((g - b) / d) % 6;
|
||||
else if (max === g) hue = (b - r) / d + 2;
|
||||
else hue = (r - g) / d + 4;
|
||||
hue *= 60; if (hue < 0) hue += 360;
|
||||
}
|
||||
const lum = luminance({ r, g, b });
|
||||
const neutral = sat < 0.18;
|
||||
const harmonious = !neutral && (
|
||||
(hue >= 64 && hue <= 188 && sat >= 0.22)
|
||||
|| (hue > 188 && hue <= 230 && sat <= 0.5)
|
||||
|| (hue >= 40 && hue < 64 && sat <= 0.42));
|
||||
return { r, g, b, a, key: `${r},${g},${b}`, hue, sat, lum, explicitAlpha, kind: neutral ? 'neutral' : harmonious ? 'harmonious' : 'foreign' };
|
||||
}
|
||||
function steps(base: string, count: number): string[] {
|
||||
if (count <= 1) return [base];
|
||||
return Array.from({ length: count }, (_, i) => {
|
||||
const t = i / (count - 1);
|
||||
if (t < 0.5) return mixHex(base, [0, 0, 0], (0.5 - t) * 0.5);
|
||||
return mixHex(base, [255, 255, 255], (t - 0.5) * 0.22);
|
||||
});
|
||||
}
|
||||
function mixHex(base: string, toward: [number, number, number], amount: number): string {
|
||||
const item = parseColor(base)!;
|
||||
const channel = (from: number, to: number) => Math.round(from + (to - from) * amount);
|
||||
return '#' + [channel(item.r, toward[0]), channel(item.g, toward[1]), channel(item.b, toward[2])]
|
||||
.map(v => v.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
function sampleScale(t: number): string {
|
||||
const stops = C2_PALETTE.scale;
|
||||
const scaled = Math.min(1, Math.max(0, t)) * (stops.length - 1);
|
||||
const index = Math.min(stops.length - 2, Math.floor(scaled));
|
||||
const item = parseColor(stops[index])!, next = parseColor(stops[index + 1])!;
|
||||
return mixHex(stops[index], [next.r, next.g, next.b], scaled - index);
|
||||
}
|
||||
function luminance(input: { r: number; g: number; b: number } | Parsed): number {
|
||||
const c = [input.r, input.g, input.b].map(v => v / 255).map(v => v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4);
|
||||
return c[0] * 0.2126 + c[1] * 0.7152 + c[2] * 0.0722;
|
||||
}
|
||||
function formatAs(original: Parsed, hex: string): string {
|
||||
if (!original.explicitAlpha) return hex;
|
||||
const item = parseColor(hex)!;
|
||||
const alpha = Number(original.a.toFixed(3));
|
||||
return `rgba(${item.r},${item.g},${item.b},${alpha})`;
|
||||
}
|
||||
export function isNeutralColor(color: string): boolean { return parseColor(color)?.kind === 'neutral'; }
|
||||
export function isHarmoniousColor(color: string): boolean { return parseColor(color)?.kind === 'harmonious'; }
|
||||
|
||||
function record(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
function collectStrings(value: unknown, into: string[]) {
|
||||
if (typeof value === 'string') into.push(value);
|
||||
else if (Array.isArray(value)) {
|
||||
if (value.length === 2 && typeof value[0] === 'number' && typeof value[1] === 'string') into.push(value[1]);
|
||||
else value.forEach(item => collectStrings(item, into));
|
||||
}
|
||||
}
|
||||
function mapColors(value: unknown, lookup: Map<string, string>): unknown {
|
||||
if (typeof value === 'string') return lookup.get(value) ?? value;
|
||||
if (Array.isArray(value)) {
|
||||
if (value.length === 2 && typeof value[0] === 'number' && typeof value[1] === 'string') return [value[0], lookup.get(value[1]) ?? value[1]];
|
||||
return value.map(item => mapColors(item, lookup));
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function paintTrace(trace: Record<string, unknown>, lookup: Map<string, string>) {
|
||||
if (record(trace['marker'])) {
|
||||
const marker = { ...trace['marker'] };
|
||||
if ('color' in marker) marker['color'] = mapColors(marker['color'], lookup);
|
||||
if ('colors' in marker) marker['colors'] = mapColors(marker['colors'], lookup);
|
||||
if (record(marker['line']) && 'color' in marker['line']) marker['line'] = { ...marker['line'], color: mapColors(marker['line']['color'], lookup) };
|
||||
trace['marker'] = marker;
|
||||
}
|
||||
if (record(trace['line']) && 'color' in trace['line']) trace['line'] = { ...trace['line'], color: mapColors(trace['line']['color'], lookup) };
|
||||
if (typeof trace['fillcolor'] === 'string') trace['fillcolor'] = lookup.get(trace['fillcolor']) ?? trace['fillcolor'];
|
||||
for (const key of ['error_x', 'error_y']) {
|
||||
if (record(trace[key]) && 'color' in (trace[key] as Record<string, unknown>)) {
|
||||
trace[key] = { ...(trace[key] as Record<string, unknown>), color: mapColors((trace[key] as Record<string, unknown>)['color'], lookup) };
|
||||
}
|
||||
}
|
||||
if (Array.isArray(trace['colorscale'])) trace['colorscale'] = sequentialScale(trace['colorscale']);
|
||||
}
|
||||
function sequentialScale(stops: unknown[]): unknown[] {
|
||||
return stops.map(stop => {
|
||||
if (!Array.isArray(stop) || typeof stop[0] !== 'number' || typeof stop[1] !== 'string') return stop;
|
||||
return [stop[0], sampleScale(stop[0])];
|
||||
});
|
||||
}
|
||||
function scalePending(figure: PlotlyFigure): boolean {
|
||||
return traceList(figure).some(trace => Array.isArray(trace['colorscale'])
|
||||
&& JSON.stringify(sequentialScale(trace['colorscale'] as unknown[])) !== JSON.stringify(trace['colorscale']));
|
||||
}
|
||||
function traceList(host: { data?: unknown; frames?: unknown }): Record<string, unknown>[] {
|
||||
const traces = Array.isArray(host.data) ? host.data.filter(record) : [];
|
||||
if (Array.isArray(host.frames)) {
|
||||
for (const frame of host.frames) {
|
||||
if (record(frame) && Array.isArray(frame['data'])) traces.push(...frame['data'].filter(record));
|
||||
}
|
||||
}
|
||||
return traces;
|
||||
}
|
||||
function gather(figure: PlotlyFigure): string[] {
|
||||
const found: string[] = [];
|
||||
for (const trace of traceList(figure)) {
|
||||
const marker = record(trace['marker']) ? trace['marker'] : undefined;
|
||||
collectStrings(marker?.['color'], found); collectStrings(marker?.['colors'], found);
|
||||
collectStrings(record(marker?.['line']) ? marker['line']['color'] : undefined, found);
|
||||
collectStrings(record(trace['line']) ? trace['line']['color'] : undefined, found);
|
||||
collectStrings(trace['fillcolor'], found);
|
||||
collectStrings(record(trace['error_x']) ? trace['error_x']['color'] : undefined, found);
|
||||
collectStrings(record(trace['error_y']) ? trace['error_y']['color'] : undefined, found);
|
||||
}
|
||||
if (Array.isArray(figure.layout['colorway'])) collectStrings(figure.layout['colorway'], found);
|
||||
return found;
|
||||
}
|
||||
|
||||
/** Data ink of a published figure, without touching text, grid or background. */
|
||||
export function recolorFigure<T extends PlotlyFigure>(figure: T): T {
|
||||
const collected = gather(figure);
|
||||
const painted = institutionalize(collected);
|
||||
if (painted.every((color, i) => color === collected[i]) && !scalePending(figure)) return figure;
|
||||
const lookup = new Map(collected.map((color, i) => [color, painted[i]]));
|
||||
const copy = structuredClone(figure);
|
||||
for (const trace of traceList(copy)) paintTrace(trace, lookup);
|
||||
if (Array.isArray(copy.layout['colorway'])) copy.layout['colorway'] = mapColors(copy.layout['colorway'], lookup);
|
||||
return copy;
|
||||
}
|
||||
|
||||
@@ -59,7 +59,18 @@ 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; búsqueda y fijación prevalecen y conservan identidades y memoria', () => {
|
||||
it('EU7 primero sin alterar catálogo; selección 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.changeSearchQuery('anómala'); fixture.detectChanges();
|
||||
expect(cards()[0].indicador.id).toBe('ind1');
|
||||
page.changeSearchQuery(''); fixture.detectChanges();
|
||||
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();
|
||||
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);
|
||||
|
||||
@@ -138,8 +138,8 @@ describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => {
|
||||
'/cama/indicadores/cama_dias_resultado_diagnostico/datos?periodos=2025-S1',
|
||||
'/cama/indicadores/cama_tasa_deteccion_histopatologica/datos?periodos=2025-S1'].sort((a, b) => pedidos.indexOf(a) - pedidos.indexOf(b)));
|
||||
const titulos = paneles().map(p => [p.querySelector('h2')!.textContent, p.textContent!.includes('Integración pendiente') ? 'pendiente' : 'dibujado']);
|
||||
expect(titulos.filter(([t]) => ['Resultado histopatológico por categoría BI-RADS', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica'].includes(t!)))
|
||||
.toEqual([['Resultado histopatológico por categoría BI-RADS', 'dibujado'], ['Días del resultado de la mastografía al diagnóstico', 'dibujado'], ['Tasa de detección histopatológica', 'dibujado']]);
|
||||
expect(titulos.filter(([t]) => ['Resultado histopatológico', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica'].includes(t!)))
|
||||
.toEqual([['Resultado histopatológico', 'dibujado'], ['Días del resultado de la mastografía al diagnóstico', 'dibujado'], ['Tasa de detección histopatológica', 'dibujado']]);
|
||||
expect(graficas()).toHaveLength(3);
|
||||
expect(graficas().map(g => g.figure!.data.length)).toEqual([6, 2, 2]);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
// What this module covers: CaMa's eight FHIR measures as the page reads them: their ids, catalog entries, category
|
||||
// metadata, the rows of each contract (C1, C2, C3r) and what the summary's cards and figures make of them, for periods
|
||||
// with data and for periods that legitimately have none.
|
||||
// Fixtures (`fixtures/cama_fhir_*.json`): `reportes` are real `GET /cama/fhir/MeasureReport` answers of the local
|
||||
// installation, cut to three semesters (2021-S1 without units, 2024-S2 and 2025-S2 with them) and two months;
|
||||
// `measures` is the Measure bundle the WebApi serves from the current dbt definitions; `measures_instalada` is the one
|
||||
// the installation served before the category metadata existed.
|
||||
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, categorias, datosDeReportes, FhirIndicadoresService, indicadorDeMeasure, indicadorId, Measure, metadatosDeMeasure, Report } from './indicadores-fhir';
|
||||
import { CAMA_MEASURE_IDS } from './indicadores-cama-fhir';
|
||||
import { c2Figure } from './indicadores-c2-adapter';
|
||||
import { modelosConteos, parConteos, totalExamenes } from './indicadores-conteos-pareados';
|
||||
import { CAMA_CONFIRMACION_KPI, CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_TOMA_DIAGNOSTICO_KPI, KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadorDatos, TipoPeriodo } from './indicadores.models';
|
||||
import { datosValidos } from './indicadores.service';
|
||||
import measuresData from './fixtures/cama_fhir_measures.json';
|
||||
import installedData from './fixtures/cama_fhir_measures_instalada.json';
|
||||
import reportsData from './fixtures/cama_fhir_reportes.json';
|
||||
|
||||
const measures = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
|
||||
const installed = resources(installedData as unknown as Bundle, 'Measure') as Measure[];
|
||||
const answers = reportsData.reports as unknown as Record<string, { semestre: Bundle; mes?: Bundle }>;
|
||||
const measure = (fhirId: string, from = measures) => from.find(m => m.id === fhirId)!;
|
||||
const reportsOf = (fhirId: string, tipo: TipoPeriodo, start: string) =>
|
||||
(resources(answers[fhirId][tipo]!, 'MeasureReport') as Report[]).filter(r => r.period?.start === start);
|
||||
const apply = (periodo: string, tipo: TipoPeriodo = 'semestre'): GlobalApplied =>
|
||||
({ tipo, selection: { mode: 'explicit', periodos: [periodo] }, revision: 0 });
|
||||
function datos(fhirId: string, start: string, periodo: string, tipo: TipoPeriodo = 'semestre', from = measures): IndicadorDatos {
|
||||
return datosValidos(datosDeReportes(measure(fhirId, from), reportsOf(fhirId, tipo, start), tipo), indicadorId(fhirId), tipo, [periodo]);
|
||||
}
|
||||
const SEMESTRE_VACIO = ['2021-01-01', '2021-S1'] as const;
|
||||
const SEMESTRE_CON_DATOS = ['2025-07-01', '2025-S2'] as const;
|
||||
|
||||
describe('Identificadores de CaMa entre FHIR y la página', () => {
|
||||
it('cada Measure publicada tiene un id de la página y ninguno se repite', () => {
|
||||
// Pins down: the explicit table covers the eight measures the WebApi publishes and the page ids stay unique
|
||||
// (`BIRADS456` is `birads_456`, which no rule derives). Fails if a measure is published without a
|
||||
// correspondence, or two measures collapse into one page id.
|
||||
const ids = measures.map(m => indicadorId(m.id!));
|
||||
expect(ids.sort()).toEqual(['cama_biopsias', 'cama_birads', 'cama_birads_456_mastografia', 'cama_birads_456_paciente',
|
||||
'cama_birads_cancer_invasor', 'cama_confirmacion_birads45', 'cama_dias_resultado_diagnostico', 'cama_dias_toma_diagnostico',
|
||||
'cama_eu38a', 'cama_histopatologia_birads', 'cama_tasa_deteccion_histopatologica']);
|
||||
expect(new Set(ids).size).toBe(measures.length);
|
||||
expect(measures.every(m => Object.hasOwn(CAMA_MEASURE_IDS, m.id!))).toBe(true);
|
||||
});
|
||||
|
||||
it('el id de una medida de otro dominio sigue la regla general', () => {
|
||||
// Pins down: only CaMa's measures use the table; TEA's and CaCu's keep `-` to `_`. Fails if the table captures
|
||||
// ids of other domains or the generic rule changes.
|
||||
expect(indicadorId('M21-diagnosticados-con-eeg')).toBe('M21_diagnosticados_con_eeg');
|
||||
expect(indicadorId('CACU-EU7')).toBe('CACU_EU7');
|
||||
});
|
||||
|
||||
it('el catálogo lleva contrato, figuras y periodos de cada medida', () => {
|
||||
// Pins down: the contract, the figures and the period types each CaMa measure publishes: a distribution offers
|
||||
// the donut and the bars, a duration its box plot, a proportion none (its history is drawn from the data rows).
|
||||
// Fails if the dbt definitions stop declaring them or the mapper drops them.
|
||||
const catalog = Object.fromEntries(measures.map(m => [indicadorId(m.id!), indicadorDeMeasure(m)]));
|
||||
expect(catalog['cama_birads_456_paciente']).toMatchObject({ contrato: 'C2', figuras: ['fig_c2_donas', 'fig_c2_barras'], tipos_periodo: ['semestre', 'mes'], estratos: [] });
|
||||
expect(catalog['cama_biopsias']).toMatchObject({ contrato: 'C2', figuras: ['fig_c2_donas', 'fig_c2_barras'] });
|
||||
expect(catalog['cama_confirmacion_birads45']).toMatchObject({ contrato: 'C1', figuras: [], sentido: 'mayor_mejor' });
|
||||
expect(catalog['cama_eu38a']).toMatchObject({ contrato: 'C3r', figuras: ['fig_c3r_caja'], sentido: 'menor_mejor' });
|
||||
expect(catalog['cama_dias_toma_diagnostico']).toMatchObject({ contrato: 'C3r', figuras: ['fig_c3r_caja'] });
|
||||
expect(catalog['cama_birads_cancer_invasor']).toMatchObject({ contrato: 'C2', estratos: ['grupo_edad', 'estadio', 'etapa', 'clasificacion', 'tamano'] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('Ficha técnica de CaMa', () => {
|
||||
it('cada medida tiene su propio código y sus poblaciones con la métrica que las cuenta', () => {
|
||||
// Pins down: the sheet's code is the measure's name without the domain (not `CAMA` for all eight) and each
|
||||
// population names the dbt metric that counts it. Fails if the sheets of different measures read alike.
|
||||
const codes = measures.map(m => metadatosDeMeasure(m).ficha!.codigo);
|
||||
expect(new Set(codes).size).toBe(measures.length);
|
||||
expect(metadatosDeMeasure(measure('CAMA-EU38A')).ficha!.codigo).toBe('EU38A');
|
||||
expect(metadatosDeMeasure(measure('CAMA-BIRADS456-PACIENTE')).ficha!.codigo).toBe('BIRADS456-PACIENTE');
|
||||
expect(metadatosDeMeasure(measure('CAMA-CONFIRMACION-BIRADS45')).poblaciones!.map(p => p.grupo)).toEqual(['poblacion', 'denominador', 'numerador']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Categorías de las composiciones de CaMa', () => {
|
||||
it('BI-RADS 4 a 6 declara solo sus subcategorías y BI-RADS completo añade «Sin dato»', () => {
|
||||
// Pins down: the labels and colours come from the Measure's extensions, in the order of the catalog, and the
|
||||
// exams' and patients' measures declare the same categories. Fails if the dbt labels drift or one measure loses them.
|
||||
expect(Object.keys(categorias(measure('CAMA-BIRADS456-PACIENTE')))).toEqual(['B4A', 'B4B', 'B4C', 'B5', 'B6']);
|
||||
expect(categorias(measure('CAMA-BIRADS456-MASTOGRAFIA'))).toEqual(categorias(measure('CAMA-BIRADS456-PACIENTE')));
|
||||
expect(Object.keys(categorias(measure('CAMA-BIRADS')))).toEqual(['B0', 'B1', 'B2', 'B3', 'B4A', 'B4B', 'B4C', 'B5', 'B6', 'SIN_DATO']);
|
||||
expect(categorias(measure('CAMA-BIRADS'))['B5']).toEqual({ etiqueta: 'BI-RADS 5', color: '#B55A1F', grupo: null });
|
||||
expect(Object.keys(categorias(measure('CAMA-BIOPSIAS')))).toEqual(['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'SIN_DATO']);
|
||||
});
|
||||
|
||||
it('un BI-RADS 4 sin subcategoría se muestra después de las categorías declaradas y no se pierde', () => {
|
||||
// Pins down: the real 2025-S2 report counts patients in `B4`, which no Measure declares. The rows add it after the
|
||||
// declared categories under the Core catalog's caption, and the total is still the report's units. Fails if
|
||||
// undeclared categories are dropped (the card would show fewer patients than the report counts).
|
||||
const periodo = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS);
|
||||
expect(Object.keys(periodo['categorias'] as object)).toEqual(['B4A', 'B4B', 'B4C', 'B5', 'B6', 'B4']);
|
||||
expect((periodo['categorias'] as Record<string, { etiqueta: string }>)['B4'].etiqueta).toBe('BI-RADS 4 (sin subcategoría)');
|
||||
const total = periodo.filas.reduce((sum, row) => sum + (row['n'] as number), 0);
|
||||
expect(total).toBe(36);
|
||||
expect(periodo.filas.map(row => [row['categoria'], row['orden']])).toEqual([['B4A', 0], ['B4B', 1], ['B4C', 2], ['B5', 3], ['B6', 4], ['B4', 5]]);
|
||||
});
|
||||
|
||||
it('una Measure sin metadatos de categoría deja ver las categorías con su código, sin perder unidades', () => {
|
||||
// Pins down: against the Measure the installation served before the labels existed (no category extensions),
|
||||
// every counted category is still listed (by its code) and the figure still draws the whole partition. Fails if a
|
||||
// Measure without metadata makes the distribution empty or undercounts it.
|
||||
const periodo = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS, 'semestre', installed);
|
||||
expect(Object.keys(periodo['categorias'] as object)).toEqual(['B4', 'B5', 'B6']);
|
||||
const result = c2Figure(periodo, { dominio: 'cama', indicador: 'cama_birads_456_paciente', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] });
|
||||
if (result.status !== 'supported') throw new Error(result.reason);
|
||||
expect(result.model.total).toBe(36);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Composiciones (C2): BI-RADS y biopsias', () => {
|
||||
it.each(['CAMA-BIRADS456-PACIENTE', 'CAMA-BIRADS456-MASTOGRAFIA', 'CAMA-BIRADS', 'CAMA-BIOPSIAS'])('%s se dibuja como dona y como barras con el total de sus unidades', fhirId => {
|
||||
// Pins down: for a period with units, both published figures are supported and the total equals the report's
|
||||
// `initial-population`. Fails if a category, a label or the unit total is lost between the report and the figure.
|
||||
const periodo = datos(fhirId, ...SEMESTRE_CON_DATOS);
|
||||
const units = reportsOf(fhirId, 'semestre', SEMESTRE_CON_DATOS[0])[0].group![0].population!.find(p => p.code?.coding?.[0].code === 'initial-population')!.count!;
|
||||
for (const figura of ['fig_c2_donas', 'fig_c2_barras']) {
|
||||
const result = c2Figure(periodo, { dominio: 'cama', indicador: indicadorId(fhirId), figura, tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] });
|
||||
if (result.status !== 'supported') throw new Error(`${fhirId} ${figura}: ${result.reason}`);
|
||||
expect(result.model.total).toBe(units);
|
||||
expect(result.model.total).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
it('todas las composiciones de CaMa de los reportes reales suman las unidades de su periodo', () => {
|
||||
// Pins down: for every C2 measure and every real period in the fixtures (semesters and months), the categories the
|
||||
// mapper lists add up to the report's units, so none is dropped. Fails if a report counts a category the rows lose.
|
||||
// The three measures of L3 have their own fixture (`indicadores-cama-l3.spec.ts`).
|
||||
for (const m of measures.filter(item => indicadorDeMeasure(item).contrato === 'C2' && Object.hasOwn(answers, item.id!))) {
|
||||
for (const tipo of ['semestre', 'mes'] as const) {
|
||||
const bundle = answers[m.id!][tipo];
|
||||
if (!bundle) continue;
|
||||
const reports = resources(bundle, 'MeasureReport') as Report[];
|
||||
const rows = datosDeReportes(m, reports, tipo).filas;
|
||||
for (const report of reports) {
|
||||
const units = report.group![0].population!.find(p => p.code?.coding?.[0].code === 'initial-population')!.count!;
|
||||
const label = report.period!.start;
|
||||
const total = rows.filter(row => row['periodo'] === (tipo === 'mes' ? label.slice(0, 7) : label.slice(0, 4) + (label.slice(5, 7) < '07' ? '-S1' : '-S2'))).reduce((sum, row) => sum + (row['n'] as number), 0);
|
||||
expect(total, `${m.id} ${label}`).toBe(units);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('un periodo sin unidades da una distribución vacía, no un error', () => {
|
||||
// Pins down: a semester without mammograms (legitimate absence of data) is a supported figure with the
|
||||
// «conteos en cero» message and every category at zero. Fails if an empty period turns into an unsupported figure.
|
||||
const periodo = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_VACIO);
|
||||
const result = c2Figure(periodo, { dominio: 'cama', indicador: 'cama_birads_456_paciente', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2021-S1'] });
|
||||
if (result.status !== 'supported') throw new Error(result.reason);
|
||||
expect(result.model.total).toBe(0);
|
||||
expect(result.emptyMessage).toContain('cero');
|
||||
expect(periodo.filas.every(row => row['n'] === 0)).toBe(true);
|
||||
});
|
||||
|
||||
it('la tarjeta de pacientes BI-RADS 4, 5 y 6 suma las categorías del periodo', () => {
|
||||
// Pins down: the opportunity card reads the patients' distribution: its value is the sum of the categories
|
||||
// (including the undeclared B4) and the card says «Disponible». Fails if the card still sees the catalog without B4.
|
||||
const result = kpiResult(datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS), KPI_BY_DOMAIN.cama[0], 'cama', apply('2025-S2'));
|
||||
expect(result).toMatchObject({ state: 'Disponible', value: 36 });
|
||||
expect(Object.values(result.categorias!).reduce((a, b) => a + b, 0)).toBe(36);
|
||||
});
|
||||
|
||||
it('un mes con datos se lee igual que un semestre', () => {
|
||||
// Pins down: the monthly search answers by `periodo` labels like `2025-12`, and the rows carry that label. Fails
|
||||
// if the month's period is read as a semester or the categories are lost.
|
||||
const periodo = datos('CAMA-BIRADS456-PACIENTE', '2025-12-01', '2025-12', 'mes');
|
||||
expect(periodo.tipo_periodo).toBe('mes');
|
||||
expect(periodo.periodos).toEqual(['2025-12']);
|
||||
expect(periodo.filas.reduce((sum, row) => sum + (row['n'] as number), 0)).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('las biopsias suman por grado histológico con los rótulos del catálogo', () => {
|
||||
// Pins down: the grades arrive as `BENIGNO`, `CARCINOMA_IN_SITU` and `CARCINOMA_INVASOR` and are drawn with the
|
||||
// catalog's captions. Fails if a grade loses its caption or is merged into another.
|
||||
const periodo = datos('CAMA-BIOPSIAS', ...SEMESTRE_CON_DATOS);
|
||||
const labels = Object.fromEntries(Object.entries(periodo['categorias'] as Record<string, { etiqueta: string }>).map(([k, v]) => [k, v.etiqueta]));
|
||||
expect(labels).toEqual({ BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ', CARCINOMA_INVASOR: 'Carcinoma invasor', SIN_DATO: 'Sin dato' });
|
||||
expect(Object.fromEntries(periodo.filas.map(row => [row['categoria'], row['n']]))).toEqual({ BENIGNO: 11, CARCINOMA_IN_SITU: 1, CARCINOMA_INVASOR: 13, SIN_DATO: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('Proporción (C1): confirmación histopatológica', () => {
|
||||
it('el grupo principal llega a la página como `total` con numerador, denominador y porcentaje', () => {
|
||||
// Pins down: the WebApi's `principal` group is the page's `total`, and the score becomes a percentage next to
|
||||
// its numerator and denominator. Fails if the group keeps its FHIR name (the card would find no rows).
|
||||
const periodo = datos('CAMA-CONFIRMACION-BIRADS45', ...SEMESTRE_CON_DATOS);
|
||||
expect(periodo['grupos']).toEqual({ total: 'Total' });
|
||||
expect(periodo.filas).toEqual([expect.objectContaining({ grupo: 'total', numerador: 28, denominador: 37, valor: 75.7, suprimido: 0 })]);
|
||||
expect(kpiResult(periodo, CAMA_CONFIRMACION_KPI, 'cama', apply('2025-S2'))).toMatchObject({ state: 'Disponible', value: '75.7',
|
||||
info: '28 de 37 mastografías BI-RADS 4 y 5 con reporte de biopsia.' });
|
||||
});
|
||||
|
||||
it('un periodo sin mastografías de sospecha no muestra un porcentaje', () => {
|
||||
// Pins down: denominator zero and no score is «Sin valor disponible», never 0 %. Fails if an empty period is
|
||||
// drawn as a measured zero.
|
||||
const periodo = datos('CAMA-CONFIRMACION-BIRADS45', ...SEMESTRE_VACIO);
|
||||
expect(periodo.filas[0]).toMatchObject({ grupo: 'total', numerador: 0, denominador: 0, valor: null });
|
||||
expect(kpiResult(periodo, CAMA_CONFIRMACION_KPI, 'cama', apply('2021-S1')).state).toBe('Sin valor disponible');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Duraciones (C3r): tiempos de CaMa', () => {
|
||||
it('toma a resultado da mediana, cuartiles y número de mastografías', () => {
|
||||
// Pins down: median 8 days with Q1 4 and Q3 12 over 101 mammograms for 2025-S2, and the card shows them. Fails if the
|
||||
// quartiles or the observation count stop coming from the report's extensions and populations.
|
||||
const periodo = datos('CAMA-EU38A', ...SEMESTRE_CON_DATOS);
|
||||
expect(periodo.filas[0]).toMatchObject({ grupo: 'TOTAL', n: 101, mediana: 8, q1: 4, q3: 12, n_sin_evento: 0, unidad: 'dias' });
|
||||
expect(kpiResult(periodo, CAMA_TAMIZAJE_RESULTADO_KPI, 'cama', apply('2025-S2'))).toMatchObject({ state: 'Disponible', value: 8,
|
||||
info: '101 mastografías; Q1 a Q3: 4 a 12 días.' });
|
||||
});
|
||||
|
||||
it('tamizaje a diagnóstico separa las mastografías medidas de las que no tienen diagnóstico', () => {
|
||||
// Pins down: 55 measured and 43 without a diagnosis by the cut-off (FHIR's population exclusion), median 60 days.
|
||||
// Fails if the unmeasured units are counted as observations or lost.
|
||||
const periodo = datos('CAMA-DIAS-TOMA-DIAGNOSTICO', ...SEMESTRE_CON_DATOS);
|
||||
expect(periodo.filas[0]).toMatchObject({ n: 55, n_sin_evento: 43, mediana: 60, q1: 41.5, q3: 131.5 });
|
||||
expect(kpiResult(periodo, CAMA_TOMA_DIAGNOSTICO_KPI, 'cama', apply('2025-S2'))).toMatchObject({ state: 'Disponible', value: 60 });
|
||||
});
|
||||
|
||||
it('un periodo sin mastografías no tiene mediana', () => {
|
||||
// Pins down: zero observations and no score is «Sin valor disponible», not a median of 0 days. Fails if an empty
|
||||
// period is shown as an instant result.
|
||||
const periodo = datos('CAMA-EU38A', ...SEMESTRE_VACIO);
|
||||
expect(periodo.filas[0]).toMatchObject({ n: 0, mediana: null });
|
||||
expect(kpiResult(periodo, CAMA_TAMIZAJE_RESULTADO_KPI, 'cama', apply('2021-S1')).state).toBe('Sin valor disponible');
|
||||
});
|
||||
|
||||
it('la caja de cuartiles se dibuja con los semestres que tienen mediana', () => {
|
||||
// Pins down: the box plot keeps the periods with a median and leaves out the empty one. Fails if an empty
|
||||
// period becomes a box at zero.
|
||||
const reports = ['2021-01-01', '2024-07-01', '2025-07-01'].flatMap(start => reportsOf('CAMA-EU38A', 'semestre', start));
|
||||
const figure = cajaDeDatos(datosValidos(datosDeReportes(measure('CAMA-EU38A'), reports, 'semestre'), 'cama_eu38a', 'semestre'));
|
||||
expect((figure.data[0] as Record<string, unknown>)['x']).toEqual(['2024-S2', '2025-S2']);
|
||||
expect((figure.data[0] as Record<string, unknown>)['median']).toEqual([7.5, 8]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Servicio FHIR sobre CaMa', () => {
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), FhirIndicadoresService] });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => http.verify());
|
||||
|
||||
it('pide por el id de la página y consulta la medida por su canónico', async () => {
|
||||
// Pins down: the page asks for `cama_birads_456_paciente` and the WebApi receives the canonical of
|
||||
// `CAMA-BIRADS456-PACIENTE` with the periods asked for. Fails if the page id is sent as the measure or the table is bypassed.
|
||||
const service = TestBed.inject(FhirIndicadoresService);
|
||||
const answer = firstValueFrom(service.datos('cama', 'cama_birads_456_paciente', 'semestre', ['2025-S2']));
|
||||
http.expectOne('/cama/fhir/Measure').flush(measuresData);
|
||||
const request = http.expectOne(r => r.url === '/cama/fhir/MeasureReport');
|
||||
expect(request.request.params.get('measure')).toBe('https://isssteleon.org/fhir/Measure/CAMA-BIRADS456-PACIENTE');
|
||||
expect(request.request.params.get('periodo')).toBe('2025-S2');
|
||||
request.flush({ ...answers['CAMA-BIRADS456-PACIENTE'].semestre, entry: reportsOf('CAMA-BIRADS456-PACIENTE', 'semestre', '2025-07-01').map(resource => ({ resource })) });
|
||||
expect((await answer).id).toBe('cama_birads_456_paciente');
|
||||
});
|
||||
|
||||
it('el catálogo de CaMa publica los ocho ids de la página', async () => {
|
||||
// Pins down: the catalog the page receives lists the correspondence ids, so its filters and cards find them.
|
||||
// Fails if a measure reaches the page under its FHIR id.
|
||||
const answer = firstValueFrom(TestBed.inject(FhirIndicadoresService).catalogo('cama'));
|
||||
http.expectOne('/cama/fhir/Measure').flush(measuresData);
|
||||
expect((await answer).map(item => item.id).sort()).toEqual(Object.values(CAMA_MEASURE_IDS).sort());
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tarjeta pareada de mastografías y pacientes BI-RADS 4, 5 y 6', () => {
|
||||
const models = (examenes: IndicadorDatos, pacientes: IndicadorDatos) => modelosConteos(parConteos('cama', 'cama_birads_456_mastografia')!, examenes, pacientes, 'semestre');
|
||||
|
||||
it('con datos reales del semestre da los conteos por categoría de ambas medidas', () => {
|
||||
// Pins down: the page's pair reads the two real C2 answers (units `examen` and `paciente`, version 0.2.0 of the
|
||||
// patients' measure) and gives the exams by category and the patients by BI-RADS family. Fails if an id, a unit or
|
||||
// a category of either measure stops matching what the pair checks.
|
||||
const [model] = models(datos('CAMA-BIRADS456-MASTOGRAFIA', ...SEMESTRE_CON_DATOS), datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS));
|
||||
expect(model.pacientesVerificados).toBe(true);
|
||||
expect(totalExamenes(model)).toBe(39);
|
||||
expect(model.filas.map(f => f.pacientes)).toEqual([14, 20, 2]);
|
||||
expect(model.filas.map(f => f.examenes)).toEqual([16, 21, 2]);
|
||||
});
|
||||
|
||||
it('un periodo sin BI-RADS 4 sin subcategoría cuenta cero en esa categoría y no rompe la tarjeta', () => {
|
||||
// Pins down: `B4` is published only when some report counts it; a period set without it leaves the card
|
||||
// working, with zero exams in that category. The reports are the real 2025-S2 ones with the `B4` stratum removed
|
||||
// and the units reduced by its count. Fails if the card turns «categorías no coinciden» whenever no 4 arrives unqualified.
|
||||
const without = (fhirId: string) => {
|
||||
const [report] = reportsOf(fhirId, 'semestre', '2025-07-01');
|
||||
const group = report.group![0];
|
||||
const removed = group.stratifier![0].stratum!.find(s => s.value?.coding?.[0].code === 'B4')!.population![0].count!;
|
||||
const units = group.population!.map(p => p.code?.coding?.[0].code === 'initial-population' ? { ...p, count: p.count! - removed } : p);
|
||||
const stratifier = [{ ...group.stratifier![0], stratum: group.stratifier![0].stratum!.filter(s => s.value?.coding?.[0].code !== 'B4') }];
|
||||
const copy = { ...report, group: [{ ...group, population: units, stratifier }] } as Report;
|
||||
return datosValidos(datosDeReportes(measure(fhirId), [copy], 'semestre'), indicadorId(fhirId), 'semestre', ['2025-S2']);
|
||||
};
|
||||
const [model] = models(without('CAMA-BIRADS456-MASTOGRAFIA'), without('CAMA-BIRADS456-PACIENTE'));
|
||||
expect(model.examenes.find(c => c.id === 'B4')!.n).toBe(0);
|
||||
expect(model.filas.map(f => f.examenes)).toEqual([0, 21, 2]);
|
||||
expect(model.filas.map(f => f.pacientes)).toEqual([0, 20, 2]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
// How CaMa's FHIR measures map onto what the indicator page reads: the page's id of each measure, the name of a
|
||||
// proportion's primary group and the categories a composition publishes beyond its declared ones.
|
||||
//
|
||||
// The WebApi names a measure `CAMA-BIRADS456-PACIENTE`; the page, its history and its cards use
|
||||
// `cama_birads_456_paciente`. A rule can't derive one from the other (`BIRADS456` splits into `birads_456`), so the
|
||||
// correspondence is explicit and a measure outside it keeps the generic rule.
|
||||
export const CAMA_MEASURE_IDS: Readonly<Record<string, string>> = {
|
||||
'CAMA-BIOPSIAS': 'cama_biopsias',
|
||||
'CAMA-BIRADS': 'cama_birads',
|
||||
'CAMA-BIRADS-CANCER-INVASOR': 'cama_birads_cancer_invasor',
|
||||
'CAMA-BIRADS456-MASTOGRAFIA': 'cama_birads_456_mastografia',
|
||||
'CAMA-BIRADS456-PACIENTE': 'cama_birads_456_paciente',
|
||||
'CAMA-CONFIRMACION-BIRADS45': 'cama_confirmacion_birads45',
|
||||
'CAMA-DIAS-RESULTADO-DIAGNOSTICO': 'cama_dias_resultado_diagnostico',
|
||||
'CAMA-DIAS-TOMA-DIAGNOSTICO': 'cama_dias_toma_diagnostico',
|
||||
'CAMA-EU38A': 'cama_eu38a',
|
||||
'CAMA-HISTOPATOLOGIA-BIRADS': 'cama_histopatologia_birads',
|
||||
'CAMA-TASA-DETECCION-HISTOPATOLOGICA': 'cama_tasa_deteccion_histopatologica',
|
||||
};
|
||||
|
||||
export const esMedidaCama = (measureId: string | undefined): boolean =>
|
||||
measureId !== undefined && Object.hasOwn(CAMA_MEASURE_IDS, measureId);
|
||||
|
||||
// A proportion's primary group is `principal` in the WebApi; CaMa's page names it `total`.
|
||||
export const GRUPO_PRINCIPAL_PAGINA = 'total';
|
||||
export const GRUPO_PRINCIPAL_FHIR = 'principal';
|
||||
|
||||
// A category a report counts that its Measure doesn't declare (a BI-RADS 4 without subcategory arrives as `B4`) is
|
||||
// shown after the declared ones under the caption the Core catalog gives it.
|
||||
export const ETIQUETA_CATEGORIA_NO_DECLARADA: Readonly<Record<string, string>> = { B4: 'BI-RADS 4 (sin subcategoría)' };
|
||||
|
||||
// The histopathological result by BI-RADS (`CAMA-HISTOPATOLOGIA-BIRADS`) publishes the cross of two stratifiers, the
|
||||
// BI-RADS of the mammogram and the grade of its biopsy, as FHIR codes (`B4A`, `CARCINOMA_IN_SITU`); the view that
|
||||
// draws it reads the page's codes. The correspondence is explicit, one table per axis, so a code outside it is an error
|
||||
// and never a silent zero. A grade is benign or malignant as the parameter `cama.biopsia_cancer` says; no biopsy and
|
||||
// no grade belong to no group.
|
||||
export const ESTRATO_BIRADS_PAGINA: Readonly<Record<string, string>> = {
|
||||
B4: 'BIRADS_4', B4A: 'BIRADS_4A', B4B: 'BIRADS_4B', B4C: 'BIRADS_4C', B5: 'BIRADS_5', B6: 'BIRADS_6',
|
||||
};
|
||||
export const CATEGORIA_HISTOPATOLOGIA_PAGINA: Readonly<Record<string, { id: string; grupo: string | null; gravedad: number | null }>> = {
|
||||
BENIGNO: { id: 'BENIGNO', grupo: 'NO_MALIGNO', gravedad: 1 },
|
||||
CARCINOMA_IN_SITU: { id: 'IN_SITU', grupo: 'MALIGNO', gravedad: 3 },
|
||||
CARCINOMA_INVASOR: { id: 'INVASOR', grupo: 'MALIGNO', gravedad: 4 },
|
||||
SIN_BIOPSIA: { id: 'SIN_BIOPSIA', grupo: null, gravedad: null },
|
||||
SIN_DATO: { id: 'SIN_DATO', grupo: 'SIN_DATO', gravedad: null },
|
||||
};
|
||||
export const GRUPOS_HISTOPATOLOGIA_PAGINA: Readonly<Record<string, string>> = { NO_MALIGNO: 'No maligno', MALIGNO: 'Maligno', SIN_DATO: 'Sin dato' };
|
||||
@@ -0,0 +1,242 @@
|
||||
// What this module covers: the three CaMa measures of L3 as the page reads them from FHIR: the detection rate (C1), the
|
||||
// time from the mammogram's result to the diagnosis (C3r) and the histopathological result by BI-RADS (C2 stratified by
|
||||
// BI-RADS): their ids, catalog entries, numerators and denominators, medians, the BI-RADS by result matrix, the periods
|
||||
// with no data and the reports that don't add up.
|
||||
// Fixtures: `fixtures/cama_fhir_measures.json` (the Measure bundle the WebApi serves from the current dbt definitions) and
|
||||
// `fixtures/cama_fhir_l3_reportes.json` (real `GET /cama/fhir/MeasureReport` answers over a read-only copy of the data of
|
||||
// the 18092 installation, with L3's views applied on the copy), cut to six semesters and three months. The semesters:
|
||||
// 2021-S1 (no data), 2024-S2, 2025-S1, 2025-S2, 2026-S1 and 2026-S2 (the one the cut-off cuts).
|
||||
import { Bundle, resources } from './fhir';
|
||||
import { datosDeReportes, indicadorDeMeasure, indicadorId, Measure, metadatosDeMeasure, Report } from './indicadores-fhir';
|
||||
import { CAMA_MEASURE_IDS } from './indicadores-cama-fhir';
|
||||
import { CAMA_RESULTADO_DIAGNOSTICO_KPI, CAMA_TASA_DETECCION_KPI, kpiResult } from './indicadores-kpi';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadorDatos, TipoPeriodo } from './indicadores.models';
|
||||
import { datosValidos } from './indicadores.service';
|
||||
import { etiquetaPeriodo, historicoFigura } from './indicadores-historico-figures';
|
||||
import { ESTRATOS_BIRADS, modeloHistopatologia, periodosHistopatologia, seleccionBase, tasas } from './indicadores-histopatologia-cama';
|
||||
import measuresData from './fixtures/cama_fhir_measures.json';
|
||||
import l3Data from './fixtures/cama_fhir_l3_reportes.json';
|
||||
|
||||
const measures = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
|
||||
const answers = l3Data.reports as unknown as Record<string, { semestre: Bundle; mes: Bundle }>;
|
||||
const TASA = 'CAMA-TASA-DETECCION-HISTOPATOLOGICA', DIAS = 'CAMA-DIAS-RESULTADO-DIAGNOSTICO', HISTO = 'CAMA-HISTOPATOLOGIA-BIRADS';
|
||||
const measure = (fhirId: string) => measures.find(m => m.id === fhirId)!;
|
||||
const reportsOf = (fhirId: string, tipo: TipoPeriodo, start?: string) =>
|
||||
(resources(answers[fhirId][tipo], 'MeasureReport') as Report[]).filter(r => !start || r.period?.start === start);
|
||||
const apply = (periodo: string, tipo: TipoPeriodo = 'semestre'): GlobalApplied =>
|
||||
({ tipo, selection: { mode: 'explicit', periodos: [periodo] }, revision: 0 });
|
||||
function datos(fhirId: string, start: string, periodo: string, tipo: TipoPeriodo = 'semestre', scope = {}): IndicadorDatos {
|
||||
return datosDeReportes(measure(fhirId), reportsOf(fhirId, tipo, start), tipo, scope);
|
||||
}
|
||||
const SEMESTRES = [['2025-01-01', '2025-S1'], ['2025-07-01', '2025-S2'], ['2026-01-01', '2026-S1'], ['2026-07-01', '2026-S2']] as const;
|
||||
const BIRADS_PACIENTES_2025_S2 = 36;
|
||||
|
||||
describe('Las tres medidas de L3 en el catálogo', () => {
|
||||
it('cada una tiene su id de página, su contrato y su sentido', () => {
|
||||
// Pins down: the explicit table names the three, none collides with another, and the catalog gives each its contract
|
||||
// (a proportion, a duration with its box plot, a composition stratified by BI-RADS). Fails if a measure is published
|
||||
// without a correspondence or its contract drifts.
|
||||
expect(indicadorId(TASA)).toBe('cama_tasa_deteccion_histopatologica');
|
||||
expect(indicadorId(DIAS)).toBe('cama_dias_resultado_diagnostico');
|
||||
expect(indicadorId(HISTO)).toBe('cama_histopatologia_birads');
|
||||
expect([TASA, DIAS, HISTO].every(id => Object.hasOwn(CAMA_MEASURE_IDS, id))).toBe(true);
|
||||
const catalogo = Object.fromEntries(measures.map(m => [indicadorId(m.id!), indicadorDeMeasure(m)]));
|
||||
expect(catalogo['cama_tasa_deteccion_histopatologica']).toMatchObject({ contrato: 'C1', figuras: [], unidad: 'examen', tipos_periodo: ['semestre', 'mes'] });
|
||||
expect(catalogo['cama_dias_resultado_diagnostico']).toMatchObject({ contrato: 'C3r', figuras: ['fig_c3r_caja'], sentido: 'menor_mejor' });
|
||||
expect(catalogo['cama_histopatologia_birads']).toMatchObject({ contrato: 'C2', estratos: ['birads'], unidad: 'paciente' });
|
||||
expect(new Set(measures.map(m => indicadorId(m.id!))).size).toBe(measures.length);
|
||||
});
|
||||
|
||||
it('la ficha de cada una dice qué cuenta y qué no es', () => {
|
||||
// Pins down: the description is the measure's definition: the detection rate is of biopsy reports and says it is not a
|
||||
// rate over screened women nor the confirmation proportion; the time says its note isn't linked to the mammogram nor is
|
||||
// the biopsy's date. Fails if the sheet is lost or reads like another indicator.
|
||||
expect(metadatosDeMeasure(measure(TASA)).descripcion).toMatch(/reporte de biopsia, no la\s+paciente/);
|
||||
expect(metadatosDeMeasure(measure(TASA)).descripcion).toMatch(/no es una tasa\s+sobre las mujeres tamizadas/);
|
||||
expect(metadatosDeMeasure(measure(DIAS)).descripcion).toMatch(/no está ligada a la mastografía/);
|
||||
expect(metadatosDeMeasure(measure(DIAS)).descripcion).toMatch(/no es la fecha de la biopsia/);
|
||||
expect(metadatosDeMeasure(measure(HISTO)).descripcion).toMatch(/la misma regla de CAMA_BIRADS456_PACIENTE/);
|
||||
const codigos = measures.map(m => metadatosDeMeasure(m).ficha!.codigo);
|
||||
expect(new Set(codigos).size).toBe(measures.length);
|
||||
expect(metadatosDeMeasure(measure(TASA)).ficha!.codigo).toBe('TASA-DETECCION-HISTOPATOLOGICA');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tasa de detección histopatológica (C1)', () => {
|
||||
it.each([['2025-01-01', '2025-S1', 16, 24, 66.7], ['2025-07-01', '2025-S2', 14, 25, 56], ['2026-01-01', '2026-S1', 13, 18, 72.2], ['2026-07-01', '2026-S2', 10, 19, 52.6]] as const)(
|
||||
'en %s el numerador y el denominador son los reportes de biopsia malignos y con resultado conocido', (inicio, periodo, numerador, denominador, valor) => {
|
||||
// Pins down: each semester's rows carry the report counts (malignant over known result) and the percentage the card
|
||||
// shows, in the page's group `total`, and the card reads «Disponible» with its sentence. Fails if a count is lost or
|
||||
// the numerator leaves its denominator.
|
||||
const d = datosValidos(datos(TASA, inicio, periodo), 'cama_tasa_deteccion_histopatologica', 'semestre', [periodo]);
|
||||
expect(d['grupos']).toEqual({ total: 'Total' });
|
||||
expect(d.filas).toEqual([expect.objectContaining({ grupo: 'total', numerador, denominador, valor, suprimido: 0 })]);
|
||||
expect(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply(periodo))).toMatchObject({
|
||||
state: 'Disponible', value: valor.toFixed(1), info: `${numerador} de ${denominador} biopsias con resultado maligno.` });
|
||||
});
|
||||
|
||||
it('el numerador nunca supera al denominador y la suma de los periodos es la de los reportes de biopsia del dominio', () => {
|
||||
// Pins down: over the real periods, malignant ≤ known result, and the four semesters add up to 56 + ... = the reports
|
||||
// (16+14+13+10 malignant of 24+25+18+19 with known result). Fails if a report is counted in two periods or one is dropped.
|
||||
const filas = SEMESTRES.flatMap(([inicio, periodo]) => datos(TASA, inicio, periodo).filas);
|
||||
expect(filas.every(f => (f['numerador'] as number) <= (f['denominador'] as number))).toBe(true);
|
||||
expect(filas.reduce((s, f) => s + (f['numerador'] as number), 0)).toBe(53);
|
||||
expect(filas.reduce((s, f) => s + (f['denominador'] as number), 0)).toBe(86);
|
||||
});
|
||||
|
||||
it('un semestre sin reportes de biopsia no da una tasa: 0 de 0 es sin datos, no 0 %', () => {
|
||||
// Pins down: 2021-S1 has no biopsy reports; the rows say 0 of 0 with no value and the card doesn't claim a rate.
|
||||
// Fails if an empty period is shown as 0 % or as an error.
|
||||
const d = datos(TASA, '2021-01-01', '2021-S1');
|
||||
expect(d.filas).toEqual([expect.objectContaining({ numerador: 0, denominador: 0, valor: null })]);
|
||||
expect(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply('2021-S1')).state).not.toBe('Disponible');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tiempo de resultado a diagnóstico (C3r)', () => {
|
||||
it.each([['2025-01-01', '2025-S1', 56, 41, 65], ['2025-07-01', '2025-S2', 59, 41, 49], ['2026-01-01', '2026-S1', 61, 21, 58], ['2026-07-01', '2026-S2', 18, 0, 40]] as const)(
|
||||
'en %s mide las mastografías con nota diagnóstica y deja fuera, contadas, las que no la tienen', (inicio, periodo, n, sinEvento, mediana) => {
|
||||
// Pins down: the observations (mammograms with a diagnosing note in the horizon), those without one and the median in
|
||||
// days, as the report publishes them, with the card reading the median. Fails if an unmeasured mammogram is dropped
|
||||
// without being counted or a median is read as zero.
|
||||
const d = datosValidos(datos(DIAS, inicio, periodo), 'cama_dias_resultado_diagnostico', 'semestre', [periodo]);
|
||||
expect(d.filas).toEqual([expect.objectContaining({ n, mediana, n_sin_evento: sinEvento, unidad: 'dias' })]);
|
||||
expect(kpiResult(d, CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', apply(periodo))).toMatchObject({ state: 'Disponible', value: mediana });
|
||||
});
|
||||
|
||||
it('las mastografías del periodo son las observadas más las que no tienen nota', () => {
|
||||
// Pins down: initial population = observations + exclusions in every real semester, so no mammogram is lost between
|
||||
// the population and the box plot. Fails if the report's counts don't close.
|
||||
for (const [inicio] of SEMESTRES) {
|
||||
const grupo = reportsOf(DIAS, 'semestre', inicio)[0].group![0];
|
||||
const n = (c: string) => grupo.population!.find(p => p.code?.coding?.[0].code === c)!.count!;
|
||||
expect(n('measure-observation') + n('measure-population-exclusion'), inicio).toBe(n('initial-population'));
|
||||
}
|
||||
});
|
||||
|
||||
it('un semestre sin mastografías no da una mediana', () => {
|
||||
// Pins down: with no observations the card has no value (a median over zero observations is no value, not zero days).
|
||||
// Fails if an empty period reads as 0 days.
|
||||
const d = datos(DIAS, '2021-01-01', '2021-S1');
|
||||
expect(kpiResult(d, CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', apply('2021-S1')).state).not.toBe('Disponible');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Resultado histopatológico por categoría BI-RADS (C2 por BI-RADS)', () => {
|
||||
const matriz = (inicio: string, periodo: string, tipo: TipoPeriodo = 'semestre') =>
|
||||
modeloHistopatologia(datosValidos(datos(HISTO, inicio, periodo, tipo, { estrato: 'birads' }), 'cama_histopatologia_birads', tipo, [periodo], { estrato: 'birads' }), periodo);
|
||||
const celdas = (m: ReturnType<typeof matriz>) => Object.fromEntries(m.filas.map(f => [f.id,
|
||||
{ ...Object.fromEntries(Object.entries(f.celdas).map(([k, c]) => [k, c.n])), ...Object.fromEntries(Object.entries(f.aparte).map(([k, c]) => [k, c.n])), total: f.total.n }]));
|
||||
|
||||
it('2025-S1: la matriz BI-RADS por resultado es la del reporte, con ceros publicados en las categorías sin pacientes', () => {
|
||||
// Pins down: the cells of the real report (BI-RADS 4: 8 benign, 6 invasive, 6 without biopsy; BI-RADS 5: 6 invasive, 1 in
|
||||
// situ, 3 without biopsy), every other stratum a published zero (never «No disponible»), each stratum's total the sum of
|
||||
// its cells and the matrix the 30 patients of the period. Fails if a cell moves, a zero turns unavailable or a total drifts.
|
||||
const m = matriz('2025-01-01', '2025-S1');
|
||||
expect(m.filas.map(f => f.id)).toEqual([...ESTRATOS_BIRADS]);
|
||||
expect(celdas(m)).toEqual({
|
||||
BIRADS_4: { BENIGNO: 8, IN_SITU: 0, INVASOR: 6, SIN_BIOPSIA: 6, SIN_DATO: 0, total: 20 },
|
||||
BIRADS_4A: { BENIGNO: 0, IN_SITU: 0, INVASOR: 0, SIN_BIOPSIA: 0, SIN_DATO: 0, total: 0 },
|
||||
BIRADS_4B: { BENIGNO: 0, IN_SITU: 0, INVASOR: 0, SIN_BIOPSIA: 0, SIN_DATO: 0, total: 0 },
|
||||
BIRADS_4C: { BENIGNO: 0, IN_SITU: 0, INVASOR: 0, SIN_BIOPSIA: 0, SIN_DATO: 0, total: 0 },
|
||||
BIRADS_5: { BENIGNO: 0, IN_SITU: 1, INVASOR: 6, SIN_BIOPSIA: 3, SIN_DATO: 0, total: 10 },
|
||||
BIRADS_6: { BENIGNO: 0, IN_SITU: 0, INVASOR: 0, SIN_BIOPSIA: 0, SIN_DATO: 0, total: 0 },
|
||||
});
|
||||
expect(m.filas.every(f => Object.values(f.celdas).every(c => c.estado === 'Publicado'))).toBe(true);
|
||||
expect(m.filas.reduce((s, f) => s + f.total.n!, 0)).toBe(30);
|
||||
expect(m.conResultado).toBe(21);
|
||||
});
|
||||
|
||||
it('la lesión de riesgo (B3) no se inventa: no hay esa categoría en las fuentes y la matriz no la dibuja', () => {
|
||||
// Pins down: the source grades are benign, in situ and invasive; the page's optional «Lesión de riesgo (B3)» isn't
|
||||
// published, so the model lists three categories and two groups (non malignant, malignant). Fails if a category the
|
||||
// source lacks appears, or the model needs it.
|
||||
const m = matriz('2025-01-01', '2025-S1');
|
||||
expect(m.categorias.map(c => c.id)).toEqual(['BENIGNO', 'IN_SITU', 'INVASOR']);
|
||||
expect(m.categorias.map(c => c.etiqueta)).toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor']);
|
||||
expect(m.grupos.map(g => [g.id, g.categorias])).toEqual([['NO_MALIGNO', ['BENIGNO']], ['MALIGNO', ['IN_SITU', 'INVASOR']]]);
|
||||
expect(m.aparte.map(a => a.id)).toEqual(['SIN_BIOPSIA', 'SIN_DATO']);
|
||||
});
|
||||
|
||||
it('las tasas por categoría usan solo a las pacientes con resultado de biopsia y llevan su intervalo', () => {
|
||||
// Pins down: for the malignant group the rate of BI-RADS 4 is 6 of 14 and BI-RADS 5 is 7 of 7 (no biopsy and no data
|
||||
// never enter the denominator), and a stratum with no patients has no rate. Fails if «sin biopsia» enters a denominator.
|
||||
const m = matriz('2025-01-01', '2025-S1');
|
||||
const t = Object.fromEntries(tasas(m, seleccionBase(m)).map(x => [x.fila.id, x]));
|
||||
expect([t['BIRADS_4'].k, t['BIRADS_4'].fila.den]).toEqual([6, 14]);
|
||||
expect([t['BIRADS_5'].k, t['BIRADS_5'].fila.den]).toEqual([7, 7]);
|
||||
expect(t['BIRADS_5'].valor).toBe(100);
|
||||
expect(t['BIRADS_4'].bajo).toBeLessThan(t['BIRADS_4'].valor!);
|
||||
expect(t['BIRADS_4'].alto).toBeGreaterThan(t['BIRADS_4'].valor!);
|
||||
expect(t['BIRADS_6'].valor).toBeNull();
|
||||
});
|
||||
|
||||
it('el total de la matriz de cada semestre es el de pacientes BI-RADS 4, 5 y 6 del periodo', () => {
|
||||
// Pins down: the matrix counts the same patients as CAMA_BIRADS456_PACIENTE (36 in 2025-S2, the report of the earlier
|
||||
// fixture), and in every real semester the units of the report are the matrix's cells. Fails if the two measures count
|
||||
// different patients.
|
||||
const total = (inicio: string, periodo: string) => matriz(inicio, periodo).filas.reduce((s, f) => s + f.total.n!, 0);
|
||||
expect(total('2025-07-01', '2025-S2')).toBe(BIRADS_PACIENTES_2025_S2);
|
||||
for (const [inicio, periodo] of SEMESTRES) {
|
||||
expect(total(inicio, periodo), periodo).toBe(reportsOf(HISTO, 'semestre', inicio)[0].group![0].population![0].count);
|
||||
}
|
||||
});
|
||||
|
||||
it('un semestre sin pacientes es una matriz de ceros publicados, no un error', () => {
|
||||
// Pins down: 2021-S1 has no mammograms: the matrix is complete with zeros and the denominators are zero (no rate).
|
||||
// Fails if an empty period breaks the view or turns into «No disponible».
|
||||
const m = matriz('2021-01-01', '2021-S1');
|
||||
expect(m.filas.every(f => f.total.n === 0 && f.den === 0)).toBe(true);
|
||||
expect(m.conResultado).toBe(0);
|
||||
});
|
||||
|
||||
it('un mes con pacientes se lee igual que un semestre', () => {
|
||||
// Pins down: the monthly answer carries the month label and the same matrix shape. Fails if the month is read as a semester.
|
||||
const m = matriz('2025-12-01', '2025-12', 'mes');
|
||||
expect(m.periodo).toBe('2025-12');
|
||||
expect(m.filas.reduce((s, f) => s + f.total.n!, 0)).toBe(8);
|
||||
});
|
||||
|
||||
it('el catálogo de categorías sale de la Measure y los códigos desconocidos son un error, no ceros', () => {
|
||||
// Pins down: an unknown BI-RADS or grade code in a report, or cells that don't add up to the units, throw instead of
|
||||
// being read as zero. Fails if the adapter hides an inconsistent report.
|
||||
const clon = (): Report[] => structuredClone(reportsOf(HISTO, 'semestre', '2025-01-01'));
|
||||
const conCodigo = clon();
|
||||
conCodigo[0].group![0].stratifier![1]['stratum']![0].component![0].value!.coding![0].code = 'B9';
|
||||
expect(() => datosDeReportes(measure(HISTO), conCodigo, 'semestre', { estrato: 'birads' })).toThrow(/no reconocido/);
|
||||
const desajustado = clon();
|
||||
desajustado[0].group![0].stratifier![1]['stratum']![0].population![0].count! += 1;
|
||||
expect(() => datosDeReportes(measure(HISTO), desajustado, 'semestre', { estrato: 'birads' })).toThrow(/no suman/);
|
||||
const sinCruce = clon();
|
||||
sinCruce[0].group![0].stratifier = sinCruce[0].group![0].stratifier!.slice(0, 1);
|
||||
expect(() => datosDeReportes(measure(HISTO), sinCruce, 'semestre', { estrato: 'birads' })).toThrow(/no admitida/);
|
||||
});
|
||||
|
||||
it('sin pedir el estrato, la medida se lee como una distribución por resultado y suma las mismas pacientes', () => {
|
||||
// Pins down: asked without the stratum the measure is a plain C2 (categories of the biopsy result); its categories add
|
||||
// to the report's units. Fails if the stratified reading changes the plain one.
|
||||
const d = datos(HISTO, '2025-01-01', '2025-S1');
|
||||
expect(d.filas.reduce((s, f) => s + (f['n'] as number), 0)).toBe(30);
|
||||
expect(periodosHistopatologia(datos(HISTO, '2025-01-01', '2025-S1', 'semestre', { estrato: 'birads' }), 'semestre')).toEqual(['2025-S1']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Resumen e Histórico leen lo mismo', () => {
|
||||
type Traza = { name?: string; x: (string | null)[]; y: (number | null)[] };
|
||||
const serie = (d: IndicadorDatos, nombre: string): Traza =>
|
||||
((historicoFigura(d, 'claro').figure as unknown as { data: Traza[] }).data).find(t => t.name === nombre)!;
|
||||
it.each([[TASA, 'Porcentaje', (d: IndicadorDatos, p: string) => Number(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply(p)).value)],
|
||||
[DIAS, 'Mediana', (d: IndicadorDatos, p: string) => Number(kpiResult(d, CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', apply(p)).value)]] as const)(
|
||||
'%s: el valor de la tarjeta de cada semestre es el punto del Histórico en ese semestre', (fhirId, nombre, tarjeta) => {
|
||||
// Pins down: the card of one semester and the history of all of them are built from the same reports, so the number on the
|
||||
// card is the point of the series for that period. Fails if the two screens compute the figure differently.
|
||||
const historico = datosDeReportes(measure(fhirId), SEMESTRES.map(([inicio]) => reportsOf(fhirId, 'semestre', inicio)[0]), 'semestre');
|
||||
const traza = serie(historico, nombre);
|
||||
for (const [inicio, periodo] of SEMESTRES) {
|
||||
const i = traza.x.indexOf(etiquetaPeriodo(periodo));
|
||||
expect(i, periodo).toBeGreaterThanOrEqual(0);
|
||||
expect(traza.y[i], periodo).toBe(tarjeta(datos(fhirId, inicio, periodo), periodo));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -346,12 +346,4 @@ describe('Filtros generales de CaMa: periodo único', () => {
|
||||
expect(control.canApply).toBe(false);
|
||||
expect(fixture.nativeElement.textContent).toContain('Selecciona un periodo válido para aplicar.');
|
||||
});
|
||||
it('los demás dominios conservan Modalidad, la selección múltiple y sus resúmenes', () => {
|
||||
// Fails if the single-period layout leaks to CaCu or TEA.
|
||||
mount(false, { mode: 'todos' }, { mode: 'todos' });
|
||||
expect(labels()).toEqual(['Intervalo de tiempo', 'Modalidad']);
|
||||
const text = fixture.nativeElement.textContent as string;
|
||||
expect(text).toContain('Selección en edición: Todos con reporte');
|
||||
expect(text).toContain('Sin cambios pendientes.');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -105,13 +105,11 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
||||
fixture.componentInstance.togglePinned(CAMA[5] as never); fixture.detectChanges();
|
||||
expect(titles()).toEqual(before);
|
||||
});
|
||||
it.each(['tea', 'cacu'] as const)('%s conserva buscador, fijados, navegación flotante, selector y conteo de figuras', domain => {
|
||||
it.each(['tea', 'cacu'] as const)('%s conserva buscador, fijados y conteo de figuras', domain => {
|
||||
// Fails if CaMa's simplified section leaks into the other domains.
|
||||
open(domain, OTRO(domain));
|
||||
expect(root().querySelector('.catalog-search')).not.toBeNull();
|
||||
expect(root().querySelectorAll('.pin-toggle').length).toBe(6);
|
||||
expect(root().querySelector('.graphic-navigation-trigger')).not.toBeNull();
|
||||
expect(section().querySelector('app-indicador-catalog-card mat-form-field')).not.toBeNull();
|
||||
expect(section().textContent).toContain('2 figuras publicadas');
|
||||
expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe('6 indicadores publicados');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
// What this module covers: CaMa's follow-up as the WebApi's cohort endpoint answers it (`GET /cama/seguimiento`):
|
||||
// the answer's validation and labels, the table the page draws from it, its states, the record of one patient and the
|
||||
// rows of a file. Nothing here is a status, a priority or a figure the data doesn't hold.
|
||||
// Fixtures (`fixtures/cama_seguimiento_cohorte_real*.json`): answers of the endpoint over the local installation's
|
||||
// synthetic CaMa data: `_inicial` (default: today, three months), `_consulta` (six months, BI-RADS 5), the whole cohort
|
||||
// at 2026-11-16 and the 403 body of a group of fewer than five patients.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { ComponentFixture } from '@angular/core/testing';
|
||||
import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla';
|
||||
import { consultaAplicada, contextoDe, seguimientoTablaResponse, SeguimientoTablaQuery } from './seguimiento-tabla.service';
|
||||
import { identidadesDe } from './paciente-identidad';
|
||||
import { toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models';
|
||||
import { flatTable } from './export/tracking-export-table';
|
||||
import inicialData from './fixtures/cama_seguimiento_cohorte_real_inicial.json';
|
||||
import consultaData from './fixtures/cama_seguimiento_cohorte_real_consulta.json';
|
||||
import cohorteData from './fixtures/cama_seguimiento_cohorte_real.json';
|
||||
import pequenoData from './fixtures/cama_seguimiento_cohorte_real_403.json';
|
||||
|
||||
const copia = (v: unknown) => structuredClone(v) as unknown as Record<string, any>;
|
||||
|
||||
describe('Seguimiento de CaMa sobre la cohorte del servidor', () => {
|
||||
it('la respuesta cumple el contrato, nombra la cohorte y rotula los códigos sin cambiar los valores enviados', () => {
|
||||
// Pins down: the answer is accepted as is (every row names its patient by `pac_id`, a decimal text), the cohort
|
||||
// context is read from it, and codes read as the clinic writes them while the code stays in `<clave>_codigo`.
|
||||
// Fails if the endpoint's shape stops passing the client's validation, or a label replaces a code the requests send.
|
||||
const respuesta = seguimientoTablaResponse(copia(cohorteData));
|
||||
expect(respuesta.items).toHaveLength(61);
|
||||
expect(identidadesDe(respuesta.items)!.every(i => i.campo === 'pac_id' && /^[1-9][0-9]*$/.test(i.id))).toBe(true);
|
||||
expect(contextoDe(respuesta)).toEqual({ cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: expect.stringMatching(/^[0-9a-f]{64}$/) });
|
||||
const fila = respuesta.items.find(i => i['birads_codigo'] === 'BIRADS_4')!;
|
||||
expect(fila['birads']).toBe('BI-RADS 4');
|
||||
expect(respuesta.filtros_disponibles.find(f => f.clave === 'birads')!.opciones.map(o => [o.codigo, o.etiqueta]))
|
||||
.toContainEqual(['BIRADS_4A', 'BI-RADS 4A']);
|
||||
expect(respuesta.filtros_disponibles.find(f => f.clave === 'grupo_edad')!.opciones.map(o => o.etiqueta))
|
||||
.toEqual(['Menores de 40 años', '40 a 49 años', '50 a 59 años', '60 a 69 años', '70 años o más', 'Sin dato']);
|
||||
expect(respuesta.columnas.map(c => c.clave)).toEqual(['pac_id', 'grupo_edad', 'birads', 'biopsia']);
|
||||
});
|
||||
|
||||
it('una página o un archivo solo se acepta si es de la consulta, la cohorte y la revisión que se pidieron', () => {
|
||||
// Pins down: the answer must repeat the window, filters and context asked for. Fails if rows of another revision
|
||||
// or another selection could be shown under the title of this one.
|
||||
const respuesta = seguimientoTablaResponse(copia(consultaData));
|
||||
const contexto = contextoDe(respuesta)!;
|
||||
const pedido: SeguimientoTablaQuery = { corte: respuesta.corte, meses: 6, page: 1, page_size: 50, filtros: { birads: 'BIRADS_5' }, contexto };
|
||||
expect(consultaAplicada(pedido, respuesta)).toBe(true);
|
||||
expect(consultaAplicada({ ...pedido, contexto: { ...contexto, revision: 'otra' } }, respuesta)).toBe(false);
|
||||
expect(consultaAplicada({ ...pedido, filtros: {} }, respuesta)).toBe(false);
|
||||
expect(consultaAplicada({ ...pedido, meses: 3 }, respuesta)).toBe(false);
|
||||
});
|
||||
|
||||
it('la ficha de una paciente muestra lo que trae la fila y deja sin dato estatus, prioridad y días', () => {
|
||||
// Pins down: the record reads BI-RADS, its date, the age group and the biopsy from the row, and what the list
|
||||
// doesn't carry stays `null` (shown as «No disponible»), never a value made up. Fails if the summary fills
|
||||
// status, priority or the days to diagnosis from anywhere.
|
||||
const r = seguimientoTablaResponse(copia(cohorteData));
|
||||
const conBiopsia = r.items.find(i => i['biopsia'] !== null)!, sinBiopsia = r.items.find(i => i['biopsia'] === null)!;
|
||||
const resumen = toCamaPatientSummary(conBiopsia, r.corte, r.columnas)!;
|
||||
expect(resumen).toMatchObject({ patientId: String(conBiopsia['pac_id']), idField: 'pac_id', cutoff: r.corte, status: null, priority: null,
|
||||
daysMammographyToDiagnosis: null, birads: conBiopsia['birads'], biopsyDate: conBiopsia['biopsia_fecha'] });
|
||||
expect(resumen.biopsyDateLabel).toBe('Fecha de reporte');
|
||||
expect(toCamaPatientSummary(sinBiopsia, r.corte, r.columnas)).toMatchObject({ histopathology: null, biopsyDate: null });
|
||||
});
|
||||
|
||||
it('el archivo lleva las columnas del servidor, sin estatus, prioridad ni días de diagnóstico', () => {
|
||||
// Pins down: the file's columns are the announced ones (with their date details) and no other, and a missing biopsy
|
||||
// is `null`. Fails if the files add a column the cohort doesn't have.
|
||||
const r = seguimientoTablaResponse(copia(cohorteData));
|
||||
const tabla = flatTable({ corte: r.corte, ventana: r.ventana, filtros: r.filtros, filtros_disponibles: r.filtros_disponibles, columnas: r.columnas, items: r.items });
|
||||
expect(tabla.columns.map(c => c.label)).toEqual(['Identificador de paciente', 'Grupo de edad', 'Última mastografía', 'Última mastografía: Fecha',
|
||||
'Resultado histopatológico', 'Resultado histopatológico: Fecha de reporte']);
|
||||
expect(tabla.rows).toHaveLength(61);
|
||||
expect(tabla.rows.some(fila => fila[4] === null && fila[5] === null)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Seguimiento de CaMa (tabla) con las respuestas del servidor', () => {
|
||||
let fixture: ComponentFixture<IndicadoresSeguimientoTabla>, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
const solicitud = () => http.expectOne(r => r.url === '/cama/seguimiento');
|
||||
async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); }
|
||||
const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement;
|
||||
const campo = (etiqueta: string) => [...root().querySelectorAll('label')].find(l => l.textContent!.trim().startsWith(etiqueta))!;
|
||||
const filas = () => [...root().querySelectorAll('tbody tr')].map(tr => [...tr.children].map(td => [...td.childNodes]
|
||||
.filter(n => n.nodeType !== Node.COMMENT_NODE).map(n => (n.textContent ?? '').trim()).filter(Boolean).join(' ')));
|
||||
const elegir = (etiqueta: string, valor: string) => {
|
||||
const s = campo(etiqueta).querySelector('select')!;
|
||||
s.value = [...s.options].find(o => o.value.endsWith(valor))!.value; s.dispatchEvent(new Event('change'));
|
||||
};
|
||||
|
||||
it('la primera consulta pide la ventana de 3 meses y dibuja las cuatro columnas de la cohorte con los datos que hay', async () => {
|
||||
// Pins down: the table has the cohort's four columns and no status, priority or days; the first request is three
|
||||
// months, page one of 50, with no cut-off (the server's today); a patient without biopsy reads «No disponible».
|
||||
// Fails if the table asks for or draws a column the endpoint doesn't announce.
|
||||
const r = solicitud();
|
||||
expect(Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)]))).toEqual({ meses: '3', page: '1', page_size: '50' });
|
||||
r.flush(inicialData); await asentar();
|
||||
expect([...root().querySelectorAll('thead th')].map(th => th.textContent!.trim())).toEqual(
|
||||
['Identificador de paciente', 'Grupo de edad', 'Última mastografía', 'Resultado histopatológico']);
|
||||
expect(filas()).toHaveLength(16);
|
||||
const sin = filas().find(f => f[3] === 'No disponible');
|
||||
expect(sin).toBeDefined();
|
||||
expect(sin![2]).toMatch(/^BI-RADS (4|4A|4B|4C|5|6) Fecha: 20\d\d-\d\d-\d\d$/);
|
||||
expect(root().textContent).toContain(`Ventana consultada: ${(inicialData as any).ventana.desde} al ${(inicialData as any).ventana.hasta}.`);
|
||||
});
|
||||
|
||||
it('el formulario ofrece los filtros que anuncia el servidor y Consultar envía el filtro elegido, el corte y la revisión que devolvió', async () => {
|
||||
// Pins down: the filters are BI-RADS, age group and biopsy result as announced, and a second query sends the cut-off
|
||||
// the first answer gave, with its cohort, scenario and revision, plus the chosen window and filter. Fails if the revision isn't quoted back or a filter the server doesn't announce appears
|
||||
// (BRCA, stage, size, priority...).
|
||||
solicitud().flush(inicialData); await asentar();
|
||||
expect([...root().querySelectorAll('form label')].map(l => l.firstChild!.textContent!.trim()))
|
||||
.toEqual(['Fecha de corte', 'Ventana de meses', 'Categoría BI-RADS', 'Grupo de edad', 'Resultado de la biopsia', 'Registros por página']);
|
||||
expect([...campo('Resultado de la biopsia').querySelectorAll('option')].map(o => o.text.trim())).toEqual(
|
||||
['Todos', 'Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'Biopsia reportada sin resultado', 'Sin biopsia reportada']);
|
||||
elegir('Ventana de meses', '6'); elegir('Categoría BI-RADS', 'BIRADS_5'); await asentar();
|
||||
boton('Consultar').click(); fixture.detectChanges();
|
||||
const r = solicitud();
|
||||
expect(Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)]))).toEqual({
|
||||
meses: '6', page: '1', page_size: '50', corte: (inicialData as any).corte, birads: 'BIRADS_5',
|
||||
cohorte: (inicialData as any).cohorte, escenario: (inicialData as any).escenario, revision: (inicialData as any).revision });
|
||||
r.flush(consultaData); await asentar();
|
||||
expect(root().textContent).toContain(`Ventana consultada: ${(consultaData as any).ventana.desde} al ${(consultaData as any).ventana.hasta}.`);
|
||||
expect(filas().every(f => f[2].startsWith('BI-RADS 5'))).toBe(true);
|
||||
});
|
||||
|
||||
it('un grupo de menos de cinco pacientes se dice con su motivo y no se dibuja ninguna fila', async () => {
|
||||
// Pins down: the server's 403 for a small selection is shown as a message and clears the table. Fails if rows of a
|
||||
// previous selection stay on screen or the page says nothing.
|
||||
solicitud().flush(inicialData); await asentar();
|
||||
elegir('Categoría BI-RADS', 'BIRADS_6'); await asentar();
|
||||
boton('Consultar').click(); fixture.detectChanges();
|
||||
solicitud().flush(pequenoData, { status: 403, statusText: 'Forbidden' }); await asentar();
|
||||
expect(root().querySelector('[role=alert]')?.textContent).toContain('muy pocos pacientes');
|
||||
expect(filas()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('si el servidor responde 404 en CaMa dice que la cohorte no está disponible, sin pantalla vacía', async () => {
|
||||
// Pins down: an endpoint that isn't there leaves an informative state. Fails if the tab shows an empty table or an
|
||||
// unhandled error.
|
||||
solicitud().flush({}, { status: 404, statusText: 'Not Found' }); await asentar();
|
||||
expect(root().querySelector('[role=alert]')?.textContent).toContain('cohorte no está disponible');
|
||||
});
|
||||
});
|
||||
@@ -44,17 +44,17 @@ describe('Cambio de dominio con consultas pendientes', () => {
|
||||
abrir('cacu', 6);
|
||||
expect(el().querySelector('.catalog-search')).not.toBeNull();
|
||||
expect(el().querySelectorAll('.pin-toggle').length).toBe(6);
|
||||
expect(el().textContent).toContain('Modalidad');
|
||||
expect(el().textContent).toContain('Intervalo de análisis');
|
||||
abrir('cama', 6);
|
||||
expect(el().querySelector('.catalog-search')).toBeNull();
|
||||
expect(el().querySelector('.pin-toggle')).toBeNull();
|
||||
expect(el().textContent).not.toContain('Modalidad');
|
||||
expect(el().textContent).not.toContain('Buscar indicadores');
|
||||
expect(el().textContent).not.toContain('cacu_');
|
||||
abrir('cacu', 6);
|
||||
// On the way back the page state (not only the DOM) says CaCu has its search again.
|
||||
expect(fixture.componentInstance.dominio).toBe('cacu');
|
||||
expect(fixture.componentInstance.searchVisible()).toBe(true);
|
||||
expect(el().textContent).toContain('Modalidad');
|
||||
expect(el().textContent).toContain('Intervalo de análisis');
|
||||
expect(el().textContent).not.toContain('cama_');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Theme } from './indicadores-c2-palette';
|
||||
import { c2Theme, groupBase, paintByGroup } from './indicadores-c2-palette';
|
||||
import { percentNumber, shareText } from './indicadores-format';
|
||||
|
||||
// Histopathological confirmation of high-grade cytology (cacu_confirmacion_citologia):
|
||||
@@ -69,10 +69,6 @@ function suma(celdas: Celda[]): number | null {
|
||||
function estado(celdas: Celda[]): Celda['estado'] {
|
||||
return celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido' : celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado';
|
||||
}
|
||||
function promedio(colores: string[]): string {
|
||||
return '#' + [1, 3, 5].map(i => Math.round(colores.reduce((s, c) => s + parseInt(c.slice(i, i + 2), 16), 0) / colores.length)
|
||||
.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
function rgba(hex: string, alfa: number): string {
|
||||
const v = parseInt(hex.slice(1), 16);
|
||||
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`;
|
||||
@@ -101,15 +97,21 @@ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): Mode
|
||||
const c = cats[a.id];
|
||||
return { id: a.id, etiqueta: registro(c) && texto(c['etiqueta']) ? c['etiqueta'] : a.etiqueta };
|
||||
});
|
||||
const grados: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => {
|
||||
const gradosCrudos: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => {
|
||||
if (!registro(c) || !texto(c['etiqueta']) || (c['color'] !== null && (typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color'])))
|
||||
|| typeof c['grupo'] !== 'string' || !etiquetaGrupo(nombres[c['grupo']])) return fail('Grados de biopsia incompatibles.');
|
||||
return { id, etiqueta: c['etiqueta'], color: (c['color'] as string | null) ?? COLOR_RESPALDO, grupo: c['grupo'] };
|
||||
});
|
||||
const conColor = gradosCrudos.filter(g => g.color !== COLOR_RESPALDO);
|
||||
const colores = paintByGroup(conColor.map(g => g.grupo));
|
||||
const colorDe = new Map(conColor.map((g, i) => [g.id, colores[i]]));
|
||||
const grados = gradosCrudos.map(g => ({ ...g, color: colorDe.get(g.id) ?? g.color }));
|
||||
const ordenGrupos = [...new Set(conColor.map(g => g.grupo))];
|
||||
const grupos = [...new Set(grados.map(g => g.grupo))].map(id => {
|
||||
// Off-catalogue grades share the group but not its colour.
|
||||
const propios = grados.filter(g => g.grupo === id), publicados = propios.filter(g => g.color !== COLOR_RESPALDO);
|
||||
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: promedio((publicados.length ? publicados : propios).map(g => g.color)),
|
||||
// Off-catalogue grades keep the neutral fallback and do not take the group hue.
|
||||
const propios = grados.filter(g => g.grupo === id);
|
||||
const indice = ordenGrupos.indexOf(id);
|
||||
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: indice < 0 ? COLOR_RESPALDO : groupBase(indice),
|
||||
grados: propios.map(g => g.id) };
|
||||
});
|
||||
// The base view is the group of LIEAG ("LIEAG o más"): the true positives.
|
||||
|
||||
@@ -87,50 +87,24 @@ describe('Conteos pareados de CaMa: lo que se puede sumar', () => {
|
||||
const dona = donaConteos(m, PAR, 'claro') as unknown as { data: { labels: string[]; values: number[] }[]; layout: { annotations: { text: string }[] } };
|
||||
expect(dona.data[0].labels).toEqual(['BI-RADS 4 (sin subcategoría)', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']);
|
||||
expect(dona.data[0].values).toEqual([15, 2, 0, 0, 18, 0]);
|
||||
expect(dona.layout.annotations[0].text).toBe('<b>35</b><br>mastografías');
|
||||
expect(dona.layout.annotations.slice(0, 2).map(a => a.text)).toEqual(['<b>35</b>', 'mastografías']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Conteos pareados de CaMa: etiquetas de la dona', () => {
|
||||
type Figura = { data: Record<string, any>[]; layout: { annotations: Record<string, any>[]; margin: Record<string, number>; showlegend: boolean } };
|
||||
const dona = (compacta = false) => donaConteos(modelo(examenes(LAB_E), pacientes(LAB_P)), PAR, 'claro', compacta) as unknown as Figura;
|
||||
const dona = () => donaConteos(modelo(examenes(LAB_E), pacientes(LAB_P)), PAR, 'claro') as unknown as Figura;
|
||||
|
||||
// Fails if the long label of the 4 without subcategory goes back inside the ring (where it is cut), loses its
|
||||
// percentage or its guide line, or if the short labels or the centre total change.
|
||||
it('2025-S2: la etiqueta larga sale del anillo, horizontal y con línea guía; las cortas y el total se conservan', () => {
|
||||
const f = dona(), t = f.data[0], llamada = f.layout.annotations[1];
|
||||
expect(t['text'][0]).toBe('');
|
||||
expect(t['text'][1]).toBe('');
|
||||
expect(t['text'][4]).toMatch(/^BI-RADS 5<br>54[.,]5 %$/);
|
||||
it('mantiene las etiquetas con porcentaje fuera del sector', () => {
|
||||
const f = dona(), t = f.data[0];
|
||||
expect(t['textinfo']).toBe('none');
|
||||
expect(t['hovertemplate']).toBe('%{value}<extra></extra>');
|
||||
expect(f.layout.annotations.slice(2).map(a => a['text']).sort()).toEqual([
|
||||
'BI-RADS 4<br>(sin<br>subcategoría)<br>45.5 %', 'BI-RADS 5<br>54.5 %',
|
||||
]);
|
||||
expect(t['values']).toEqual([15, 0, 0, 0, 18, 0]);
|
||||
expect(f.layout.annotations[0]['text']).toBe('<b>33</b><br>mastografías');
|
||||
expect(f.layout.annotations).toHaveLength(2);
|
||||
expect(llamada['text']).toBe('BI-RADS 4<br>(sin subcategoría)<br>45.5 %');
|
||||
// A guide line: an arrow without head from the label to a point inside the slice, and no text rotation.
|
||||
expect(llamada['showarrow']).toBe(true);
|
||||
expect(llamada['arrowhead']).toBe(0);
|
||||
expect(llamada['textangle']).toBeUndefined();
|
||||
});
|
||||
|
||||
// Fails if the label can reach the neighbouring chart: its side must keep a margin, and it sits on the side of its slice.
|
||||
it('reserva espacio del lado de la etiqueta y la coloca del lado de su segmento', () => {
|
||||
const f = dona(), llamada = f.layout.annotations[1];
|
||||
// The slice is 45 % of a clockwise ring: its middle points right, so label and margin are on the right.
|
||||
expect(llamada['xanchor']).toBe('left');
|
||||
expect(llamada['ax']).toBeGreaterThan(0);
|
||||
expect(f.layout.margin['r']).toBeGreaterThanOrEqual(110);
|
||||
expect(f.layout.margin['l']).toBeLessThan(20);
|
||||
expect(f.layout.showlegend).toBe(false);
|
||||
});
|
||||
|
||||
// Fails if a narrow screen keeps a label that needs side room instead of moving to a legend under the donut.
|
||||
it('en pantalla estrecha no hay llamada: la dona usa una leyenda debajo', () => {
|
||||
const f = dona(true);
|
||||
expect(f.layout.annotations).toHaveLength(1);
|
||||
expect(f.layout.showlegend).toBe(true);
|
||||
expect((f.layout as Record<string, any>)['legend']['orientation']).toBe('h');
|
||||
expect(f.layout.margin['r']).toBeLessThan(20);
|
||||
expect(f.data[0]['values']).toEqual([15, 0, 0, 0, 18, 0]);
|
||||
expect(f.layout.annotations.slice(0, 2).map(a => a['text'])).toEqual(['<b>33</b>', 'mastografías']);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -42,10 +42,10 @@ export const esSocioConteos = (dominio: Dominio, id: string, ids: readonly strin
|
||||
|
||||
// The kit publishes a 4 without subcategory as «B4», with no colour.
|
||||
const ETIQUETA_RESPALDO: Readonly<Record<string, string>> = { B4: 'BI-RADS 4 (sin subcategoría)' };
|
||||
// The categories a response lists only when some unit falls in them: a period set without any has none, not an unknown.
|
||||
const OPCIONALES: ReadonlySet<string> = new Set(Object.keys(ETIQUETA_RESPALDO));
|
||||
const COLOR_RESPALDO: Readonly<Record<string, string>> = { B4: '#E9C08C' };
|
||||
const COLOR_NEUTRO = '#8A9199';
|
||||
// Labels longer than «BI-RADS 4A» do not fit inside the ring.
|
||||
const LARGO_ETIQUETA_INTERIOR = 12;
|
||||
|
||||
export interface CategoriaConteo { id: string; etiqueta: string; color: string; n: number | null; }
|
||||
export interface FilaConteo { id: string; etiqueta: string; pacientes: number | null; examenes: number | null; }
|
||||
@@ -82,21 +82,24 @@ export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacien
|
||||
};
|
||||
const color = (id: string) => registro(catExamenes[id]) && typeof catExamenes[id]['color'] === 'string' ? catExamenes[id]['color'] as string : COLOR_RESPALDO[id] ?? COLOR_NEUTRO;
|
||||
const todas = par.grupos.flatMap(g => g.categorias);
|
||||
if (par.categoriasExamen.some(id => !Object.hasOwn(catExamenes, id)) || todas.some(id => !Object.hasOwn(catPacientes, id) || !Object.hasOwn(catExamenes, id))) {
|
||||
if (par.categoriasExamen.some(id => !OPCIONALES.has(id) && !Object.hasOwn(catExamenes, id))
|
||||
|| todas.some(id => !OPCIONALES.has(id) && (!Object.hasOwn(catPacientes, id) || !Object.hasOwn(catExamenes, id)))) {
|
||||
fail('Las categorías de mastografías y pacientes no coinciden.');
|
||||
}
|
||||
const verificados = par.versionesPacientes.includes(String(pacientes['version'] ?? ''));
|
||||
const periodos = [...examenes.periodos].filter(p => pacientes.periodos.includes(p)).sort();
|
||||
const filasE = examenes.filas as Record<string, unknown>[], filasP = pacientes.filas as Record<string, unknown>[];
|
||||
const de = (filas: Record<string, unknown>[], cat: Record<string, unknown>, periodo: string, id: string) =>
|
||||
OPCIONALES.has(id) && !Object.hasOwn(cat, id) ? 0 : cuenta(filas, periodo, id);
|
||||
return periodos.map(periodo => ({
|
||||
periodo,
|
||||
examenes: par.categoriasExamen.map(id => ({ id, etiqueta: etiqueta(catExamenes, id), color: color(id), n: cuenta(filasE, periodo, id) })),
|
||||
examenes: par.categoriasExamen.map(id => ({ id, etiqueta: etiqueta(catExamenes, id), color: color(id), n: de(filasE, catExamenes, periodo, id) })),
|
||||
// Only the exams the response reports apart; an indicator that lists no such category has none.
|
||||
sinDato: Object.hasOwn(catExamenes, 'SIN_DATO') ? cuenta(filasE, periodo, 'SIN_DATO') : 0,
|
||||
filas: par.grupos.map(g => ({
|
||||
id: g.id, etiqueta: g.etiqueta,
|
||||
pacientes: verificados ? sumar(g.categorias.map(id => cuenta(filasP, periodo, id))) : null,
|
||||
examenes: sumar(g.categorias.map(id => cuenta(filasE, periodo, id))),
|
||||
pacientes: verificados ? sumar(g.categorias.map(id => de(filasP, catPacientes, periodo, id))) : null,
|
||||
examenes: sumar(g.categorias.map(id => de(filasE, catExamenes, periodo, id))),
|
||||
})),
|
||||
pacientesVerificados: verificados,
|
||||
notas: [...new Set([...(examenes.notas ?? []), ...(pacientes.notas ?? [])])],
|
||||
@@ -104,49 +107,62 @@ export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacien
|
||||
}
|
||||
export const totalExamenes = (m: ModeloConteos) => sumar(m.examenes.map(c => c.n));
|
||||
|
||||
// Geometry the callouts rely on. The ring is height-bound (a 400 px figure with a 10 px margin above and below and
|
||||
// the pie over 90 % of that height), so its radius does not depend on the width of the card.
|
||||
const ALTO_DONA = 400, MARGEN_VERTICAL = 10, RADIO_DONA = Math.round((ALTO_DONA - 2 * MARGEN_VERTICAL) * .9 / 2);
|
||||
const MARGEN_ROTULO = 120, SALIDA_ROTULO = 28;
|
||||
const ALTO_DONA = 400, MARGEN_DONA = 8;
|
||||
const DIAMETRO_MAXIMO_DONA = 270;
|
||||
|
||||
/**
|
||||
* Exams by category around their total; nothing is drawn when a cell is unknown. A long label does not fit in the
|
||||
* ring: it is drawn outside, horizontal and on two lines, joined to its slice by a guide line, on the side of the
|
||||
* slice with room reserved for it so it never reaches the neighbouring chart. On a narrow card (`compacta`) the
|
||||
* callouts give way to a legend under the donut.
|
||||
*/
|
||||
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, compacta = false): PlotlyFigure {
|
||||
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, ancho = 390): PlotlyFigure {
|
||||
const total = totalExamenes(m);
|
||||
if (!total) return { data: [], layout: {} };
|
||||
const p = c2Theme(tema), n = m.examenes.map(c => c.n!);
|
||||
const larga = (i: number) => m.examenes[i].etiqueta.length > LARGO_ETIQUETA_INTERIOR && n[i] > 0;
|
||||
const porcentaje = (i: number) => percentNumber(100 * n[i] / total) + ' %';
|
||||
const dibujadas = (i: number) => !larga(i) && n[i] / total >= .05;
|
||||
// Each long label is a callout whose guide line ends inside its slice.
|
||||
let antes = 0;
|
||||
const llamadas = n.flatMap((v, i) => {
|
||||
const angulo = 2 * Math.PI * (antes + v / 2) / total;
|
||||
antes += v;
|
||||
if (compacta || !larga(i)) return [];
|
||||
const seno = Math.sin(angulo), coseno = Math.cos(angulo), dentro = Math.round(RADIO_DONA * .8), fuera = RADIO_DONA + SALIDA_ROTULO - dentro;
|
||||
const etiqueta = escapar(m.examenes[i].etiqueta), corte = etiqueta.indexOf(' (');
|
||||
return [{ x: .5, y: .5, xref: 'paper', yref: 'paper', xshift: Math.round(dentro * seno), yshift: Math.round(dentro * coseno),
|
||||
ax: Math.round(fuera * seno), ay: Math.round(-fuera * coseno), axref: 'pixel', ayref: 'pixel', showarrow: true, arrowhead: 0, arrowwidth: 1, arrowcolor: p.text,
|
||||
text: (corte > 0 ? etiqueta.slice(0, corte) + '<br>' + etiqueta.slice(corte + 1) : etiqueta) + '<br>' + porcentaje(i),
|
||||
align: seno >= 0 ? 'left' : 'right', xanchor: seno >= 0 ? 'left' : 'right', yanchor: 'middle', font: { size: 12, color: p.text }, lado: seno >= 0 ? 'r' : 'l' }];
|
||||
// Fit both label columns before sizing the ring. Use the same radius for Plotly and the guide lines.
|
||||
const margenEtiquetas = Math.min(90, 59 + Math.max(0, ancho - 230) * .2);
|
||||
const diametro = Math.max(1, Math.min(DIAMETRO_MAXIMO_DONA, ancho - 2 * (MARGEN_DONA + margenEtiquetas)));
|
||||
const radio = diametro / 2;
|
||||
const fraccionVertical = radio / (ALTO_DONA - 2 * MARGEN_DONA);
|
||||
const fuenteEtiqueta = Math.round(8 + (margenEtiquetas - 59) / 10);
|
||||
const fuenteUnidad = Math.min(11, Math.max(7, Math.round(radio / 7)));
|
||||
const separacionCentro = fuenteUnidad === 7 ? 6 : fuenteUnidad < 11 ? 7 : 8;
|
||||
const etiquetas = m.examenes.map(c => escapar(c.etiqueta));
|
||||
const porcentajes = n.map(v => percentNumber(100 * v / total));
|
||||
const centro = { x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false };
|
||||
// The pie starts at noon. Keep each callout on its slice's side and order the rows vertically,
|
||||
// so even several adjacent slivers get separate labels and their guide lines keep the same order.
|
||||
let acumulado = 0;
|
||||
const puntos = n.flatMap((valor, i) => {
|
||||
const angulo = 2 * Math.PI * (acumulado + valor / 2) / total;
|
||||
acumulado += valor;
|
||||
if (!valor) return [];
|
||||
const x = radio * Math.sin(angulo), y = radio * Math.cos(angulo);
|
||||
return [{ i, x, y }];
|
||||
});
|
||||
const lado = (l: string) => llamadas.some(a => a.lado === l) ? MARGEN_ROTULO : 10;
|
||||
return { data: [{ type: 'pie', hole: .6, sort: false, direction: 'clockwise', values: n, labels: m.examenes.map(c => escapar(c.etiqueta)),
|
||||
marker: { colors: m.examenes.map(c => c.color), line: { color: p.background, width: 2 } }, textinfo: 'text', textposition: 'inside',
|
||||
text: n.map((_, i) => dibujadas(i) ? escapar(m.examenes[i].etiqueta) + '<br>' + porcentaje(i) : ''),
|
||||
domain: { x: [0, 1], y: [.05, .95] },
|
||||
customdata: n.map(v => [miles(v), percentNumber(100 * v / total)]),
|
||||
hovertemplate: `%{label}<br>%{customdata[0]} ${par.unidades.examenes}, %{customdata[1]} %<extra></extra>` }],
|
||||
layout: { autosize: true, height: compacta ? ALTO_DONA + 40 : ALTO_DONA, showlegend: compacta, paper_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { t: MARGEN_VERTICAL, b: compacta ? 70 : MARGEN_VERTICAL, l: lado('l'), r: lado('r') },
|
||||
...(compacta ? { legend: { orientation: 'h', x: .5, xanchor: 'center', y: -.02, yanchor: 'top', font: { size: 12 } } } : {}),
|
||||
annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false, font: { size: 18, color: p.text },
|
||||
text: `<b>${miles(total)}</b><br>${par.unidades.examenes}` }, ...llamadas.map(({ lado: _lado, ...a }) => a)] }, config: { displayModeBar: false } };
|
||||
const llamadas = [-1, 1].flatMap(lado => {
|
||||
const columna = puntos.filter(punto => (punto.x < 0 ? -1 : 1) === lado).sort((a, b) => b.y - a.y);
|
||||
return columna.map(({ i, x, y }, fila) => {
|
||||
const altura = (columna.length - 1 - 2 * fila) * 24;
|
||||
const texto = etiquetas[i].replace(' (sin subcategoría)', '<br>(sin<br>subcategoría)');
|
||||
return {
|
||||
annotation: { ...centro, xshift: lado * (radio + 10), yshift: altura,
|
||||
xanchor: lado < 0 ? 'right' : 'left', align: lado < 0 ? 'right' : 'left',
|
||||
font: { size: fuenteEtiqueta, color: p.text }, text: texto + '<br>' + porcentajes[i] + ' %' },
|
||||
shape: { type: 'path', xref: 'paper', yref: 'paper', xsizemode: 'pixel', ysizemode: 'pixel',
|
||||
xanchor: .5, yanchor: .5, line: { color: p.text, width: 1 },
|
||||
path: 'M ' + Math.round(x) + ',' + Math.round(y) + ' L ' + lado * (radio + 3) + ',' + y + ' L ' + lado * (radio + 8) + ',' + altura },
|
||||
};
|
||||
});
|
||||
});
|
||||
return { data: [{ type: 'pie', hole: .54, sort: false, direction: 'clockwise', values: n, labels: etiquetas,
|
||||
marker: { colors: m.examenes.map(c => c.color), line: { color: p.background, width: 2 } }, textinfo: 'none',
|
||||
domain: { x: [0, 1], y: [.5 - fraccionVertical, .5 + fraccionVertical] },
|
||||
customdata: n.map((v, i) => [miles(v), porcentajes[i]]),
|
||||
hovertemplate: '%{value}<extra></extra>' }],
|
||||
layout: { autosize: true, height: ALTO_DONA, showlegend: false, paper_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { t: MARGEN_DONA, b: MARGEN_DONA, l: MARGEN_DONA, r: MARGEN_DONA },
|
||||
shapes: llamadas.map(({ shape }) => shape),
|
||||
annotations: [
|
||||
{ ...centro, yshift: separacionCentro, font: { size: fuenteUnidad + 3, color: p.text }, text: `<b>${miles(total)}</b>` },
|
||||
{ ...centro, yshift: -separacionCentro, font: { size: fuenteUnidad, color: p.text }, text: par.unidades.examenes },
|
||||
...llamadas.map(({ annotation }) => annotation),
|
||||
] }, config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
/** Per BI-RADS family: patients (in their most severe category) next to exams. No ratio between them is drawn. */
|
||||
|
||||
@@ -176,6 +176,8 @@ 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);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Theme } from './indicadores-c2-palette';
|
||||
import { c2Theme, groupBase, paintByGroup } from './indicadores-c2-palette';
|
||||
import { percentNumber, shareText } from './indicadores-format';
|
||||
|
||||
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
|
||||
@@ -39,10 +39,6 @@ function estado(celdas: Celda[]): Escenario['estado'] {
|
||||
return celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido'
|
||||
: celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado';
|
||||
}
|
||||
function promedio(colores: string[]): string {
|
||||
return '#' + [1, 3, 5].map(i => Math.round(colores.reduce((s, c) => s + parseInt(c.slice(i, i + 2), 16), 0) / colores.length)
|
||||
.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
function rgba(hex: string, alfa: number): string {
|
||||
const v = parseInt(hex.slice(1), 16);
|
||||
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`;
|
||||
@@ -128,9 +124,10 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
|
||||
if (new Set(orden.values()).size !== orden.size) return fail('Orden de categorías EU7 duplicado.');
|
||||
// Missing rows remain unavailable. Catalog order is used only for the accessible
|
||||
// list of missing categories; a partial distribution is never drawn as a donut.
|
||||
const categorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity));
|
||||
const grupos = [...new Set(categorias.map(c => c.grupo))].map(id => ({ id, etiqueta: nombres[id],
|
||||
color: promedio(categorias.filter(c => c.grupo === id).map(c => c.color)) }));
|
||||
const baseCategorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity));
|
||||
const colores = paintByGroup(baseCategorias.map(c => c.grupo));
|
||||
const categorias = baseCategorias.map((c, i) => ({ ...c, color: colores[i] }));
|
||||
const grupos = [...new Set(categorias.map(c => c.grupo))].map((id, i) => ({ id, etiqueta: nombres[id], color: groupBase(i) }));
|
||||
const celdas = Object.fromEntries(cats.map(c => [c.id, celda(g.get(JSON.stringify([null, c.id])))]));
|
||||
const totals = porEscenario['totales_estrato'];
|
||||
if (totals !== undefined && (!Array.isArray(totals) || !totals.every(registro))) return fail('Totales de escenario inválidos.');
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,208 @@
|
||||
// What this module covers: the indicator page and TEA's follow-up over the WebApi's FHIR endpoint. The catalog and
|
||||
// technical sheet from `Measure`, the data rows from `MeasureReport`, the periods from two one-report searches, the
|
||||
// C3r box plot, and the follow-up list and patient summary from `EpisodeOfCare` and `$resumen-tea`; each mapped into
|
||||
// the shapes the page reads and passed through the same checks.
|
||||
// Fixtures: `indicadores-fhir.fixtures.ts`, real responses of the WebApi over its TEA fixture database.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { Bundle, resources } from './fhir';
|
||||
import {
|
||||
cajaDeDatos, datosDeReportes, FhirIndicadoresPeriodos, FhirIndicadoresService, indicadorDeMeasure, Measure, periodoIniciado,
|
||||
periodosDesde, Report,
|
||||
} from './indicadores-fhir';
|
||||
import * as fx from './indicadores-fhir.fixtures';
|
||||
import { c1AlterationFigure } from './indicadores-c1-alteraciones';
|
||||
import { c2Figure } from './indicadores-c2-adapter';
|
||||
import { datosValidos } from './indicadores.service';
|
||||
import { FhirTeaSeguimientoService, mapaDeElectrodos } from './tea-seguimiento-fhir';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
|
||||
const measure = (id: string) => resources(fx.measures).find(m => m.id === id) as Measure;
|
||||
const reports = (bundle: Bundle) => resources(bundle, 'MeasureReport') as Report[];
|
||||
|
||||
describe('Indicadores sobre FHIR', () => {
|
||||
it('el catálogo sale de cada Measure con los ids, contratos, figuras y estratos de la página', () => {
|
||||
// Pins down: ids with underscores, the contract and figures from the extensions, the age stratum of a C1 and none
|
||||
// for a C2 (its stratifier holds the categories). Fails if the catalog stops matching the page's TEA ids.
|
||||
const catalog = resources(fx.measures).map(m => indicadorDeMeasure(m as Measure));
|
||||
const m21 = catalog.find(i => i.id === 'M21_diagnosticados_con_eeg')!;
|
||||
expect(m21).toMatchObject({ contrato: 'C1', figuras: ['fig_c1_barras_edad'], tipos_periodo: ['semestre', 'mes'], estratos: ['grupo_edad'], sentido: 'mayor_mejor' });
|
||||
expect(catalog.find(i => i.id === 'M28_casos_por_estado')).toMatchObject({ contrato: 'C2', estratos: [] });
|
||||
expect(catalog.find(i => i.id === 'M25_dias_mchat_diagnostico')).toMatchObject({ contrato: 'C3r', sentido: 'menor_mejor' });
|
||||
});
|
||||
|
||||
it('los grupos de M30 llegan como filas por alteración y dibujan sus barras', () => {
|
||||
// Pins down: a report's extra groups become one row each under the group's code, labelled by the Measure, and
|
||||
// that is what `fig_c1_barras_alteracion` draws. The report is written here in the WebApi's shape (the fixtures
|
||||
// hold none for M30). Fails if the groups are dropped or renamed on the way, or the figure stops reading them.
|
||||
const m30 = measure('M30-resultado-eeg');
|
||||
const pop = (code: string, count: number) => ({ code: { coding: [{ code }] }, count });
|
||||
const group = (code: string, n: number) => ({ code: { coding: [{ code }] }, population: [pop('denominator', 8), pop('numerator', n)],
|
||||
measureScore: { value: n / 8 } });
|
||||
const codes = (m30.group ?? []).map(g => g.code?.coding?.[0]?.code as string);
|
||||
const report = { resourceType: 'MeasureReport', id: 'M30-resultado-eeg-1', period: { start: '2025-07-01', end: '2025-12-31' },
|
||||
group: codes.map((c, i) => group(c, c === 'TOTAL' ? 4 : i % 3)) } as unknown as Report;
|
||||
const datos = datosValidos(datosDeReportes(m30, [report], 'semestre'), 'M30_resultado_eeg', 'semestre', ['2025-S2']);
|
||||
expect(datos.filas.map(f => f['grupo'])).toEqual(codes);
|
||||
expect(codes).toContain('ritmo_posterior');
|
||||
const result = c1AlterationFigure(datos, { dominio: 'tea', indicador: 'M30_resultado_eeg', figura: 'fig_c1_barras_alteracion',
|
||||
tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] });
|
||||
if (result.status !== 'supported') throw new Error(result.reason);
|
||||
const [trace] = result.figure.data as Record<string, unknown>[];
|
||||
expect(trace['x']).toEqual(['Alguna alteración', 'Ritmo posterior', 'Husos de sueño N2', 'Husos de sueño N3', 'Picos paroxísticos',
|
||||
'Gradiente anteroposterior']);
|
||||
expect((trace['y'] as number[])[0]).toBe(50);
|
||||
});
|
||||
|
||||
it('una proporción da numerador, denominador y porcentaje, y por grupo de edad los códigos de la página', () => {
|
||||
// Pins down: the score becomes a percentage, the age groups `16-23`..., and an empty «Sin dato» stratum is left
|
||||
// out. Fails if the fraction isn't multiplied, the codes keep FHIR's underscore or the empty stratum becomes a bar.
|
||||
const total = datosValidos(datosDeReportes(measure('M21-diagnosticados-con-eeg'), reports(fx.m21Semestres), 'semestre'),
|
||||
'M21_diagnosticados_con_eeg', 'semestre');
|
||||
expect(total.periodos).toEqual(['2025-S1', '2025-S2']);
|
||||
expect(total.filas[0]).toMatchObject({ periodo: '2025-S1', grupo: 'TOTAL', estrato: null, numerador: 2, denominador: 2, valor: 100, suprimido: 0 });
|
||||
const porEdad = datosDeReportes(measure('M21-diagnosticados-con-eeg'), reports(fx.m21Semestres), 'semestre', { estrato: 'grupo_edad' });
|
||||
expect(porEdad['valores_estrato']).toEqual(['16-23', '24-29', '30-36']);
|
||||
expect((porEdad['etiquetas_estrato'] as Record<string, string>)['16-23']).toBe('16 a 23 meses');
|
||||
});
|
||||
|
||||
it('una exclusión del denominador llega como n_excluido', () => {
|
||||
// Pins down: M24's neuropediatrics notes without F84.0 are counted apart. Fails if the exclusion is dropped.
|
||||
const datos = datosDeReportes(measure('M24-confirmacion-diagnostico'), reports(fx.m24Semestres), 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ numerador: 2, denominador: 5, valor: 40, n_excluido: 1 });
|
||||
});
|
||||
|
||||
it('una composición da todas sus categorías, también las de cero, y la página la dibuja', () => {
|
||||
// Pins down: one row per category of the Measure, in its order, with zeros for the absent ones, so the C2 adapter
|
||||
// accepts the partition. Fails if a category with no patients is left out (the page refuses an incomplete one).
|
||||
const datos = datosDeReportes(measure('M29-calidad-eeg'), reports(fx.m29Semestres), 'semestre');
|
||||
const s1 = datos.filas.filter(f => f['periodo'] === '2025-S1');
|
||||
expect(s1.map(f => [f['categoria'], f['n']])).toEqual([['BUENO', 2], ['MALO', 1], ['SIN_ANALIZAR', 0]]);
|
||||
const m28 = datosDeReportes(measure('M28-casos-por-estado'), [reports(fx.m28Semestres)[0]], 'semestre');
|
||||
const figure = c2Figure(m28, { indicador: 'M28_casos_por_estado', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', dominio: 'tea' });
|
||||
expect(figure.status).toBe('supported');
|
||||
});
|
||||
|
||||
it('una duración da mediana, cuartiles y unidad en días, y su caja por periodo', () => {
|
||||
// Pins down: the median and quartile extensions, `dias` (what the KPI card requires) and the box plot built here
|
||||
// instead of by the server. Fails if the quartiles are lost or the box plot stops having one box per period.
|
||||
const datos = datosDeReportes(measure('M25-dias-mchat-diagnostico'), reports(fx.m25Semestres), 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ mediana: 59.5, q1: 58.75, q3: 60.25, n: 2, n_sin_evento: 4, unidad: 'dias' });
|
||||
const caja = cajaDeDatos(datos as IndicadorDatos);
|
||||
expect(caja.data[0]).toMatchObject({ type: 'box', median: datos.filas.filter(f => f['mediana'] !== null).map(f => f['mediana']) });
|
||||
});
|
||||
|
||||
it('los periodos siguen al primero sin huecos y los que no han empezado se descartan', () => {
|
||||
// Pins down: semesters and months counted on from the first report, and none after today. Fails if a year
|
||||
// boundary is crossed wrongly or a future period is offered.
|
||||
expect(periodosDesde('2024-07-01', 'semestre', 3)).toEqual(['2024-S2', '2025-S1', '2025-S2']);
|
||||
expect(periodosDesde('2024-11-01', 'mes', 3)).toEqual(['2024-11', '2024-12', '2025-01']);
|
||||
const today = new Date(2025, 9, 15);
|
||||
expect(periodoIniciado('2025-S2', today)).toBe(true);
|
||||
expect(periodoIniciado('2025-11', today)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Servicios FHIR de indicadores', () => {
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), FhirIndicadoresService, FhirIndicadoresPeriodos] });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => http.verify());
|
||||
|
||||
it('pide los periodos elegidos de una medida a la búsqueda de MeasureReport', async () => {
|
||||
// Pins down: one `Measure` list per domain, and `/MeasureReport?measure=<canonical>&periodo=...`. Fails if the
|
||||
// request leaves the FHIR endpoint or loses the periods asked for.
|
||||
const service = TestBed.inject(FhirIndicadoresService);
|
||||
const answer = firstValueFrom(service.datos('tea', 'M21_diagnosticados_con_eeg', 'semestre', ['2025-S1', '2025-S2']));
|
||||
http.expectOne('/tea/fhir/Measure').flush(fx.measures);
|
||||
const request = http.expectOne(r => r.url === '/tea/fhir/MeasureReport');
|
||||
expect(request.request.params.get('measure')).toBe('https://isssteleon.org/fhir/Measure/M21-diagnosticados-con-eeg');
|
||||
expect(request.request.params.get('periodo')).toBe('2025-S1,2025-S2');
|
||||
request.flush(fx.m21Semestres);
|
||||
expect((await answer).filas.length).toBe(2);
|
||||
});
|
||||
|
||||
it('el inventario de periodos sale de dos búsquedas de un solo reporte', async () => {
|
||||
// Pins down: one report of each type and the search's total, shared by every measure of the domain. Fails if each
|
||||
// measure computes its own periods or every period is evaluated to list them.
|
||||
const periodos = TestBed.inject(FhirIndicadoresPeriodos);
|
||||
periodos.today = () => new Date(2025, 11, 31);
|
||||
const answer = firstValueFrom(periodos.periodos('tea', 'M28_casos_por_estado'));
|
||||
http.expectOne('/tea/fhir/Measure').flush(fx.measures);
|
||||
const semestres = http.expectOne(r => r.params.get('tipo-periodo') === 'semestre');
|
||||
expect(semestres.request.params.get('_count')).toBe('1');
|
||||
semestres.flush({ ...fx.m28Semestres, entry: fx.m28Semestres.entry!.slice(0, 1) });
|
||||
const first = reports(fx.m28Semestres)[0];
|
||||
http.expectOne(r => r.params.get('tipo-periodo') === 'mes').flush({ resourceType: 'Bundle', total: 12,
|
||||
entry: [{ resource: { ...first, period: { start: '2025-01-01', end: '2025-01-31' } } }] });
|
||||
const found = await answer;
|
||||
expect(found.filter(p => p.tipo === 'semestre').map(p => p.periodo)).toEqual(['2025-S2', '2025-S1']);
|
||||
expect(found.filter(p => p.tipo === 'mes').length).toBe(12);
|
||||
expect(await firstValueFrom(periodos.periodos('tea', 'M21_diagnosticados_con_eeg'))).toEqual(found);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Seguimiento de TEA sobre FHIR', () => {
|
||||
let http: HttpTestingController;
|
||||
let service: FhirTeaSeguimientoService;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), FhirTeaSeguimientoService] });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
service = TestBed.inject(FhirTeaSeguimientoService);
|
||||
});
|
||||
afterEach(() => http.verify());
|
||||
|
||||
it('la lista sale de los episodios con sus recursos incluidos y respeta filtros y página', async () => {
|
||||
// Pins down: the window and cut-off as `date`, the filters as search parameters, paging as `_count`/`_offset`,
|
||||
// and each row's age group, M-CHAT, ADOS-2, study EEG and alterations from the included resources. Fails if a
|
||||
// filter is dropped or a column stops coming from its resource.
|
||||
const answer = firstValueFrom(service.consultar({ corte: '2025-12-31', meses: 12, page: 1, page_size: 5, grupo_edad: '16-23 meses', estado_caso: 'completo' }));
|
||||
const list = http.expectOne(r => r.url === '/tea/fhir/EpisodeOfCare');
|
||||
expect(list.request.params.getAll('date')).toEqual(['ge2025-01-01', 'le2025-12-31']);
|
||||
expect(list.request.params.get('grupo-edad')).toBe('16_23');
|
||||
expect(list.request.params.get('status')).toBe('finished');
|
||||
expect(list.request.params.get('_count')).toBe('5');
|
||||
list.flush(fx.episodios);
|
||||
http.expectOne(r => r.url === '/tea/fhir/EpisodeOfCare/$resumen-eeg').flush(fx.resumenEeg);
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
||||
const response = await answer;
|
||||
expect(response.paginacion).toEqual({ page: 1, page_size: 5, total_items: 6, total_pages: 2 });
|
||||
expect(response.items[0]).toMatchObject({ id_seudonimo: 'P-4A59E9D8B4', grupo_edad: '16-23 meses', ultimo_eeg: '2025-05-20', mchat: 12,
|
||||
css_ados2: 7, modulo_ados2: '1', estado_caso: 'completo', alteraciones_eeg: 'anormal', alteraciones: ['ritmo_posterior'], pendientes: [] });
|
||||
expect(response.resumen_eeg).toMatchObject({ normales: 2, anormales: 1, sin_eeg: 3 });
|
||||
expect(response.tipos_alteracion.map(t => t.codigo)).toContain('ritmo_posterior');
|
||||
});
|
||||
|
||||
it('el resumen del paciente arma el ADOS-2, la calidad, las alteraciones y su mapa', async () => {
|
||||
// Pins down: ADOS-2 domains whose totals add up (the page checks it), quality criteria in channels or dB, each
|
||||
// metric's state and effects from the code system, and one map per evaluable metric from its electrodes. Fails if
|
||||
// the summary stops passing the page's checks or a map appears for a metric without electrodes.
|
||||
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
|
||||
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente);
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
||||
const detalle = await answer;
|
||||
expect(detalle.grupo_edad).toBe('16-23 meses');
|
||||
expect(detalle.ados2).toMatchObject({ modulo: '1', css: 7, clasificacion: 'autismo', nivel_css: 'moderado' });
|
||||
expect(detalle.eeg!.calidad).toBe('bueno');
|
||||
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'linea')).toMatchObject({ valor: 3.5, unidad: 'dB' });
|
||||
const ritmo = detalle.eeg!.alteraciones.find(a => a.codigo === 'ritmo_posterior')!;
|
||||
expect(ritmo).toMatchObject({ estado: 'disminuido', valor_z: -4.08 });
|
||||
expect(ritmo.efectos).toContain('Ritmo más lento de lo esperado para la edad.');
|
||||
expect(detalle.eeg!.mapas.map(m => m.codigo)).toEqual(['ritmo_posterior']);
|
||||
});
|
||||
|
||||
it('el mapa toma el valor de cada electrodo y deja en blanco lo que ninguno alcanza', () => {
|
||||
// Pins down: the electrode's own z at its position, regions averaged from the measured electrodes only, and no
|
||||
// value far from every electrode. Fails if the map paints the whole head from a few occipital electrodes.
|
||||
const mapa = mapaDeElectrodos('ritmo_posterior', 'Ritmo posterior', { O1: -2.8, O2: -2.4, Pz: -1.1 });
|
||||
const eje = Array.from({ length: 41 }, (_, i) => Math.round((-1 + i * .05) * 100) / 100);
|
||||
expect(mapa.z[eje.indexOf(-0.75)][eje.indexOf(-0.25)]).not.toBeNull();
|
||||
expect(mapa.z[eje.indexOf(0.75)][eje.indexOf(0)]).toBeNull();
|
||||
expect(mapa.regiones.map(r => r.codigo)).toEqual(['occipital', 'parietal']);
|
||||
expect(mapa.regiones[0].valor_z).toBe(-2.6);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,409 @@
|
||||
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';
|
||||
import {
|
||||
CAMA_MEASURE_IDS, CATEGORIA_HISTOPATOLOGIA_PAGINA, esMedidaCama, ESTRATO_BIRADS_PAGINA, ETIQUETA_CATEGORIA_NO_DECLARADA, GRUPO_PRINCIPAL_FHIR,
|
||||
GRUPO_PRINCIPAL_PAGINA, GRUPOS_HISTOPATOLOGIA_PAGINA,
|
||||
} from './indicadores-cama-fhir';
|
||||
|
||||
// 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: string | null; gravedad?: number | 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; CaMa's measures
|
||||
// have an explicit correspondence (`CAMA-BIRADS456-PACIENTE` -> `cama_birads_456_paciente`).
|
||||
export const indicadorId = (measureId: string) => CAMA_MEASURE_IDS[measureId] ?? 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 } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
// TEA's measures are named by their first segment (`M21`); CaMa's share the domain's, so theirs is the rest (`BIRADS456-PACIENTE`).
|
||||
const codigoDeFicha = (measureId: string) => esMedidaCama(measureId) ? measureId.slice(measureId.indexOf('-') + 1) : measureId.split('-')[0];
|
||||
|
||||
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: codigoDeFicha(measure.id ?? ''), 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 categories a composition's reports count that its Measure doesn't declare, in order of appearance, with their
|
||||
// captions. Only CaMa's: its BI-RADS 4 without subcategory is published this way.
|
||||
function categoriasNoDeclaradas(reports: Report[], declaradas: Record<string, Categoria>): Map<string, string> {
|
||||
const found = new Map<string, string>();
|
||||
for (const report of reports) {
|
||||
for (const stratum of report.group?.flatMap(g => g.stratifier?.[0]?.stratum ?? []) ?? []) {
|
||||
const categoria = code(stratum.value);
|
||||
if (!categoria || Object.hasOwn(declaradas, categoria) || found.has(categoria) || !(stratum.population?.[0]?.count)) continue;
|
||||
found.set(categoria, ETIQUETA_CATEGORIA_NO_DECLARADA[categoria] ?? display(stratum.value) ?? categoria);
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
// The cross of the two stratifiers of CaMa's histopathological result (BI-RADS by biopsy grade) in one report, in the
|
||||
// page's codes. FHIR publishes only the cells that have patients; the report is complete, so a cell it doesn't list is
|
||||
// zero. A code the correspondence tables don't know, or cells that don't add up to the report's units, is an error.
|
||||
function cruceDeHistopatologia(group: Group, estrato: string): Map<string, number> {
|
||||
const stratifier = group.stratifier?.find(s => Array.isArray(s.code) && s.code.length === 2 && code(s.code[0]) === estrato);
|
||||
const unidades = count(group.population, 'initial-population');
|
||||
// A report with no units has no cell to cross: it is a published matrix of zeros, not a missing stratifier.
|
||||
if (!stratifier && unidades === 0) return new Map();
|
||||
if (!stratifier) throw new Error('Dimensión no admitida');
|
||||
const celdas = new Map<string, number>();
|
||||
for (const stratum of stratifier.stratum ?? []) {
|
||||
const bi = stratum.component?.find(c => code(c.code) === estrato), cat = stratum.component?.find(c => code(c.code) !== estrato);
|
||||
const e = ESTRATO_BIRADS_PAGINA[code(bi?.value) ?? ''], c = CATEGORIA_HISTOPATOLOGIA_PAGINA[code(cat?.value) ?? ''];
|
||||
if (!e || !c) throw new Error('Código de histopatología no reconocido');
|
||||
const clave = `${e}|${c.id}`;
|
||||
celdas.set(clave, (celdas.get(clave) ?? 0) + (stratum.population?.[0]?.count ?? 0));
|
||||
}
|
||||
if (unidades !== null && [...celdas.values()].reduce((sum, n) => sum + n, 0) !== unidades) {
|
||||
throw new Error('Los conteos por categoría no suman las unidades del periodo');
|
||||
}
|
||||
return celdas;
|
||||
}
|
||||
|
||||
// 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), estrato = scope.estrato, cama = esMedidaCama(measure.id);
|
||||
const declaradas = categorias(measure);
|
||||
const extras = kind === 'C2' && cama ? categoriasNoDeclaradas(reports, declaradas) : new Map<string, string>();
|
||||
// The histopathological result by BI-RADS asked by its stratum is read as a matrix of the page's codes (see above).
|
||||
const cruzado = kind === 'C2' && estrato !== undefined && CAMA_MEASURE_IDS[measure.id ?? ''] === 'cama_histopatologia_birads';
|
||||
const cats: Record<string, Categoria> = cruzado
|
||||
? Object.fromEntries(Object.entries(declaradas).map(([codigo, c]) => {
|
||||
const m = CATEGORIA_HISTOPATOLOGIA_PAGINA[codigo];
|
||||
if (!m) throw new Error('Categoría de histopatología no reconocida');
|
||||
return [m.id, { ...c, grupo: m.grupo, gravedad: m.gravedad }];
|
||||
}))
|
||||
: { ...declaradas,
|
||||
...Object.fromEntries([...extras].map(([categoria, etiqueta]) => [categoria, { etiqueta, color: null, grupo: null }])) };
|
||||
const totales: Record<string, unknown>[] = [];
|
||||
// CaMa's page names the primary group of a proportion `total`; the WebApi names it `principal`.
|
||||
const nombre = (codigo: string | undefined) => {
|
||||
const grupo = codigo ?? 'TOTAL';
|
||||
return cama && kind === 'C1' && grupo === GRUPO_PRINCIPAL_FHIR ? GRUPO_PRINCIPAL_PAGINA : grupo;
|
||||
};
|
||||
const grupos = Object.fromEntries((measure.group ?? []).map(g => {
|
||||
const id = nombre(code(g.code));
|
||||
return [id, id === 'TOTAL' || id === GRUPO_PRINCIPAL_PAGINA ? '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 = nombre(code(group.code));
|
||||
if (cruzado) {
|
||||
const celdas = cruceDeHistopatologia(group, estrato!);
|
||||
Object.values(ESTRATO_BIRADS_PAGINA).forEach(e => {
|
||||
let total = 0;
|
||||
Object.keys(cats).forEach((categoria, orden) => {
|
||||
const n = celdas.get(`${e}|${categoria}`) ?? 0;
|
||||
total += n;
|
||||
filas.push({ periodo, grupo, estrato: e, categoria, n, orden, suprimido: 0 });
|
||||
});
|
||||
totales.push({ periodo, grupo, estrato: e, n: total, suprimido: 0 });
|
||||
valores.set(e, e);
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (kind === 'C2') {
|
||||
const strata = group.stratifier?.[0]?.stratum ?? [];
|
||||
const counts = new Map(strata.map(s => [code(s.value), s.population?.[0]?.count ?? 0]));
|
||||
// A report whose categories don't add up to its units can't be drawn as a partition; say so, don't undercount.
|
||||
const units = count(group.population, 'initial-population');
|
||||
if (cama && units !== null && [...counts.values()].reduce((sum, n) => sum + n, 0) !== units) {
|
||||
throw new Error('Los conteos por categoría no suman las unidades del periodo');
|
||||
}
|
||||
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: cruzado ? {} : Object.fromEntries(valores) } : { valores_estrato: [] }),
|
||||
...(cruzado ? { totales_estrato: totales } : {}),
|
||||
grupos,
|
||||
categorias: cats,
|
||||
grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : {},
|
||||
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 }));
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user