Compare commits
19 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 88c1eb33be | |||
| 73b88de0ca | |||
| 6039e6b741 | |||
| b5bff7e0c6 | |||
| ddb203857f | |||
| 0f0f85db39 | |||
| 7fcc0091d7 | |||
| 5d3603740a | |||
| 3e3ec5fd03 | |||
| a15e37ed77 | |||
| 245622b490 | |||
| ea2664f324 | |||
| 1342b1712d | |||
| dc631d9827 | |||
| 2a48c28245 | |||
| e1a8127c22 | |||
| 6de193f44e | |||
| 0059427179 | |||
| 8192f92be9 |
@@ -3,11 +3,12 @@ import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models';
|
||||
import { identidadDe, identidadesDe } from './paciente-identidad';
|
||||
import { PAGE_SIZE_MAX } from './seguimiento-tabla.service';
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string';
|
||||
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
|
||||
export function validSeguimientoQuery(q: SeguimientoQuery) {
|
||||
return (!q.corte || isoDate(q.corte)) && [1,3,6,12].includes(q.meses) && integer(q.page, 1) && integer(q.page_size, 1) && q.page_size <= 200;
|
||||
return (!q.corte || isoDate(q.corte)) && [1,3,6,12].includes(q.meses) && integer(q.page, 1) && integer(q.page_size, 1) && q.page_size <= PAGE_SIZE_MAX;
|
||||
}
|
||||
export function seguimientoResponse(v: unknown): SeguimientoResponse {
|
||||
// The current authorization covers demonstration records only. Validate this
|
||||
@@ -18,7 +19,7 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse {
|
||||
|| !record(filters) || (filters['estatus'] !== null && typeof filters['estatus'] !== 'string')
|
||||
|| !Array.isArray(v['estatus_disponibles']) || !v['estatus_disponibles'].every(status)
|
||||
|| !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string))
|
||||
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|
||||
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > PAGE_SIZE_MAX || !integer(p['total_items']) || !integer(p['total_pages'])
|
||||
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => {
|
||||
if (!record(item) || !identidadDe(item) || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false;
|
||||
const c = item['ultima_citologia'], h = item['ultimo_vph'];
|
||||
|
||||
@@ -187,7 +187,7 @@ describe('KPI integración con autoridad global', () => {
|
||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['5', undefined, '7', undefined, undefined]);
|
||||
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(['pacientes', undefined, 'días (mediana)', undefined, undefined]);
|
||||
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu'
|
||||
? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible']
|
||||
? ['Disponible', 'Selección no consolidable', 'Disponible', 'Integración pendiente', 'Integración pendiente']
|
||||
: ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Indicador no disponible']);
|
||||
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining(domain === 'cacu' ? '5 citologías; primer cuartil: 3 días; tercer cuartil: 9 días.' : '5 mastografías; Q1 a Q3: 3 a 9 días.'),
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
<mat-card class="route" aria-label="Días desde la toma de muestra hasta cada evento de la ruta del tamizaje">
|
||||
<header><div class="card-identity"><h2 class="figure-title">Tiempos de la ruta del tamizaje</h2></div></header>
|
||||
@switch (status()) {
|
||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando los tiempos de la ruta del tamizaje" /><p role="status">Cargando los tiempos de la ruta…</p> }
|
||||
@case ('error') { <div role="alert"><p>{{ message() }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
@case ('incompatible') { <div role="alert"><p>{{ message() }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@if (model(); as m) {
|
||||
<div class="controls">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Periodo</mat-label>
|
||||
<mat-select [value]="m.period" (selectionChange)="selectPeriod($event.value)" aria-label="Periodo de la ruta del tamizaje">
|
||||
@for (period of m.periods; track period) { <mat-option [value]="period">{{ periodLabel(period) }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-button-toggle-group [value]="view()" (change)="selectView($event.value)" aria-label="Vista de los tiempos">
|
||||
<mat-button-toggle value="cumulative">Acumulado desde la toma</mat-button-toggle>
|
||||
<mat-button-toggle value="steps">Por pasos</mat-button-toggle>
|
||||
</mat-button-toggle-group>
|
||||
</div>
|
||||
@if (status() === 'empty') { <p role="status">No hay tiempos publicados para esta ruta.</p> }
|
||||
@else if (figure(); as figure) {
|
||||
<app-plotly-chart [figure]="figure" [showNotes]="false" label="Días desde la toma de muestra hasta cada evento de la ruta del tamizaje" />
|
||||
}
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<div class="table-scroll" role="region" aria-label="Tabla de tiempos de la ruta del tamizaje" tabindex="0">
|
||||
<table><caption>Días por evento en {{ m.period ? periodLabel(m.period) : 'el periodo' }}</caption>
|
||||
<thead><tr><th scope="col">Evento</th><th scope="col">Desde la toma</th><th scope="col">Desde el paso anterior</th></tr></thead>
|
||||
<tbody>@for (row of m.rows; track row.step.id) {
|
||||
<tr><th scope="row">{{ row.step.label }}</th><td>{{ cellText(row.fromSample) }}</td><td>{{ cellText(row.fromPrevious) }}</td></tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
</mat-card>
|
||||
@@ -0,0 +1,13 @@
|
||||
// A card of its own, as wide as the grid like the pair of cards above it.
|
||||
:host { display: block; min-width: 0; grid-column: 1 / -1; }
|
||||
.route { min-width: 0; margin: 0; }
|
||||
.figure-title { margin: 0; font-size: 1.25rem; }
|
||||
p, h2, summary { overflow-wrap: anywhere; }
|
||||
.controls { display: flex; flex-wrap: wrap; gap: 1rem 1.5rem; align-items: center; margin-block: .75rem; }
|
||||
app-plotly-chart { --plot-height: 360px; }
|
||||
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; max-height: 28rem; }
|
||||
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||
caption { text-align: start; font-weight: 600; }
|
||||
@@ -0,0 +1,128 @@
|
||||
// What this module covers: the screening route component: when it loads, the seven requests it makes, what it draws for
|
||||
// each view and period, and its empty, error and incompatible states. The model and the figure have their own spec
|
||||
// (`screening-route.spec.ts`).
|
||||
// Fixtures: `payload`, synthetic C3r /datos shaped like /cacu/indicadores/<id>/datos; `ChartStub` stands for the chart.
|
||||
import { Component, input } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadorScreeningRoute } from './indicador-screening-route';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import { ROUTE_IDS } from './screening-route';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); }
|
||||
|
||||
const row = (periodo: string, n: number, q1: number, mediana: number, q3: number, suprimido = 0) =>
|
||||
({ periodo, grupo: 'TOTAL', estrato: null, n, q1, mediana, q3, n_sin_evento: 0, n_excluido: 0, suprimido, unidad: 'dias' });
|
||||
const MEDIANAS: Record<string, number> = {
|
||||
cacu_eu_tiempo_reporte: 7.9, cacu_dias_toma_colposcopia: 35.7, cacu_dias_resultado_colposcopia: 27.8, cacu_dias_toma_biopsia: 52.1,
|
||||
cacu_dias_colposcopia_biopsia: 16.4, cacu_dias_toma_diagnostico: 18.4, cacu_dias_biopsia_diagnostico: 12.8,
|
||||
};
|
||||
const payload = (id: string, suprimido = 0): IndicadorDatos => ({
|
||||
id, contrato: 'C3r', tipo_periodo: 'semestre', periodos: ['2025-S1', '2025-S2'], version: '1',
|
||||
filas: [row('2025-S1', 100, 3, MEDIANAS[id] + 1, MEDIANAS[id] + 9, suprimido), row('2025-S2', 120, 4, MEDIANAS[id], MEDIANAS[id] + 8, suprimido)],
|
||||
});
|
||||
|
||||
describe('Ruta del tamizaje: componente', () => {
|
||||
let f: ReturnType<typeof TestBed.createComponent<IndicadorScreeningRoute>>;
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorScreeningRoute], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorScreeningRoute, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
f = TestBed.createComponent(IndicadorScreeningRoute);
|
||||
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('tema', 'claro');
|
||||
});
|
||||
afterEach(() => { f.destroy(); http.match(() => true); http.verify(); });
|
||||
// The shared request queue runs a few at a time: answer in waves until nothing is left.
|
||||
function responder(entrega: (id: string) => IndicadorDatos = id => payload(id)) {
|
||||
const vistos: string[] = [];
|
||||
for (;;) {
|
||||
const pendientes = http.match(r => r.url.endsWith('/datos'));
|
||||
if (!pendientes.length) return vistos;
|
||||
for (const r of pendientes) { const id = r.request.url.split('/').at(-2)!; vistos.push(id); r.flush(entrega(id)); }
|
||||
f.detectChanges();
|
||||
}
|
||||
}
|
||||
const charts = () => f.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
||||
|
||||
it('carga diferida; pide las siete medidas; dibuja una gráfica y cambia de vista y de periodo sin otra petición', () => {
|
||||
// Pins down: nothing is requested while hidden, each of the seven measures is requested once, the view and the period
|
||||
// are chosen without new requests, and the theme redraws the same data. Fails if the region loads before it is
|
||||
// visible, a measure is missing or repeated, or a control triggers a request.
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
|
||||
f.componentRef.setInput('visible', true); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('loading');
|
||||
expect(responder().sort()).toEqual([...ROUTE_IDS].sort());
|
||||
expect(f.componentInstance.status()).toBe('ready');
|
||||
expect(charts()).toHaveLength(1);
|
||||
expect(charts()[0].figure()).toBe(f.componentInstance.figure());
|
||||
expect((f.componentInstance.figure()!.data[0] as Record<string, unknown>)['base']).toBeUndefined();
|
||||
f.componentInstance.selectView('steps'); f.detectChanges();
|
||||
expect((f.componentInstance.figure()!.data[0] as Record<string, unknown>)['base']).toBeDefined();
|
||||
f.componentInstance.selectPeriod('2025-S1'); f.detectChanges();
|
||||
expect(f.componentInstance.model()!.period).toBe('2025-S1');
|
||||
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
|
||||
expect(f.componentInstance.figure()!.layout['paper_bgcolor']).toBe('#081839');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('la tabla de valores publicados dice la mediana de cada evento y el estado si no hay caja', () => {
|
||||
// Fails if the table drops an event or shows a suppressed box as a number.
|
||||
f.detectChanges();
|
||||
responder(id => (id === 'cacu_dias_toma_biopsia' ? payload(id, 1) : payload(id)));
|
||||
const text = f.nativeElement.querySelector('table').textContent as string;
|
||||
expect(text).toContain('Resultado de citología');
|
||||
expect(text).toContain('mediana 35.7');
|
||||
expect(text).toContain('Suprimido');
|
||||
});
|
||||
it('sin ninguna caja publicada muestra estado vacío y no dibuja', () => {
|
||||
// Fails if an empty route draws a chart or hides the reason.
|
||||
f.detectChanges();
|
||||
responder(id => payload(id, 1));
|
||||
expect(f.componentInstance.status()).toBe('empty');
|
||||
expect(charts()).toHaveLength(0);
|
||||
expect(f.nativeElement.textContent).toContain('No hay tiempos publicados');
|
||||
});
|
||||
it('un fallo del servicio se anuncia como error y reintentar vuelve a pedir', () => {
|
||||
// Fails if an error leaves a stale chart, hides the alert, or retry does not request again.
|
||||
f.detectChanges();
|
||||
http.match(r => r.url.endsWith('/datos'))[0].flush({}, { status: 500, statusText: 'Server Error' });
|
||||
f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('error');
|
||||
expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
|
||||
expect(charts()).toHaveLength(0);
|
||||
http.match(() => true); // the other requests of the first try were cancelled with it
|
||||
f.componentInstance.retry(); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('loading');
|
||||
expect(responder().length).toBe(ROUTE_IDS.length);
|
||||
expect(f.componentInstance.status()).toBe('ready');
|
||||
});
|
||||
it('datos de otro contrato quedan incompatibles y no se dibujan', () => {
|
||||
// Fails if a payload that is not a duration is drawn as one.
|
||||
f.detectChanges();
|
||||
responder(id => (id === 'cacu_dias_toma_biopsia' ? { ...payload(id), contrato: 'C1' } : payload(id)));
|
||||
expect(f.componentInstance.status()).toBe('incompatible');
|
||||
expect(charts()).toHaveLength(0);
|
||||
expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
|
||||
});
|
||||
it('es una tarjeta con su encabezado y abre en el periodo del filtro general; otro filtro suelta el periodo elegido adentro', () => {
|
||||
// Fails if the chart is not a card of its own, ignores the periods of the general filter, or keeps a period picked
|
||||
// inside it after the filter changed.
|
||||
f.componentRef.setInput('periodos', ['2025-S1']);
|
||||
f.detectChanges(); responder();
|
||||
expect(f.nativeElement.querySelector('mat-card h2')?.textContent).toContain('Tiempos de la ruta del tamizaje');
|
||||
expect(f.componentInstance.model()?.period).toBe('2025-S1');
|
||||
f.componentInstance.selectPeriod('2025-S2');
|
||||
expect(f.componentInstance.model()?.period).toBe('2025-S2');
|
||||
f.componentRef.setInput('periodos', ['2025-S2']); f.detectChanges();
|
||||
expect(f.componentInstance.requestedPeriod()).toBeUndefined();
|
||||
expect(f.componentInstance.model()?.period).toBe('2025-S2');
|
||||
// A period the route does not publish falls back to the newest that has data.
|
||||
f.componentRef.setInput('periodos', ['2019-S1']); f.detectChanges();
|
||||
expect(f.componentInstance.model()?.period).toBe('2025-S2');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { forkJoin, Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
|
||||
import { etiquetaPeriodo } from './indicadores-historico-figures';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
import { ROUTE_IDS, RouteIncompatible, RouteView, routeCellText, routeFigure, routeHasData, routeModel } from './screening-route';
|
||||
|
||||
/** Days along the screening route, from the sample to each event, as horizontal bars: cumulative or step by step. */
|
||||
@Component({
|
||||
selector: 'app-indicador-screening-route',
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatCardModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
|
||||
templateUrl: './indicador-screening-route.html',
|
||||
styleUrl: './indicador-screening-route.scss',
|
||||
})
|
||||
export class IndicadorScreeningRoute {
|
||||
readonly dominio = input.required<Dominio>();
|
||||
readonly tema = input.required<Tema>();
|
||||
/** The general filter's interval (semester or month) and, when it names periods, those periods. */
|
||||
readonly tipo = input<TipoPeriodo>('semestre');
|
||||
readonly periodos = input<readonly string[] | undefined>(undefined);
|
||||
/** The measures load once the region is visible. */
|
||||
readonly visible = input(true);
|
||||
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
readonly message = signal('');
|
||||
readonly view = signal<RouteView>('cumulative');
|
||||
readonly requestedPeriod = signal<string | undefined>(undefined);
|
||||
private readonly payloads = signal<Record<string, IndicadorDatos> | undefined>(undefined);
|
||||
readonly model = computed(() => {
|
||||
const data = this.payloads();
|
||||
return data ? routeModel(data, this.tipo(), this.requestedPeriod() ?? this.periodoDelFiltro(data)) : undefined;
|
||||
});
|
||||
readonly figure = computed(() => {
|
||||
const model = this.model();
|
||||
return model && routeHasData(model) ? routeFigure(model, this.view(), this.tema()) : undefined;
|
||||
});
|
||||
// The newest period of the general filter that the route publishes; the chart shows one period at a time.
|
||||
private periodoDelFiltro(data: Record<string, IndicadorDatos>) {
|
||||
const pedidos = this.periodos();
|
||||
if (!pedidos?.length) return undefined;
|
||||
const publicados = new Set(ROUTE_IDS.flatMap(id => data[id].periodos));
|
||||
return [...pedidos].sort().reverse().find(p => publicados.has(p));
|
||||
}
|
||||
readonly periodLabel = etiquetaPeriodo;
|
||||
readonly cellText = routeCellText;
|
||||
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private subscription?: Subscription;
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const dominio = this.dominio(), tipo = this.tipo();
|
||||
if (!this.visible()) { this.status.set('deferred'); return; }
|
||||
untracked(() => this.load(dominio, tipo));
|
||||
});
|
||||
// Another general filter is another question: the period picked inside the card no longer holds.
|
||||
effect(() => { this.tipo(); this.periodos(); untracked(() => this.requestedPeriod.set(undefined)); });
|
||||
inject(DestroyRef).onDestroy(() => this.subscription?.unsubscribe());
|
||||
}
|
||||
|
||||
retry() { this.load(this.dominio(), this.tipo()); }
|
||||
selectPeriod(period: string) { this.requestedPeriod.set(period); }
|
||||
selectView(view: RouteView) { this.view.set(view); }
|
||||
|
||||
private load(dominio: Dominio, tipo: TipoPeriodo) {
|
||||
this.subscription?.unsubscribe();
|
||||
this.payloads.set(undefined);
|
||||
this.status.set('loading');
|
||||
const requests = Object.fromEntries(ROUTE_IDS.map(id => [id, this.snapshots.datos(dominio, id, tipo)]));
|
||||
this.subscription = forkJoin(requests).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: data => {
|
||||
try {
|
||||
const model = routeModel(data, tipo, this.requestedPeriod());
|
||||
this.payloads.set(data);
|
||||
this.status.set(routeHasData(model) ? 'ready' : 'empty');
|
||||
} catch (error) { this.failure(error); }
|
||||
},
|
||||
error: error => this.failure(error),
|
||||
});
|
||||
}
|
||||
|
||||
private failure(error: unknown) {
|
||||
this.payloads.set(undefined);
|
||||
this.message.set(error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
||||
: error instanceof RouteIncompatible ? error.message : httpMessage(error));
|
||||
this.status.set(error instanceof RouteIncompatible || (error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError))
|
||||
? 'incompatible' : 'error');
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
|
||||
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
|
||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { historicoFigura } from './indicadores-historico-figures';
|
||||
|
||||
const STRUCTURE = 'https://isssteleon.org/fhir/StructureDefinition';
|
||||
const ENDPOINT = ['CACU-CONFIRMACION-CITOLOGIA', 'CACU-DIAS-TOMA-DIAGNOSTICO', 'CACU-EU-TIEMPO-REPORTE', 'CACU-EU13', 'CACU-EU7',
|
||||
@@ -130,4 +131,37 @@ describe('Las medidas de CaCu como las publica el WebApi con figuras y etiquetas
|
||||
expect(dibujo.status).toBe('supported');
|
||||
}
|
||||
});
|
||||
|
||||
it('un C1 publicado con su intervalo de Wilson llena la banda del histórico, en porcentaje', () => {
|
||||
// Pins down: the `ic-bajo` and `ic-alto` of a proportion's score (proportions) reach the rows as percentages and
|
||||
// the history trend draws them as its band. Fails if the bounds are read unconverted or dropped.
|
||||
const eu13 = medida('CACU-EU13');
|
||||
const cuenta = (code: string, count: number) => ({ code: { coding: [{ code }] }, count });
|
||||
const reporte13 = { resourceType: 'MeasureReport', id: 'CACU-EU13-1', period: { start: '2025-01-01', end: '2025-06-30' },
|
||||
group: [{ code: { coding: [{ code: 'principal' }] }, population: [cuenta('initial-population', 4), cuenta('denominator', 4), cuenta('numerator', 1)],
|
||||
measureScore: { value: 0.25, extension: [{ url: `${STRUCTURE}/ic-bajo`, valueDecimal: 0.0456 }, { url: `${STRUCTURE}/ic-alto`, valueDecimal: 0.6994 }] } }] } as unknown as Report;
|
||||
const datos = datosDeReportes(eu13, [reporte13], 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ valor: 25, ic_bajo: 4.6, ic_alto: 69.9 });
|
||||
const banda = (historicoFigura(datos, 'claro').figure as unknown as { data: { name: string; y: number[] }[] }).data[0];
|
||||
expect(banda.name).toBe('Intervalo de confianza');
|
||||
expect(banda.y).toEqual([69.9, 4.6]);
|
||||
});
|
||||
|
||||
it('un C1 de CaCu cuyo grupo se llama principal dibuja su tendencia en el histórico', () => {
|
||||
// Pins down: the WebApi names the group of a proportion `principal`; the page reads it as `total`, the group the
|
||||
// history trend draws, for CaCu as for CaMa. Fails if the rows keep the group `principal` and the trend comes out
|
||||
// empty, with its period listed as having no data.
|
||||
const cuenta = (code: string, count: number) => ({ code: { coding: [{ code }] }, count });
|
||||
for (const id of ['CACU-EU13', 'IND1']) {
|
||||
const medida13 = medida(id);
|
||||
const reporte = { resourceType: 'MeasureReport', id: id + '-1', period: { start: '2025-01-01', end: '2025-06-30' },
|
||||
group: [{ code: { coding: [{ code: 'principal' }] }, population: [cuenta('initial-population', 4), cuenta('denominator', 4), cuenta('numerator', 1)],
|
||||
measureScore: { value: 0.25 } }] } as unknown as Report;
|
||||
const datos = datosDeReportes(medida13, [reporte], 'semestre');
|
||||
expect(datos.filas[0]['grupo']).toBe('total');
|
||||
const figura = historicoFigura(datos, 'claro');
|
||||
expect((figura.figure as unknown as { data: { y: number[] }[] }).data[1].y).toEqual([25]);
|
||||
expect(figura.sinDato).toEqual([]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,7 +6,14 @@
|
||||
// the correspondence is explicit, as CaMa's is, and a measure outside it keeps the generic rule.
|
||||
export const CACU_MEASURE_IDS: Readonly<Record<string, string>> = {
|
||||
'CACU-CONFIRMACION-CITOLOGIA': 'cacu_confirmacion_citologia',
|
||||
'CACU-DIAS-BIOPSIA-DIAGNOSTICO': 'cacu_dias_biopsia_diagnostico',
|
||||
'CACU-DIAS-COLPOSCOPIA-BIOPSIA': 'cacu_dias_colposcopia_biopsia',
|
||||
'CACU-DIAS-DIAGNOSTICO-TRATAMIENTO': 'cacu_dias_diagnostico_tratamiento',
|
||||
'CACU-DIAS-RESULTADO-COLPOSCOPIA': 'cacu_dias_resultado_colposcopia',
|
||||
'CACU-DIAS-TOMA-BIOPSIA': 'cacu_dias_toma_biopsia',
|
||||
'CACU-DIAS-TOMA-COLPOSCOPIA': 'cacu_dias_toma_colposcopia',
|
||||
'CACU-DIAS-TOMA-DIAGNOSTICO': 'cacu_dias_toma_diagnostico',
|
||||
'CACU-DIAS-TOMA-TRATAMIENTO': 'cacu_dias_toma_tratamiento',
|
||||
'CACU-EU-TIEMPO-REPORTE': 'cacu_eu_tiempo_reporte',
|
||||
'CACU-EU13': 'cacu_eu13',
|
||||
'CACU-EU7': 'cacu_eu7',
|
||||
|
||||
@@ -87,8 +87,8 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', (
|
||||
'Pacientes evaluadas', 'Días de toma a resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento',
|
||||
]);
|
||||
for (const kpi of kpis.slice(3)) {
|
||||
expect(kpi.querySelectorAll('p')).toHaveLength(1);
|
||||
expect(kpi.querySelector('p')?.textContent).toBe('Indicador no disponible');
|
||||
expect(kpi.querySelector('.kpi-state')?.textContent?.trim()).toBe('Integración pendiente');
|
||||
expect(kpi.textContent).toContain('aún no está publicado');
|
||||
}
|
||||
expect(root.querySelector('.kpi-grid')?.getAttribute('style')).toContain('--kpi-count: 5');
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel))).toHaveLength(3);
|
||||
|
||||
@@ -58,6 +58,8 @@ function decimal(score: Score | undefined, name: string): number | null {
|
||||
return typeof value === 'number' ? value : null;
|
||||
}
|
||||
const round1 = (value: number) => Math.round(value * 10) / 10;
|
||||
// A proportion's bounds travel as proportions; the rows hold percentages, like `valor`.
|
||||
const percent = (value: number | null) => value === null ? null : round1(value * 100);
|
||||
|
||||
// A category's group is optional (`grupo` inside its `categoria`): a Measure that declares none, like CaMa's and TEA's,
|
||||
// keeps every category ungrouped.
|
||||
@@ -148,7 +150,7 @@ function proporcion(populations: Population[] | undefined, score: Score | undefi
|
||||
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'),
|
||||
ic_bajo: percent(decimal(score, 'ic-bajo')), ic_alto: percent(decimal(score, 'ic-alto')),
|
||||
n_sin_evento: numerador !== null && denominador !== null ? denominador - numerador : null,
|
||||
n_excluido: count(populations, 'denominator-exclusion') ?? 0,
|
||||
};
|
||||
|
||||
@@ -89,14 +89,9 @@ describe('Histórico de CaCu: grupo principal e identificadores reales', () => {
|
||||
expect(catalogo.get(panel.id)?.contrato).toBe(panel.contrato);
|
||||
}
|
||||
});
|
||||
it('los paneles reservados llevan los ids FHIR esperados y ninguno se activa por estar en el catálogo', () => {
|
||||
const reservados = HISTORICO_CACU.filter(p => disponibilidadDe(p) !== 'activo');
|
||||
expect(reservados.map(p => [p.id, p.fhir, disponibilidadDe(p)])).toEqual([
|
||||
['cacu_dias_toma_tratamiento', ['CACU-DIAS-TOMA-TRATAMIENTO'], 'integracion_pendiente'],
|
||||
['cacu_dias_diagnostico_tratamiento', ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'], 'integracion_pendiente'],
|
||||
['cacu_riesgo_banda', ['CACU-RIESGO-BANDA'], 'pendiente_validacion'],
|
||||
]);
|
||||
// The risk bands are in the catalog and stay reserved.
|
||||
it('todos los paneles del Histórico están activos; las medidas sin panel siguen en el catálogo', () => {
|
||||
expect(HISTORICO_CACU.filter(p => disponibilidadDe(p) !== 'activo')).toEqual([]);
|
||||
expect(HISTORICO_CACU.map(p => p.id)).not.toContain('cacu_riesgo_banda');
|
||||
expect(indicadorDeMeasure(medida('CACU-RIESGO-BANDA')).id).toBe('cacu_riesgo_banda');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
// Covers CaCu's history tab: the six active panels and the three reserved ones, what is requested and when (nothing
|
||||
// until the tab is open, nothing for a reserved panel, only the latest periods at first), the states of a panel, and
|
||||
// the notice. Responses are synthetic, shaped like /cacu/indicadores/<id>/periodos and /datos.
|
||||
// Covers CaCu's history tab: its six panels (the times to treatment and the risk by band have none), what is requested
|
||||
// and when (nothing until the tab is open, only the latest periods at first), the states of a panel, and the notice. Responses are synthetic, shaped like /cacu/indicadores/<id>/periodos and /datos.
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
@@ -9,7 +8,7 @@ import { By } from '@angular/platform-browser';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadoresHistorico } from './indicadores-historico';
|
||||
import { AVISO_CACU, HISTORICO_CACU } from './indicadores-historico-config';
|
||||
import { HISTORICO_CACU } from './indicadores-historico-config';
|
||||
import { Indicador } from './indicadores.models';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
@@ -20,10 +19,11 @@ const SEMESTRES = ['2023-S1', '2023-S2', '2024-S1', '2024-S2', '2025-S1', '2025-
|
||||
const CONTRATOS: Record<string, string> = { cacu_eu7: 'C2', ind1: 'C1', cacu_eu13: 'C1', cacu_confirmacion_citologia: 'C2', cacu_eu_tiempo_reporte: 'C3r',
|
||||
cacu_dias_toma_diagnostico: 'C3r', cacu_dias_toma_tratamiento: 'C3r', cacu_dias_diagnostico_tratamiento: 'C3r', cacu_riesgo_banda: 'C2' };
|
||||
const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico'];
|
||||
const RESERVADOS = ['cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda'];
|
||||
// Measures the catalog can publish that the history has no panel for.
|
||||
const SIN_PANEL = ['cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda'];
|
||||
const item = (id: string): Indicador => ({ id, titulo: id, contrato: CONTRATOS[id], figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador;
|
||||
// Every measure the catalog could publish, reserved ones included: publishing them must not activate them.
|
||||
const CATALOGO = [...ACTIVOS, ...RESERVADOS].map(item);
|
||||
// Every measure the catalog could publish: publishing the ones without a panel must not add one.
|
||||
const CATALOGO = [...ACTIVOS, ...SIN_PANEL].map(item);
|
||||
|
||||
function datos(id: string, tipo: string, periodos: string[], opciones: { contrato?: string; sinPoblacion?: string } = {}) {
|
||||
const contrato = opciones.contrato ?? CONTRATOS[id];
|
||||
@@ -91,36 +91,30 @@ describe('Histórico de CaCu', () => {
|
||||
fixture.detectChanges();
|
||||
}
|
||||
expect([...vistos].sort()).toEqual([...ACTIVOS].sort());
|
||||
for (const reservado of RESERVADOS) expect(vistos.has(reservado)).toBe(false);
|
||||
for (const id of SIN_PANEL) expect(vistos.has(id)).toBe(false);
|
||||
});
|
||||
it('dibuja nueve paneles en orden: seis con gráfica y tres reservados sin consultar', () => {
|
||||
it('dibuja seis paneles en orden, todos con gráfica, aunque el catálogo publique medidas sin panel', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CACU.map(p => p.titulo));
|
||||
expect(paneles()).toHaveLength(9);
|
||||
expect(paneles()).toHaveLength(6);
|
||||
expect(graficas()).toHaveLength(6);
|
||||
const reservados = paneles().slice(6);
|
||||
expect(reservados.every(p => !p.querySelector('app-plotly-chart') && !p.querySelector('mat-progress-bar'))).toBe(true);
|
||||
expect(reservados.map(p => p.querySelector('[data-reservado]')?.getAttribute('data-reservado'))).toEqual(['integracion', 'integracion', 'validacion']);
|
||||
expect(reservados[0].textContent).toContain('Integración pendiente');
|
||||
expect(reservados[2].textContent).toContain('Pendiente de validación');
|
||||
// Title and description, no figures, no invented numbers.
|
||||
expect(reservados[2].textContent).toContain('banda de riesgo de CIN2+');
|
||||
expect(reservados.every(p => !/\d+ de \d+|0 %|rango/i.test(p.querySelector('p.rango')?.textContent ?? ''))).toBe(true);
|
||||
expect(root().querySelector('[data-reservado]')).toBeNull();
|
||||
for (const titulo of ['Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento', 'Riesgo CIN2+ por banda']) expect(root().textContent).not.toContain(titulo);
|
||||
});
|
||||
it('un panel reservado sigue reservado aunque el catálogo no lo publique ni lo publique', () => {
|
||||
// Pins down: the state of a reserved panel comes from the config alone.
|
||||
for (const catalogo of [ACTIVOS.map(item), CATALOGO]) {
|
||||
montar(catalogo, true); responder();
|
||||
expect(paneles().slice(6).map(p => p.querySelector('[data-reservado]')?.getAttribute('data-reservado'))).toEqual(['integracion', 'integracion', 'validacion']);
|
||||
fixture.destroy(); TestBed.resetTestingModule();
|
||||
}
|
||||
it('ampliar dos veces seguidas (de 5 a 10 y a «Todos») sin esperar la primera respuesta deja todos los periodos', () => {
|
||||
// Fails if the second answer is dropped because the first one arrived before it: the periods stop at the 10.
|
||||
montar(CATALOGO, true); responder();
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegirVentana(10); fixture.detectChanges();
|
||||
fixture.componentInstance.elegirVentana(0); fixture.detectChanges();
|
||||
responder();
|
||||
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ene 2025 a dic 2025 (12 meses)');
|
||||
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12);
|
||||
});
|
||||
it('el aviso de validación clínica y supresión se ve siempre', () => {
|
||||
it('el Histórico de CaCu no lleva un aviso de validación clínica', () => {
|
||||
montar();
|
||||
const aviso = root().querySelector('[data-aviso="historico"]')!;
|
||||
expect(aviso.textContent).toBe(AVISO_CACU);
|
||||
expect(aviso.textContent).toContain('validación clínica');
|
||||
expect(aviso.textContent).toContain('supresión');
|
||||
expect(root().querySelector('[data-aviso="historico"]')).toBeNull();
|
||||
expect(root().textContent).not.toContain('supresión estadística');
|
||||
});
|
||||
it('al abrir pide solo los últimos cinco periodos de cada medida y no repite la lista', () => {
|
||||
// Pins down the first request: the page asks for the latest five months, not the twelve it could.
|
||||
|
||||
@@ -51,14 +51,10 @@ export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
|
||||
{ id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' },
|
||||
];
|
||||
|
||||
// Whether CaCu offers the history tab. The panels carry no clinical validation and no suppression policy yet (see
|
||||
// `AVISO_CACU`): while they wait, this is the switch that takes the tab out.
|
||||
// Whether CaCu offers the history tab: the switch that takes it out.
|
||||
export const HISTORICO_CACU_HABILITADO = true;
|
||||
|
||||
export const AVISO_CACU = 'Los resultados de CaCu están sujetos a validación clínica y a la política institucional de supresión estadística. '
|
||||
+ 'Los conjuntos clínicos, los horizontes y los umbrales son provisionales. No los use para decidir.';
|
||||
|
||||
// CaCu's history. The first six read the measures `dev` publishes; the last three are reserved.
|
||||
// CaCu's history: the six measures `dev` publishes. The times to treatment and the risk by band have no panel here.
|
||||
export const HISTORICO_CACU: readonly PanelHistorico[] = [
|
||||
{ id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', grafica: 'barras_apiladas' },
|
||||
{ id: 'ind1', titulo: 'Pacientes con citología anómala', contrato: 'C1', grafica: 'linea_porcentaje' },
|
||||
@@ -66,15 +62,6 @@ export const HISTORICO_CACU: readonly PanelHistorico[] = [
|
||||
{ id: 'cacu_confirmacion_citologia', titulo: 'Resultado de biopsia tras citología de alto grado', contrato: 'C2', grafica: 'barras_apiladas' },
|
||||
{ id: 'cacu_eu_tiempo_reporte', titulo: 'Días de la toma de la citología a su resultado', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||
{ id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||
{ id: 'cacu_dias_toma_tratamiento', titulo: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', grafica: 'linea_mediana', estado: 'integracion_pendiente',
|
||||
fhir: ['CACU-DIAS-TOMA-TRATAMIENTO'],
|
||||
descripcion: 'Días de la toma de la citología al primer tratamiento. La medida no está en el catálogo de dev.' },
|
||||
{ id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', grafica: 'linea_mediana', estado: 'integracion_pendiente',
|
||||
fhir: ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'],
|
||||
descripcion: 'Días del diagnóstico que resuelve la citología al primer tratamiento. La medida no está en el catálogo de dev.' },
|
||||
{ id: 'cacu_riesgo_banda', titulo: 'Riesgo CIN2+ por banda', contrato: 'C2', grafica: 'barras_apiladas', estado: 'pendiente_validacion',
|
||||
fhir: ['CACU-RIESGO-BANDA'],
|
||||
descripcion: 'Pacientes de la cohorte de vigilancia por banda de riesgo de CIN2+. El horizonte, el modelo y los cortes no están aprobados.' },
|
||||
];
|
||||
|
||||
const HISTORICOS: Readonly<Partial<Record<Dominio, HistoricoDominio>>> = {
|
||||
@@ -86,7 +73,6 @@ const HISTORICOS: Readonly<Partial<Record<Dominio, HistoricoDominio>>> = {
|
||||
periodosIniciales: 5,
|
||||
conciliarC2: true,
|
||||
c2SinPoblacionSinDato: true,
|
||||
aviso: AVISO_CACU,
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -28,9 +28,12 @@ const CASOS = 'M28_casos_por_estado';
|
||||
const PERSONALIZADO = -1;
|
||||
// What two answers for the same indicator give together: the periods, rows and reports of both.
|
||||
function unir(a: IndicadorDatos, b: IndicadorDatos): IndicadorDatos {
|
||||
const reportes = [...(Array.isArray(a['reportes']) ? a['reportes'] : []), ...(Array.isArray(b['reportes']) ? b['reportes'] : [])];
|
||||
// A period both have (two widenings asked for it) is kept once, from `a`.
|
||||
const nuevos = b.periodos.filter(p => !a.periodos.includes(p));
|
||||
const deNuevos = (fila: unknown) => !fila || typeof fila !== 'object' || !('periodo' in fila) || nuevos.includes(String((fila as { periodo: unknown }).periodo));
|
||||
const reportes = [...(Array.isArray(a['reportes']) ? a['reportes'] : []), ...(Array.isArray(b['reportes']) ? b['reportes'].filter(deNuevos) : [])];
|
||||
const unidades = { ...(a['unidades_periodo'] as object | undefined), ...(b['unidades_periodo'] as object | undefined) };
|
||||
return { ...a, periodos: [...a.periodos, ...b.periodos.filter(p => !a.periodos.includes(p))], filas: [...a.filas, ...b.filas],
|
||||
return { ...a, periodos: [...a.periodos, ...nuevos], filas: [...a.filas, ...b.filas.filter(deNuevos)],
|
||||
...(reportes.length ? { reportes } : {}), ...(a['unidades_periodo'] || b['unidades_periodo'] ? { unidades_periodo: unidades } : {}) };
|
||||
}
|
||||
|
||||
@@ -331,13 +334,19 @@ export class IndicadoresHistorico {
|
||||
const faltan = this.necesarios(carga.disponibles).filter(p => !carga.datos.periodos.includes(p));
|
||||
if (!faltan.length) continue;
|
||||
this.service.datos(this.dominio(), item.id, tipo, faltan).pipe(takeUntilDestroyed(this.destruccion)).subscribe({
|
||||
// The load may have been replaced by an earlier widening's answer: what counts is that the item is still ready, and
|
||||
// `unir` keeps a period once if two widenings asked for it. Comparing with the load this request started from
|
||||
// dropped the second answer when the first arrived before it (5 -> 10 -> Todos).
|
||||
next: datos => this.cargas.update(actual => {
|
||||
const vigente = actual[tipo]?.[item.id];
|
||||
return vigente?.estado === 'listo' && vigente === carga
|
||||
return vigente?.estado === 'listo'
|
||||
? { ...actual, [tipo]: { ...actual[tipo], [item.id]: { ...vigente, datos: unir(vigente.datos, datos) } } } : actual;
|
||||
}),
|
||||
error: error => this.cargas.update(actual => actual[tipo]?.[item.id] === carga
|
||||
? { ...actual, [tipo]: { ...actual[tipo], [item.id]: { estado: 'error', mensaje: httpMessage(error) } } } : actual),
|
||||
error: error => this.cargas.update(actual => {
|
||||
const vigente = actual[tipo]?.[item.id];
|
||||
return vigente?.estado === 'listo' && faltan.some(p => !vigente.datos.periodos.includes(p))
|
||||
? { ...actual, [tipo]: { ...actual[tipo], [item.id]: { estado: 'error', mensaje: httpMessage(error) } } } : actual;
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,7 +130,8 @@ describe('P0-C.1: cinco tarjetas de oportunidad', () => {
|
||||
expect(cards.map(c => c.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['20', '12', '52', undefined, undefined]);
|
||||
expect(cards.map(c => c.querySelector('.value span')?.textContent)).toEqual(['pacientes', 'días (mediana)', 'días (mediana)', undefined, undefined]);
|
||||
for (const card of cards.slice(3)) {
|
||||
expect(card.querySelectorAll('p')).toHaveLength(1); expect(card.querySelector('p')!.textContent).toBe('Indicador no disponible');
|
||||
expect(card.querySelector('.kpi-state')?.textContent?.trim()).toBe('Integración pendiente');
|
||||
expect(card.textContent).toContain('aún no está publicado');
|
||||
}
|
||||
http.expectNone(() => true);
|
||||
} finally { f.destroy(); vi.unstubAllGlobals(); http.verify(); }
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
// What this module covers: CaCu's two times to treatment: their ids from the API's measures, and their cards, which wait
|
||||
// as pending until the catalog publishes them and then give way to the real ones.
|
||||
import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
|
||||
import { CACU_TRATAMIENTO_KPIS, cacuPendingKpiCards } from './indicadores-kpi';
|
||||
|
||||
describe('Tiempos a tratamiento de CaCu', () => {
|
||||
it('las medidas del API se traducen a los ids de la web, sin quedar en mayúsculas', () => {
|
||||
// Fails if a measure is missing from the map: it would reach the page as CACU_DIAS_TOMA_TRATAMIENTO.
|
||||
expect(CACU_MEASURE_IDS['CACU-DIAS-TOMA-TRATAMIENTO']).toBe('cacu_dias_toma_tratamiento');
|
||||
expect(CACU_MEASURE_IDS['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO']).toBe('cacu_dias_diagnostico_tratamiento');
|
||||
expect(CACU_TRATAMIENTO_KPIS.map(k => k.id)).toEqual(['cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento']);
|
||||
});
|
||||
it('sin ninguna tarjeta dibujada no se agrega nada', () => {
|
||||
expect(cacuPendingKpiCards([])).toEqual([]);
|
||||
});
|
||||
it('las que el catálogo aún no publica quedan pendientes, y las publicadas ya no', () => {
|
||||
expect(cacuPendingKpiCards(['cacu_eu7']).map(c => [c.definition.id, c.pending])).toEqual([
|
||||
['cacu_dias_toma_tratamiento', true], ['cacu_dias_diagnostico_tratamiento', true]]);
|
||||
expect(cacuPendingKpiCards(['cacu_eu7', 'cacu_dias_toma_tratamiento']).map(c => c.definition.id)).toEqual(['cacu_dias_diagnostico_tratamiento']);
|
||||
expect(cacuPendingKpiCards(['cacu_eu7', ...CACU_TRATAMIENTO_KPIS.map(k => k.id)])).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -79,6 +79,16 @@ export function camaKpiCards(published: (id: string) => boolean): KpiCardSlot[]
|
||||
const cards = CAMA_OPORTUNIDAD_KPIS.map(definition => ({ definition, pending: !published(definition.id) }));
|
||||
return cards.some(card => !card.pending) ? cards : [];
|
||||
}
|
||||
// CaCu's two times to treatment stay outside KPI_BY_DOMAIN: they are queried only once the catalog publishes them, and
|
||||
// keep their cards, pending, until then. Nothing is added until some other card is drawn.
|
||||
export const CACU_TRATAMIENTO_KPIS: KpiDefinition[] = [
|
||||
{ id: 'cacu_dias_toma_tratamiento', title: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', unit: 'días (mediana)' },
|
||||
{ id: 'cacu_dias_diagnostico_tratamiento', title: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', unit: 'días (mediana)' },
|
||||
];
|
||||
export function cacuPendingKpiCards(drawn: readonly string[]): KpiCardSlot[] {
|
||||
if (!drawn.length) return [];
|
||||
return CACU_TRATAMIENTO_KPIS.filter(definition => !drawn.includes(definition.id)).map(definition => ({ definition, pending: true }));
|
||||
}
|
||||
// Published CaMa indicators whose card the summary does not draw.
|
||||
// The summary draws the paired card and the histopathology card; the rest of CaMa's indicators are in Histórico
|
||||
// and in Datos y definiciones, which still list the whole catalog.
|
||||
|
||||
@@ -52,7 +52,7 @@
|
||||
</div>
|
||||
@if (resumen) { <app-tea-resumen-periodo [periodo]="resumen" [paneles]="kpiPanels()" /> }
|
||||
<!-- With the summary the panels keep loading the data, but their cards are not shown. -->
|
||||
<div class="kpi-grid" [class.kpi-grid-oculto]="resumen" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : dominio === 'cama' ? 1 : 0)">
|
||||
<div class="kpi-grid" [class.kpi-grid-oculto]="resumen" [style.--kpi-count]="kpis.length + (dominio === 'cama' ? 1 : 0)">
|
||||
@for (card of kpis; track dominio + ':' + card.definition.id) {
|
||||
@if (card.pending) {
|
||||
<app-indicador-kpi-card [title]="card.definition.title" state="Integración pendiente"
|
||||
@@ -62,10 +62,7 @@
|
||||
[applied]="filters?.applied" [availability]="availability()" [initialPresentation]="false" />
|
||||
}
|
||||
}
|
||||
@if (dominio === 'cacu') {
|
||||
<app-indicador-kpi-card title="Tiempo de tamizaje a tratamiento" state="Indicador no disponible" />
|
||||
<app-indicador-kpi-card title="Tiempo de diagnóstico a tratamiento" state="Indicador no disponible" />
|
||||
} @else if (dominio === 'cama') {
|
||||
@if (dominio === 'cama') {
|
||||
<app-indicador-kpi-card title="Tiempo de diagnóstico a tratamiento" state="Indicador no disponible"
|
||||
additionalInfo="Este indicador aún no está publicado por el catálogo institucional." />
|
||||
}
|
||||
@@ -121,6 +118,10 @@
|
||||
<app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
|
||||
[pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" />
|
||||
}
|
||||
@if (screeningRouteAvailable && filters; as general) {
|
||||
<app-indicador-screening-route [dominio]="dominio" [tema]="tema" [tipo]="general.applied.tipo"
|
||||
[periodos]="general.applied.selection.mode === 'explicit' ? general.applied.selection.periodos : undefined" />
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
@@ -17,9 +17,11 @@ import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { esSocioConteos } from './indicadores-conteos-pareados';
|
||||
import { CACU_RESULTADO_KPI, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, KpiCardSlot, camaKpiCards } from './indicadores-kpi';
|
||||
import { CACU_RESULTADO_KPI, CACU_TRATAMIENTO_KPIS, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, KpiCardSlot, cacuPendingKpiCards, camaKpiCards } from './indicadores-kpi';
|
||||
import { TeaResumenPeriodo } from './tea-resumen-periodo';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { IndicadorScreeningRoute } from './indicador-screening-route';
|
||||
import { CACU_SIN_TARJETA, ROUTE_IDS } from './screening-route';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection';
|
||||
import { identityElementId, indicatorIdentity } from './indicadores-identities';
|
||||
@@ -53,7 +55,7 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-page',
|
||||
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
|
||||
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo, IndicadorScreeningRoute],
|
||||
templateUrl: './indicadores-page.html',
|
||||
styleUrl: './indicadores-page.scss',
|
||||
})
|
||||
@@ -335,8 +337,15 @@ export class IndicadoresPage {
|
||||
return this.dominio === 'cama' && !this.catalogLoading() && !this.catalogError() && this.catalog().length > 0
|
||||
&& !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA);
|
||||
}
|
||||
// CaCu's screening route chart, once the catalog publishes every measure it reads.
|
||||
get screeningRouteAvailable() {
|
||||
return this.dominio === 'cacu' && ROUTE_IDS.every(id => this.catalog().some(item => item.id === id));
|
||||
}
|
||||
// How many indicators the graphic section shows: all the catalog, except in CaMa, which draws only some of them.
|
||||
get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); }
|
||||
get availableKpis() {
|
||||
const definitions = this.dominio === 'cacu' ? [...this.kpisByDomain.cacu, ...CACU_TRATAMIENTO_KPIS] : this.kpisByDomain[this.dominio];
|
||||
return definitions.filter(definition => this.catalog().some(item => item.id === definition.id));
|
||||
}
|
||||
// TEA shows a summary paragraph instead of its cards for exactly one explicitly chosen period.
|
||||
get teaResumenPeriodo(): string | undefined {
|
||||
const selection = this.filters?.applied.selection;
|
||||
@@ -353,7 +362,8 @@ export class IndicadoresPage {
|
||||
// What the KPI grid draws. CaMa adds explicit pending cards for opportunity indicators the catalog does not publish.
|
||||
get kpiCards(): KpiCardSlot[] {
|
||||
if (this.dominio === 'cama') return camaKpiCards(id => this.catalog().some(item => item.id === id));
|
||||
return this.opportunityKpis.map(definition => ({ definition, pending: false }));
|
||||
const cards = this.opportunityKpis.map(definition => ({ definition, pending: false }));
|
||||
return this.dominio === 'cacu' ? [...cards, ...cacuPendingKpiCards(cards.map(card => card.definition.id))] : cards;
|
||||
}
|
||||
private readonly catalogRequests = new Subject<void>();
|
||||
readonly catalog = signal<Indicador[]>([]);
|
||||
@@ -364,8 +374,11 @@ export class IndicadoresPage {
|
||||
// Stable presentation order. Pins no longer reorder the summary.
|
||||
readonly catalogOrder = computed(() => {
|
||||
const catalog = this.catalog();
|
||||
// CaCu's page draws the cytology result and the confirmation as cards, and the route chart. The times of the route
|
||||
// get no card of their own once the chart is there; the rest live in the history (they have no figure here).
|
||||
const hidden = this.screeningRouteAvailable ? [...ROUTE_IDS, ...CACU_SIN_TARJETA] : [];
|
||||
return this.dominio === 'cacu'
|
||||
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')]
|
||||
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7' && !hidden.includes(item.id))]
|
||||
: this.dominio === 'cama' ? this.cardsDeCama(catalog)
|
||||
: catalog.filter(item => !item.vistas || item.vistas.includes('resumen'));
|
||||
});
|
||||
|
||||
@@ -11,7 +11,7 @@ describe('Regresión del mapeo FHIR en CaCu y TEA', () => {
|
||||
it('las 16 medidas se mapean igual que antes: ids, catálogo, ficha y filas de datos', () => {
|
||||
// Pins down: ids, catalog entries, sheets and data rows of CaCu's seven and TEA's nine measures, over real reports,
|
||||
// equal the recorded ones; an error counts as a result too. Fails if a change meant for CaMa (its id table, its
|
||||
// group name, its undeclared categories, its sheet code) reaches another domain. If the new result is the right one,
|
||||
// undeclared categories, its sheet code) reaches another domain. If the new result is the right one,
|
||||
// regenerate the recorded mapping and say why in the change.
|
||||
const actual = mapeoDeCacuYTea({ indicadorId, indicadorDeMeasure, metadatosDeMeasure, datosDeReportes });
|
||||
expect(Object.keys(actual)).toEqual(Object.keys(esperado));
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
// What this module covers: the screening route chart in CaCu's page: it appears only when the catalog publishes the seven
|
||||
// measures it reads, and then those measures that nothing else draws lose their own cards. Catalogs are synthetic,
|
||||
// shaped like /cacu/indicadores.
|
||||
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 { provideRouter } from '@angular/router';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorScreeningRoute } from './indicador-screening-route';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { Dominio } from './indicadores.models';
|
||||
import { CACU_SIN_TARJETA, ROUTE_IDS, ROUTE_ONLY_IDS } from './screening-route';
|
||||
|
||||
const item = (id: string, contrato = 'C3r') => ({ id, titulo: id, contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] });
|
||||
|
||||
describe('Ruta del tamizaje: página de CaCu', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
for (const domain of ['tea', 'cacu', 'cama'] as const) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
|
||||
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); });
|
||||
function abrir(domain: Dominio, catalog: unknown[]) {
|
||||
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
|
||||
http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges();
|
||||
http.match(() => true);
|
||||
}
|
||||
const ruta = () => fixture.nativeElement.querySelector('app-indicador-screening-route');
|
||||
const tarjetas = () => fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(d => (d.componentInstance as IndicadorCatalogCard).indicador.id);
|
||||
|
||||
it('con las siete medidas publicadas aparece la gráfica y CaCu deja solo las tarjetas que la gráfica no dibuja', () => {
|
||||
// Pins down: the chart replaces the cards of every measure it reads, the proportions without a figure and the times to
|
||||
// treatment live in the history, and the cytology result and its confirmation keep theirs. Fails if the chart stops
|
||||
// appearing, or one of those measures also shows as a card.
|
||||
abrir('cacu', [item('cacu_eu7', 'C2'), item('cacu_confirmacion_citologia', 'C2'), item('ind1', 'C1'), item('cacu_eu13', 'C1'),
|
||||
item('cacu_riesgo_banda', 'C2'), item('cacu_dias_toma_tratamiento'), item('cacu_dias_diagnostico_tratamiento'), ...ROUTE_IDS.map(id => item(id))]);
|
||||
expect(ruta()).not.toBeNull();
|
||||
const ids = tarjetas();
|
||||
for (const id of [...ROUTE_IDS, ...CACU_SIN_TARJETA]) expect(ids).not.toContain(id);
|
||||
expect(ids).toEqual(['cacu_eu7', 'cacu_confirmacion_citologia']);
|
||||
});
|
||||
it('la ruta es la última de la sección clínica, en su tarjeta y con el intervalo del filtro general', () => {
|
||||
// Fails if the chart is not the last card of the grid, is not inside a card, or does not follow the general filter's interval.
|
||||
abrir('cacu', [item('cacu_eu7', 'C2'), item('cacu_confirmacion_citologia', 'C2'), ...ROUTE_IDS.map(id => item(id))]);
|
||||
const grid = fixture.nativeElement.querySelector('.catalog-grid') as HTMLElement;
|
||||
expect(grid.lastElementChild?.tagName).toBe('APP-INDICADOR-SCREENING-ROUTE');
|
||||
expect(grid.lastElementChild?.querySelector('mat-card h2')?.textContent).toContain('Tiempos de la ruta del tamizaje');
|
||||
const ruta = fixture.debugElement.query(By.directive(IndicadorScreeningRoute)).componentInstance as IndicadorScreeningRoute;
|
||||
expect(ruta.tipo()).toBe(fixture.componentInstance.filters!.applied.tipo);
|
||||
});
|
||||
it('con la ruta, la franja de oportunidad conserva sus tarjetas: solo se retiran las de la sección clínica', () => {
|
||||
// Fails if the opportunity strip loses a card when the route chart appears.
|
||||
abrir('cacu', [item('cacu_eu7', 'C2'), ...ROUTE_IDS.map(id => item(id))]);
|
||||
const titulos = [...fixture.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card h3')].map((h: HTMLElement) => h.textContent);
|
||||
expect(titulos).toEqual(['Pacientes evaluadas', 'Días de toma a resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento']);
|
||||
});
|
||||
it('si el catálogo no publica alguna de las siete, no hay gráfica y las medidas conservan sus tarjetas', () => {
|
||||
// Fails if the chart appears with a measure missing, or the cards of the others disappear anyway.
|
||||
abrir('cacu', [item('cacu_eu7', 'C2'), ...ROUTE_IDS.filter(id => id !== 'cacu_dias_toma_biopsia').map(id => item(id))]);
|
||||
expect(ruta()).toBeNull();
|
||||
const ids = tarjetas();
|
||||
for (const id of ROUTE_ONLY_IDS.filter(id => id !== 'cacu_dias_toma_biopsia')) expect(ids).toContain(id);
|
||||
});
|
||||
it('las otras áreas no la tienen', () => {
|
||||
// Fails if the CaCu chart leaks into TEA or CaMa.
|
||||
abrir('cama', [item('cama_eu38a'), ...ROUTE_IDS.map(id => item(id))]);
|
||||
expect(ruta()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -195,13 +195,12 @@ describe('Seguimiento de CaMa (tabla)', () => {
|
||||
expect(root().querySelector('[role=alert]')?.textContent).toBe('La respuesta del servicio no tiene el formato esperado.');
|
||||
expect(root().querySelector('table')).toBeNull(); expect(root().textContent).not.toContain('M-0081');
|
||||
});
|
||||
it('un tamaño de página inválido no sale del navegador', async () => {
|
||||
it('un tamaño de página mayor al máximo se acota y no sale del navegador sin acotar', async () => {
|
||||
await cargado();
|
||||
const tam = campo('Registros por página').querySelector('input') as HTMLInputElement;
|
||||
tam.value = '500'; tam.dispatchEvent(new Event('input')); fixture.detectChanges();
|
||||
tam.value = '500'; tam.dispatchEvent(new Event('input')); tam.dispatchEvent(new Event('change')); fixture.detectChanges();
|
||||
boton('Consultar').click(); fixture.detectChanges();
|
||||
http.expectNone(() => true);
|
||||
expect(root().querySelector('[role=alert]')?.textContent).toContain('Revisa la fecha');
|
||||
expect(parametros(solicitud())).toMatchObject({ page_size: '200' });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import { TrackingExportBar } from './export/tracking-export-bar';
|
||||
import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card';
|
||||
import { CamaPatientSummary, toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models';
|
||||
import {
|
||||
consultaAplicada, ContextoLista, contextoDe, etiquetaVentana, MESES_VENTANA, MesesVentana, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery,
|
||||
consultaAplicada, ContextoLista, contextoDe, etiquetaVentana, MESES_VENTANA, MesesVentana, acotarTamano, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery,
|
||||
SeguimientoTablaResponse, SeguimientoTablaService, SeguimientoValor,
|
||||
} from './seguimiento-tabla.service';
|
||||
|
||||
@@ -76,7 +76,7 @@ const mismosFiltros = (a: Record<string, string | undefined>, b: Record<string,
|
||||
@for (o of filtro.opciones; track o.codigo) { <option [value]="o.codigo">{{ o.etiqueta }}</option> }
|
||||
</select></label>
|
||||
}
|
||||
<label>Registros por página <input name="size" type="number" min="1" [max]="tamanoMaximo" required [(ngModel)]="draft.page_size" /></label>
|
||||
<label>Registros por página <input name="size" type="number" min="1" [max]="tamanoMaximo" required [(ngModel)]="draft.page_size" (change)="draft.page_size = acotar(draft.page_size)" /></label>
|
||||
<button type="submit" [disabled]="estado() === 'loading'">Consultar</button>
|
||||
</form>
|
||||
@switch (estado()) {
|
||||
@@ -163,6 +163,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
|
||||
private readonly consultas = new Subject<Consulta | null>();
|
||||
readonly etiquetaVentana = etiquetaVentana;
|
||||
readonly tamanoMaximo = PAGE_SIZE_MAX;
|
||||
readonly acotar = acotarTamano;
|
||||
readonly estado = signal<Estado>('idle');
|
||||
readonly mensaje = signal('');
|
||||
readonly data = signal<SeguimientoTablaResponse | undefined>(undefined);
|
||||
@@ -315,7 +316,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
|
||||
this.appliedEtiqueta = etiqueta;
|
||||
// Another cut-off is another cohort at that date: its revision is not quoted, the answer brings the new one.
|
||||
const otroCorte = !!contexto && !seleccion && !!this.draft.corte && this.draft.corte !== this.contextoCorte;
|
||||
const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: Number(this.draft.page_size), filtros,
|
||||
const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: acotarTamano(this.draft.page_size), filtros,
|
||||
contexto: otroCorte ? undefined : contexto };
|
||||
// A new query of the cohort starts from nothing on screen: what was there belongs to the previous one.
|
||||
if (contexto) { this.data.set(undefined); this.etiquetaDatos.set(undefined); }
|
||||
|
||||
@@ -39,7 +39,7 @@ const finito = (v: unknown): v is number => typeof v === 'number' && Number.isFi
|
||||
const conteo = (v: unknown): v is number => finito(v) && Number.isSafeInteger(v) && v >= 0;
|
||||
const fail = (message: string): never => { throw new TiemposIncompatibles(message); };
|
||||
|
||||
function caja(fila: Record<string, unknown> | undefined): Caja {
|
||||
export function caja(fila: Record<string, unknown> | undefined): Caja {
|
||||
if (!fila) return { estado: 'No disponible' };
|
||||
if (fila['suprimido'] === 1) return { estado: 'Suprimido' };
|
||||
const { n, q1, mediana, q3 } = fila;
|
||||
|
||||
@@ -48,7 +48,7 @@
|
||||
@for (t of tiposAlteracion; track t.codigo) { <option [value]="t.codigo">{{ t.etiqueta }}</option> }
|
||||
</select></label>
|
||||
}
|
||||
<label>Registros por página <input name="size" type="number" min="1" max="200" required [(ngModel)]="draft.page_size" /></label>
|
||||
<label>Registros por página <input name="size" type="number" min="1" [max]="tamanoMaximo" required [(ngModel)]="draft.page_size" (change)="draft.page_size = acotar(draft.page_size)" /></label>
|
||||
<button type="submit" [disabled]="status === 'loading'">Consultar</button>
|
||||
</form>
|
||||
@if (status === 'loading') { <p role="status">Cargando seguimiento…</p> }
|
||||
|
||||
@@ -4,6 +4,7 @@ import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { catchError, defer, map, of, Subject, switchMap } from 'rxjs';
|
||||
import { CacuSeguimientoService, validSeguimientoQuery } from './cacu-seguimiento.service';
|
||||
import { acotarTamano, PAGE_SIZE_MAX } from './seguimiento-tabla.service';
|
||||
import { latestStudy, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle';
|
||||
@@ -30,6 +31,8 @@ export class IndicadoresTracking implements OnChanges {
|
||||
@Input() seleccion?: SeleccionSeguimiento;
|
||||
/** CaMa: the way back to the analysis the selection came from. */
|
||||
readonly volverAlAnalisis = output<void>();
|
||||
readonly tamanoMaximo = PAGE_SIZE_MAX;
|
||||
readonly acotar = acotarTamano;
|
||||
private readonly service = inject(CacuSeguimientoService);
|
||||
private readonly indicators = inject(IndicadoresService);
|
||||
private readonly teaService = inject(TeaSeguimientoService);
|
||||
@@ -119,11 +122,11 @@ export class IndicadoresTracking implements OnChanges {
|
||||
}
|
||||
private load(q: SeguimientoQuery) {
|
||||
if (this.dominio !== 'cacu' && this.dominio !== 'tea') return;
|
||||
if (!validSeguimientoQuery(q)) { this.message = 'Revisa la fecha, la ventana y el tamaño de página (1 a 200).'; return; }
|
||||
if (!validSeguimientoQuery(q)) { this.message = `Revisa la fecha, la ventana y el tamaño de página (1 a ${PAGE_SIZE_MAX}).`; return; }
|
||||
this.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.applied = { ...q };
|
||||
(this.dominio === 'tea' ? this.teaRequests : this.requests).next(q);
|
||||
}
|
||||
apply() { this.load({ ...this.draft, page: 1 }); }
|
||||
apply() { this.draft.page_size = acotarTamano(this.draft.page_size); this.load({ ...this.draft, page: 1 }); }
|
||||
retry() { this.load(this.applied); }
|
||||
navigate(page: number) {
|
||||
if (!this.response || page < 1 || page > this.response.paginacion.total_pages) return;
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { of } from 'rxjs';
|
||||
import { PLOTLY_LOADER } from '../../../shared/plotly/plotly-runtime';
|
||||
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
|
||||
import { riesgoCacuCancerSinEstimar, riesgoCacuConEstimando, riesgoCacuDosDesenlaces, riesgoCacuEjemplo, riesgoCacuVista } from './paciente-riesgo.testing';
|
||||
import { conIntervalo, encabezado, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion';
|
||||
import { riesgoPacienteResponse } from './paciente-riesgo.validation';
|
||||
import { figuraRiesgoPaciente } from './paciente-riesgo-figura';
|
||||
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
|
||||
|
||||
// What the patient's risk says about its number (the model's `[estimand]`) and the curve of its horizons.
|
||||
describe('Riesgo individual: qué se estima y su curva', () => {
|
||||
function setup(data: unknown) {
|
||||
const react = vi.fn(() => Promise.resolve());
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
|
||||
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(data) } },
|
||||
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve({ react, purge: vi.fn(), Plots: { resize: vi.fn() },
|
||||
addFrames: vi.fn(), deleteFrames: vi.fn() }) }] });
|
||||
const fixture = TestBed.createComponent(PacienteRiesgoTabla);
|
||||
fixture.componentRef.setInput('pacId', '42');
|
||||
fixture.detectChanges();
|
||||
fixture.detectChanges();
|
||||
return { fixture, root: fixture.nativeElement as HTMLElement };
|
||||
}
|
||||
|
||||
it('lee el estimando conocido e ignora claves que no conoce (también el método del intervalo, que es del reporte); sin extensión queda en null', () => {
|
||||
expect(riesgoPacienteResponse(riesgoCacuConEstimando(), '42')!.riesgo.estimando).toEqual({
|
||||
quantity: 'Riesgo acumulado', description: 'Probabilidad de CIN2+ antes de cada horizonte.',
|
||||
outcome: 'CIN2+: biopsia LIEAG, CIS o carcinoma', horizons_unit: 'años' });
|
||||
expect(riesgoPacienteResponse(riesgoCacuEjemplo(), '42')).toEqual(riesgoCacuVista());
|
||||
});
|
||||
|
||||
it('rechaza un estimando mal formado', () => {
|
||||
const data = riesgoCacuConEstimando();
|
||||
data.entry[0].resource.extension[0].extension = 'texto';
|
||||
expect(() => riesgoPacienteResponse(data, '42')).toThrow();
|
||||
});
|
||||
|
||||
it('nombra el número, su desenlace y la unidad de los horizontes en la ficha', () => {
|
||||
const { root } = setup(riesgoCacuConEstimando());
|
||||
expect([...root.querySelectorAll('thead th')].map(th => th.textContent!.trim()))
|
||||
.toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)']);
|
||||
expect(root.querySelector('details.risk-details summary')!.textContent).toContain('Detalle del modelo');
|
||||
for (const value of ['Qué se estima', 'CIN2+: biopsia LIEAG, CIS o carcinoma']) {
|
||||
expect(root.textContent).toContain(value);
|
||||
}
|
||||
expect(root.textContent).not.toContain('método delta');
|
||||
});
|
||||
|
||||
it('dibuja la curva solo al abrir su sección', async () => {
|
||||
const { fixture, root } = setup(riesgoCacuConEstimando());
|
||||
const details = root.querySelector('details.risk-curve') as HTMLDetailsElement;
|
||||
expect(details.querySelector('summary')!.textContent).toContain('Curva de riesgo acumulado');
|
||||
expect(root.querySelector('app-plotly-chart')).toBeNull();
|
||||
details.open = true;
|
||||
details.dispatchEvent(new Event('toggle'));
|
||||
fixture.detectChanges();
|
||||
expect(root.querySelector('app-plotly-chart')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('la figura une los horizontes y pone el intervalo como banda, o como barras si falta en alguno', () => {
|
||||
const riesgo = riesgoPacienteResponse(riesgoCacuConEstimando(), '42')!.riesgo;
|
||||
const banda = figuraRiesgoPaciente([riesgo]);
|
||||
expect(banda.data).toHaveLength(3);
|
||||
expect(banda.data[2]['y']).toEqual([8, 21, 34]);
|
||||
expect(banda.data[1]['y']).toEqual([5, 15, 26]);
|
||||
expect((banda.layout['yaxis'] as any).title.text).toBe('Riesgo acumulado (%)');
|
||||
|
||||
const parcial = { ...riesgo, horizontes: riesgo.horizontes.map((h, i) => i === 0 ? { ...h, ic_bajo: null, ic_alto: null } : h) };
|
||||
const barras = figuraRiesgoPaciente([parcial]);
|
||||
expect(barras.data).toHaveLength(1);
|
||||
expect((barras.data[0]['error_y'] as any).array[0]).toBe(0);
|
||||
});
|
||||
|
||||
it('pone una columna por desenlace, LIEAG+ primero, con el IC entre paréntesis', () => {
|
||||
const { root } = setup(riesgoCacuDosDesenlaces());
|
||||
expect([...root.querySelectorAll('thead th')].map(th => th.textContent!.trim()))
|
||||
.toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)']);
|
||||
const fila = [...root.querySelectorAll('tbody tr')][2];
|
||||
expect([...fila.querySelectorAll('td')].map(td => td.textContent!.replace(/\s+/g, ' ').trim()))
|
||||
.toEqual(['34 % (26 – 44 %)', '1.5 % (0.8 – 2.8 %)']);
|
||||
});
|
||||
|
||||
it('la frase dice los resultados índice y los dos riesgos al horizonte más largo, respectivamente', () => {
|
||||
const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!;
|
||||
expect(riesgos.map(r => r.desenlace)).toEqual(['cin2_mas', 'cancer']);
|
||||
expect(fraseRiesgo(riesgos)).toBe('Un resultado de VPH positivo y una citología LIEBG (2026-06-01) tienen un riesgo '
|
||||
+ 'acumulado a 5 años de estar presente o de aparecer LIEAG+ y cáncer de 34 % (26 – 44 %) y 1.5 % (0.8 – 2.8 %), '
|
||||
+ 'respectivamente.');
|
||||
expect(fraseRiesgo(riesgoPacienteResponse(riesgoCacuEjemplo(), '42')!.riesgos)).toBeNull();
|
||||
});
|
||||
|
||||
it('dibuja una curva por desenlace, cada una con su banda', () => {
|
||||
const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!;
|
||||
const figura = figuraRiesgoPaciente(riesgos);
|
||||
const lineas = figura.data.filter(t => t['mode'] === 'lines+markers');
|
||||
expect(lineas.map(t => t['name'])).toEqual(['LIEAG+', 'cáncer']);
|
||||
expect((lineas[1]['y'] as number[]).map(v => Math.round(v * 10) / 10)).toEqual([0.4, 0.9, 1.5]);
|
||||
expect(figura.data.filter(t => t['fill'] === 'tonexty')).toHaveLength(2);
|
||||
expect((figura.layout['xaxis'] as any).title.text).toBe('Horizonte (años desde la fecha índice (2026-06-01))');
|
||||
});
|
||||
|
||||
it('escribe los porcentajes con los decimales que un riesgo pequeño necesita', () => {
|
||||
expect([0.34, 0.178, 0.015, 0.004, 0.00123, 0, 0.1, 1].map(porcentaje))
|
||||
.toEqual(['34', '17.8', '1.5', '0.4', '0.123', '0', '10', '100']);
|
||||
expect(conIntervalo({ horizonte_anios: 1, probabilidad: 0.2, ic_bajo: null, ic_alto: null })).toBe('20 % (IC no disponible)');
|
||||
});
|
||||
|
||||
it('un desenlace con otra fecha índice la dice en su columna y queda fuera de la frase', () => {
|
||||
const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!;
|
||||
const muerte = { ...riesgos[1], desenlace: 'muerte', fecha_indice: '2024-03-01' };
|
||||
expect(encabezado(muerte, riesgos[0].fecha_indice)).toBe('Probabilidad a muerte desde 2024-03-01');
|
||||
expect(fraseRiesgo([riesgos[0], muerte])).toBe('Un resultado de VPH positivo y una citología LIEBG (2026-06-01) '
|
||||
+ 'tienen un riesgo acumulado a 5 años de estar presente o de aparecer LIEAG+ de 34 % (26 – 44 %).');
|
||||
});
|
||||
|
||||
it('sin modelo de un desenlace su columna dice No disponible', () => {
|
||||
const { root } = setup(riesgoCacuConEstimando());
|
||||
const celdas = [...root.querySelectorAll('tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim());
|
||||
expect(celdas).toEqual(['No disponible', 'No disponible', 'No disponible']);
|
||||
});
|
||||
|
||||
it('con un modelo que no la estima su columna lo dice, con el motivo, y no entra en la curva ni en la frase', () => {
|
||||
const data = riesgoCacuCancerSinEstimar();
|
||||
const { root } = setup(data);
|
||||
const celdas = [...root.querySelectorAll('tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim());
|
||||
expect(celdas).toEqual(['No estimada para su grupo', 'No estimada para su grupo', 'No estimada para su grupo']);
|
||||
expect(root.querySelector('.unavailable-note')!.textContent).toContain('queda fuera de su población');
|
||||
const { riesgos, riesgo } = riesgoPacienteResponse(data, '42')!;
|
||||
expect(riesgo.desenlace).toBe('cin2_mas');
|
||||
expect(riesgos[1]).toMatchObject({ desenlace: 'cancer', horizontes: [], sin_estimacion: 'queda fuera de su población' });
|
||||
expect(figuraRiesgoPaciente(riesgos.filter(r => r.horizontes.length)).data.filter(t => t['mode'] === 'lines+markers'))
|
||||
.toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import { PlotlyFigure } from '../indicadores.models';
|
||||
import { conIntervalo, etiquetaDesenlace } from './paciente-riesgo.presentacion';
|
||||
import { tieneIntervalo } from './paciente-riesgo.validation';
|
||||
import { LoteRiesgoCacu } from './paciente-riesgo.models';
|
||||
|
||||
/** One color per curve, in the order of the outcomes (CIN2+, cancer, any other). */
|
||||
const COLORES = ['#6a3d9a', '#b2182b', '#1f78b4'];
|
||||
const BANDAS = ['rgba(106,61,154,.18)', 'rgba(178,24,43,.16)', 'rgba(31,120,180,.16)'];
|
||||
|
||||
/**
|
||||
* The patient's risk of each outcome at the model's horizons as small curves on one axis: the points joined by a
|
||||
* line, with the interval as a band where every horizon has one and as error bars otherwise. In percent; the axis
|
||||
* names follow the first model's estimand, and the x axis says the index date the horizons count from.
|
||||
*/
|
||||
export function figuraRiesgoPaciente(riesgos: LoteRiesgoCacu[]): PlotlyFigure {
|
||||
const data: Record<string, unknown>[] = [];
|
||||
let maximo = 0;
|
||||
riesgos.forEach((riesgo, k) => {
|
||||
const h = riesgo.horizontes, x = h.map(p => p.horizonte_anios), y = h.map(p => p.probabilidad * 100);
|
||||
const color = COLORES[k % COLORES.length], nombre = etiquetaDesenlace(riesgo);
|
||||
const conIc = h.map(tieneIntervalo);
|
||||
const banda = conIc.length > 1 && conIc.every(Boolean);
|
||||
if (banda) {
|
||||
data.push(
|
||||
{ type: 'scatter', mode: 'lines', x, y: h.map(p => p.ic_alto! * 100), line: { width: 0 }, showlegend: false,
|
||||
hoverinfo: 'skip', legendgroup: nombre },
|
||||
{ type: 'scatter', mode: 'lines', x, y: h.map(p => p.ic_bajo! * 100), fill: 'tonexty',
|
||||
fillcolor: BANDAS[k % BANDAS.length], line: { width: 0 }, name: `IC 95 % ${nombre}`, hoverinfo: 'skip',
|
||||
legendgroup: nombre },
|
||||
);
|
||||
}
|
||||
const barras = !banda && conIc.some(Boolean) ? {
|
||||
error_y: { type: 'data', symmetric: false, visible: true, color, thickness: 2, width: 6,
|
||||
array: h.map((p, i) => conIc[i] ? (p.ic_alto! - p.probabilidad) * 100 : 0),
|
||||
arrayminus: h.map((p, i) => conIc[i] ? (p.probabilidad - p.ic_bajo!) * 100 : 0) },
|
||||
} : {};
|
||||
data.push({
|
||||
type: 'scatter', mode: 'lines+markers', x, y, name: nombre, legendgroup: nombre, line: { color, width: 2 },
|
||||
marker: { color, size: 9, line: { color: 'white', width: 2 } }, ...barras,
|
||||
customdata: h.map(conIntervalo),
|
||||
hovertemplate: `%{x} ${riesgo.estimando?.horizons_unit ?? 'años'}: %{customdata}<extra>${nombre}</extra>`,
|
||||
});
|
||||
maximo = Math.max(maximo, ...h.map(p => (tieneIntervalo(p) ? p.ic_alto! : p.probabilidad) * 100));
|
||||
});
|
||||
const primero = riesgos[0];
|
||||
const unidad = primero?.estimando?.horizons_unit ?? 'años';
|
||||
const fechas = [...new Set(riesgos.map(r => r.fecha_indice))];
|
||||
const desde = fechas.length === 1 ? `la fecha índice (${fechas[0]})`
|
||||
: `la fecha índice de cada desenlace (${riesgos.map(r => `${etiquetaDesenlace(r)}: ${r.fecha_indice}`).join('; ')})`;
|
||||
return {
|
||||
data,
|
||||
layout: {
|
||||
margin: { l: 56, r: 16, t: 16, b: 48 }, showlegend: true, legend: { orientation: 'h', y: -0.25 },
|
||||
xaxis: { title: { text: `Horizonte (${unidad} desde ${desde})` },
|
||||
tickvals: [...new Set(riesgos.flatMap(r => r.horizontes.map(p => p.horizonte_anios)))], zeroline: false },
|
||||
yaxis: { title: { text: `${primero?.estimando?.quantity ?? 'Probabilidad'} (%)` }, rangemode: 'tozero',
|
||||
range: [0, Math.max(maximo * 1.15, 1)], zeroline: false },
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -7,37 +7,66 @@
|
||||
}
|
||||
@case ('error') { <p role="alert">No se pudo validar o cargar el riesgo individual.</p> }
|
||||
@case ('disponible') {
|
||||
@let todos = lectura.datos.riesgos;
|
||||
@let riesgos = conRiesgo(todos);
|
||||
@let riesgo = lectura.datos.riesgo;
|
||||
<h5>Modelo y evaluación</h5>
|
||||
<dl class="metadata">
|
||||
<div><dt>Modelo</dt><dd>{{ riesgo.modelo_nombre }}</dd></div>
|
||||
<div><dt>Versión del modelo</dt><dd>{{ riesgo.modelo_version }}</dd></div>
|
||||
<div><dt>Fecha índice</dt><dd>{{ riesgo.fecha_indice }}</dd></div>
|
||||
<div><dt>Desenlace</dt><dd>{{ riesgo.desenlace_texto ?? riesgo.desenlace }}</dd></div>
|
||||
<div><dt>Evaluado en (UTC)</dt><dd>{{ riesgo.evaluado_en }}</dd></div>
|
||||
<div><dt>Estado del lote</dt><dd>{{ riesgo.estado_lote === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</dd></div>
|
||||
</dl>
|
||||
@if (riesgo.horizontes.length) {
|
||||
<div class="risk-scroll" role="region" aria-label="Probabilidades por horizonte, tabla desplazable" tabindex="0">
|
||||
<table>
|
||||
<caption>Probabilidades por horizonte desde la fecha índice</caption>
|
||||
<thead><tr>
|
||||
<th scope="col">Horizonte (años)</th>
|
||||
<th scope="col">Probabilidad (%)</th>
|
||||
<th scope="col">Intervalo de confianza (%)</th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
@for (h of riesgo.horizontes; track h.horizonte_anios) {
|
||||
<tr>
|
||||
<th scope="row">{{ h.horizonte_anios }}</th>
|
||||
<td class="percentage">{{ h.probabilidad * 100 | number:'1.0-4' }} %</td>
|
||||
<td class="interval">@if (tieneIntervalo(h)) { {{ h.ic_bajo! * 100 | number:'1.0-4' }} % – {{ h.ic_alto! * 100 | number:'1.0-4' }} % } @else { No disponible }</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
} @else { <p role="status">Sin horizontes evaluados en el lote vigente.</p> }
|
||||
@let columnas = columnasDe(todos);
|
||||
@let filas = filasDe(lotesDe(columnas));
|
||||
@if (filas.length) {
|
||||
<div class="risk-scroll" role="region" aria-label="Riesgos por horizonte, tabla desplazable" tabindex="0">
|
||||
<table>
|
||||
<caption>{{ riesgo.estimando?.quantity ?? 'Probabilidad' }} por horizonte desde la fecha índice
|
||||
({{ riesgo.fecha_indice }}), con su intervalo de confianza entre paréntesis</caption>
|
||||
<thead><tr>
|
||||
<th scope="col">Horizonte ({{ riesgo.estimando?.horizons_unit ?? 'años' }})</th>
|
||||
@for (c of columnas; track c.encabezado) { <th scope="col">{{ c.encabezado }} (%)</th> }
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
@for (f of filas; track f.horizonte_anios) {
|
||||
<tr>
|
||||
<th scope="row">{{ f.horizonte_anios }}</th>
|
||||
@for (c of f.celdas; track $index; let i = $index) {
|
||||
<td>@if (columnas[i].vacia; as vacia) {<span class="unavailable">{{ vacia }}</span>} @else if (c) {<span class="percentage">{{ porcentaje(c.probabilidad) }} %</span>{{ ' ' }}<span class="interval">@if (tieneIntervalo(c)) {({{ porcentaje(c.ic_bajo!) }} – {{ porcentaje(c.ic_alto!) }} %)} @else {(IC no disponible)}</span>} @else {—}</td>
|
||||
}
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@for (c of columnas; track c.encabezado) {
|
||||
@if (c.lote?.sin_estimacion; as motivo) { <p class="unavailable-note">{{ c.encabezado }}: {{ motivo }}.</p> }
|
||||
}
|
||||
<details class="risk-details">
|
||||
<summary>Detalle del modelo</summary>
|
||||
@for (r of riesgos; track r.id) {
|
||||
@if (riesgos.length > 1) { <h6>{{ encabezado(r) }}</h6> }
|
||||
<dl class="metadata">
|
||||
<div><dt>Modelo</dt><dd>{{ r.modelo_nombre }}</dd></div>
|
||||
<div><dt>Versión del modelo</dt><dd>{{ r.modelo_version }}</dd></div>
|
||||
<div><dt>Fecha índice</dt><dd>{{ r.fecha_indice }}</dd></div>
|
||||
<div><dt>Desenlace</dt><dd>{{ r.desenlace_texto ?? r.desenlace }}</dd></div>
|
||||
<div><dt>Evaluado en</dt><dd><time [attr.datetime]="r.evaluado_en">{{ instante(r.evaluado_en) }}</time></dd></div>
|
||||
<div><dt>Estado del lote</dt><dd>{{ r.estado_lote === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</dd></div>
|
||||
@if (r.estimando; as e) {
|
||||
@if (e.quantity) { <div><dt>Qué se estima</dt><dd>{{ e.quantity }}@if (e.description) {: {{ e.description }}}</dd></div> }
|
||||
@if (e.outcome) { <div><dt>Desenlace del modelo</dt><dd>{{ e.outcome }}</dd></div> }
|
||||
@if (e.index_date) { <div><dt>Desde</dt><dd>{{ e.index_date }}</dd></div> }
|
||||
@if (e.horizons_unit) { <div><dt>Horizontes en</dt><dd>{{ e.horizons_unit }}</dd></div> }
|
||||
}
|
||||
</dl>
|
||||
}
|
||||
</details>
|
||||
@if (filas.length > 1) {
|
||||
<details class="risk-curve" (toggle)="curvaAbierta.set($any($event.target).open)">
|
||||
<summary>Curva{{ riesgos.length > 1 ? 's' : '' }} de {{ (riesgo.estimando?.quantity ?? 'probabilidad') | lowercase }} con su intervalo</summary>
|
||||
@if (frase(riesgos); as texto) { <p class="risk-sentence">{{ texto }}</p> }
|
||||
@if (curvaAbierta()) {
|
||||
<app-plotly-chart [style.--plot-height]="'300px'" [showNotes]="false" [figure]="figura(riesgos)"
|
||||
[label]="'Curvas de riesgo individual ' + rotulo() + ' por horizonte'" />
|
||||
}
|
||||
</details>
|
||||
}
|
||||
} @else { <p role="status">Sin horizontes evaluados en el lote vigente.</p> }
|
||||
}
|
||||
}
|
||||
<p class="recommendations">Recomendaciones no disponibles.</p>
|
||||
|
||||
@@ -18,3 +18,9 @@ thead th { position: sticky; top: 0; background: var(--issste-background, var(--
|
||||
tbody th, td { background: var(--issste-surface); }
|
||||
tbody tr:last-child > * { border-bottom: 0; }
|
||||
.percentage, .interval { font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.risk-curve { margin-block: .75rem 0; border: 1px solid var(--issste-border); border-radius: .5rem; padding-inline: .75rem; }
|
||||
.risk-sentence { margin: .25rem 0 .75rem; line-height: 1.5; }
|
||||
.risk-details { margin-block: .75rem 0; border: 1px solid var(--issste-border); border-radius: .5rem; padding-inline: .75rem; }
|
||||
.risk-details h6 { margin: .75rem 0 .25rem; font-size: .95rem; }
|
||||
.unavailable { color: var(--issste-text-secondary); }
|
||||
.unavailable-note { color: var(--issste-text-secondary); font-size: .85rem; margin: .5rem 0 0; }
|
||||
|
||||
@@ -1,12 +1,22 @@
|
||||
import { Component, computed, effect, inject, input } from '@angular/core';
|
||||
import { DecimalPipe } from '@angular/common';
|
||||
import { DominioRiesgo } from './paciente-riesgo.models';
|
||||
import { Component, computed, effect, inject, input, signal } from '@angular/core';
|
||||
import { LowerCasePipe } from '@angular/common';
|
||||
import { PlotlyChart } from '../../../shared/plotly/plotly-chart';
|
||||
import { PlotlyFigure } from '../indicadores.models';
|
||||
import { figuraRiesgoPaciente } from './paciente-riesgo-figura';
|
||||
import { ColumnaRiesgo, columnasRiesgo, conRiesgo, encabezado, etiquetaDesenlace, filasRiesgo, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion';
|
||||
import { DominioRiesgo, LoteRiesgoCacu } from './paciente-riesgo.models';
|
||||
import { PacienteRiesgoState } from './paciente-riesgo.state';
|
||||
import { tieneIntervalo } from './paciente-riesgo.validation';
|
||||
|
||||
/** A UTC instant as the day and the minute it happened, so it reads next to the index date (a calendar day, not an instant). */
|
||||
export const instanteUtc = (iso: string) => {
|
||||
const m = /^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})/.exec(iso);
|
||||
return m ? `${m[1]} ${m[2]} UTC` : iso;
|
||||
};
|
||||
|
||||
@Component({
|
||||
selector: 'app-paciente-riesgo-tabla',
|
||||
imports: [DecimalPipe],
|
||||
imports: [LowerCasePipe, PlotlyChart],
|
||||
providers: [PacienteRiesgoState],
|
||||
templateUrl: './paciente-riesgo-tabla.html',
|
||||
styleUrl: './paciente-riesgo-tabla.scss',
|
||||
@@ -20,6 +30,22 @@ export class PacienteRiesgoTabla {
|
||||
private readonly state = inject(PacienteRiesgoState);
|
||||
readonly estado = this.state.estado;
|
||||
readonly tieneIntervalo = tieneIntervalo;
|
||||
readonly instante = instanteUtc;
|
||||
/** The curve is drawn only while its section is open, so Plotly isn't loaded for a closed one. */
|
||||
readonly curvaAbierta = signal(false);
|
||||
readonly porcentaje = porcentaje;
|
||||
readonly encabezado = encabezado;
|
||||
readonly etiqueta = etiquetaDesenlace;
|
||||
readonly frase = fraseRiesgo;
|
||||
readonly filasDe = filasRiesgo;
|
||||
readonly conRiesgo = conRiesgo;
|
||||
columnasDe(riesgos: LoteRiesgoCacu[]): ColumnaRiesgo[] { return columnasRiesgo(riesgos, this.dominio()); }
|
||||
lotesDe(columnas: ColumnaRiesgo[]) { return columnas.map(c => (c.lote?.horizontes.length ? c.lote : null)); }
|
||||
private figuraDe?: { riesgos: LoteRiesgoCacu[]; figura: PlotlyFigure };
|
||||
figura(riesgos: LoteRiesgoCacu[]): PlotlyFigure {
|
||||
if (this.figuraDe?.riesgos !== riesgos) this.figuraDe = { riesgos, figura: figuraRiesgoPaciente(riesgos) };
|
||||
return this.figuraDe.figura;
|
||||
}
|
||||
constructor() {
|
||||
effect(() => { this.state.dominio.set(this.dominio()); this.state.pacId.set(this.pacId()); });
|
||||
}
|
||||
|
||||
@@ -14,6 +14,25 @@ export interface HorizonteRiesgoCacu {
|
||||
ic_alto?: number | null;
|
||||
}
|
||||
|
||||
/** What the model's number is (the scenario's `[estimand]`, extension `estimando`); each field may be missing. */
|
||||
export interface EstimandoRiesgo {
|
||||
/** e.g. "Riesgo acumulado"; also `method.text`. */
|
||||
quantity?: string;
|
||||
description?: string;
|
||||
outcome?: string;
|
||||
index_date?: string;
|
||||
/** The unit the horizons are counted in, e.g. "años". */
|
||||
horizons_unit?: string;
|
||||
}
|
||||
|
||||
/** The results of the cytology sampled on the risk's index date (extension `resultados-indice`), as recorded. */
|
||||
export interface ResultadosIndice {
|
||||
escamosas?: string;
|
||||
glandulares?: string;
|
||||
/** `POSITIVO`, `NEGATIVO` or `INDETERMINADO`. */
|
||||
vph?: string;
|
||||
}
|
||||
|
||||
/** The view of one FHIR `RiskAssessment` (`GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id>`). */
|
||||
export interface LoteRiesgoCacu {
|
||||
/** The resource's id, `<lote_id>-<pac_id>`. */
|
||||
@@ -28,12 +47,21 @@ export interface LoteRiesgoCacu {
|
||||
desenlace: string;
|
||||
desenlace_texto: string | null;
|
||||
horizontes: HorizonteRiesgoCacu[];
|
||||
/** `null` for a model whose scenario doesn't say. */
|
||||
estimando: EstimandoRiesgo | null;
|
||||
/** `null` when no cytology was sampled on the index date (or the domain doesn't give it). */
|
||||
resultados_indice: ResultadosIndice | null;
|
||||
/** Why a current model of this outcome has no risk for her (extension `sin-estimacion`; then `horizontes` is
|
||||
* empty and `fecha_indice` too); `null` when it scored her. */
|
||||
sin_estimacion: string | null;
|
||||
}
|
||||
|
||||
/** DEV-only: the patient's current `RiskAssessment`, from a `searchset` Bundle tagged `simulado`. */
|
||||
/** DEV-only: the patient's current `RiskAssessment` of each outcome, from a `searchset` Bundle tagged `simulado`.
|
||||
* `riesgos` holds them CIN2+ first, then cancer, then any other; `riesgo` is the first. */
|
||||
export interface RiesgoPacienteCacu {
|
||||
simulado: true;
|
||||
riesgo: LoteRiesgoCacu;
|
||||
riesgos: LoteRiesgoCacu[];
|
||||
}
|
||||
|
||||
/** The raw FHIR answer (a Bundle), or `null` when the patient has no risk data. */
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import { HorizonteRiesgoCacu, LoteRiesgoCacu, ResultadosIndice } from './paciente-riesgo.models';
|
||||
import { tieneIntervalo } from './paciente-riesgo.validation';
|
||||
|
||||
/** How the record names an outcome in its columns, curves and sentence. */
|
||||
export function etiquetaDesenlace(lote: LoteRiesgoCacu): string {
|
||||
if (lote.desenlace.startsWith('cin2')) return 'LIEAG+';
|
||||
if (lote.desenlace === 'cancer') return 'cáncer';
|
||||
if (lote.desenlace === 'muerte') return 'muerte';
|
||||
return lote.desenlace_texto ?? lote.desenlace;
|
||||
}
|
||||
|
||||
/** A column's header: "Probabilidad a LIEAG+", "Probabilidad a cáncer"; with its own index date when it isn't
|
||||
* `fechaComun` (a survival model counts from the invasive biopsy, not from the cytology). */
|
||||
export function encabezado(lote: LoteRiesgoCacu, fechaComun: string | null = null): string {
|
||||
const desde = fechaComun && lote.fecha_indice !== fechaComun ? ` desde ${lote.fecha_indice}` : '';
|
||||
return `Probabilidad a ${etiquetaDesenlace(lote)}${desde}`;
|
||||
}
|
||||
|
||||
/** A probability as a percentage with the decimals a small risk needs, without trailing zeros: 0.178 -> "17.8",
|
||||
* 0.015 -> "1.5", 0.00123 -> "0.123", 0.34 -> "34". */
|
||||
export function porcentaje(p: number): string {
|
||||
const v = p * 100;
|
||||
const decimales = v === 0 ? 0 : v < 1 ? 3 : v < 10 ? 2 : 1;
|
||||
const texto = v.toFixed(decimales);
|
||||
return texto.includes('.') ? texto.replace(/\.?0+$/, '') : texto;
|
||||
}
|
||||
|
||||
/** The risk with its interval in parentheses, as the table and the sentence write it. */
|
||||
export function conIntervalo(h: HorizonteRiesgoCacu): string {
|
||||
const punto = `${porcentaje(h.probabilidad)} %`;
|
||||
return tieneIntervalo(h) ? `${punto} (${porcentaje(h.ic_bajo!)} – ${porcentaje(h.ic_alto!)} %)` : `${punto} (IC no disponible)`;
|
||||
}
|
||||
|
||||
/** The outcomes a domain's record always has a column for, even with no model: CaCu's CIN2+ and cancer. */
|
||||
const COLUMNAS_FIJAS: Record<string, { desenlace: string; etiqueta: string }[]> = {
|
||||
cacu: [{ desenlace: 'cin2', etiqueta: 'LIEAG+' }, { desenlace: 'cancer', etiqueta: 'cáncer' }],
|
||||
};
|
||||
const esDe = (lote: LoteRiesgoCacu, desenlace: string) =>
|
||||
desenlace === 'cin2' ? lote.desenlace.startsWith('cin2') : lote.desenlace === desenlace;
|
||||
|
||||
export interface ColumnaRiesgo {
|
||||
encabezado: string;
|
||||
/** Its model's risks; `null` when no model of the outcome is current. */
|
||||
lote: LoteRiesgoCacu | null;
|
||||
/** What the cells say when there's no risk: no model, or a model that doesn't estimate her. */
|
||||
vacia: string | null;
|
||||
}
|
||||
|
||||
/** The table's columns: the domain's fixed outcomes (CaCu: LIEAG+ and cancer), with or without a model, then any
|
||||
* other outcome she has a risk of. A column's index date shows when it isn't the first risk's. */
|
||||
export function columnasRiesgo(riesgos: LoteRiesgoCacu[], dominio = 'cacu'): ColumnaRiesgo[] {
|
||||
const fecha = riesgos.find(r => r.horizontes.length)?.fecha_indice ?? null;
|
||||
const fijas = COLUMNAS_FIJAS[dominio] ?? [];
|
||||
const columnas: ColumnaRiesgo[] = fijas.map(({ desenlace, etiqueta }) => {
|
||||
const lote = riesgos.find(r => esDe(r, desenlace)) ?? null;
|
||||
if (!lote) return { encabezado: `Probabilidad a ${etiqueta}`, lote: null, vacia: 'No disponible' };
|
||||
return { encabezado: encabezado(lote, fecha), lote,
|
||||
vacia: lote.horizontes.length ? null : 'No estimada para su grupo' };
|
||||
});
|
||||
for (const lote of riesgos) {
|
||||
if (fijas.some(f => esDe(lote, f.desenlace)) || !lote.horizontes.length) continue;
|
||||
columnas.push({ encabezado: encabezado(lote, fecha), lote, vacia: null });
|
||||
}
|
||||
return columnas;
|
||||
}
|
||||
|
||||
/** The risks the record can draw and describe: the ones with horizons. */
|
||||
export const conRiesgo = (riesgos: LoteRiesgoCacu[]) => riesgos.filter(r => r.horizontes.length);
|
||||
|
||||
export interface FilaRiesgo {
|
||||
horizonte_anios: number;
|
||||
/** One cell per column, in their order; `null` where that column has no risk at this horizon. */
|
||||
celdas: (HorizonteRiesgoCacu | null)[];
|
||||
}
|
||||
|
||||
/** The table's rows: every horizon any of the columns has, ascending, with each column's risk there. */
|
||||
export function filasRiesgo(lotes: (LoteRiesgoCacu | null)[]): FilaRiesgo[] {
|
||||
const horizontes = [...new Set(lotes.flatMap(r => r?.horizontes.map(h => h.horizonte_anios) ?? []))]
|
||||
.sort((a, b) => a - b);
|
||||
return horizontes.map(horizonte_anios => ({
|
||||
horizonte_anios,
|
||||
celdas: lotes.map(r => r?.horizontes.find(h => h.horizonte_anios === horizonte_anios) ?? null),
|
||||
}));
|
||||
}
|
||||
|
||||
function resultado(r: ResultadosIndice | null): string | null {
|
||||
if (!r) return null;
|
||||
const vph = r.vph === 'POSITIVO' ? 'VPH positivo' : r.vph === 'NEGATIVO' ? 'VPH negativo'
|
||||
: r.vph ? `VPH ${r.vph.toLowerCase()}` : 'sin resultado de VPH';
|
||||
const citologia = [r.escamosas, r.glandulares].filter(Boolean).join(' con ');
|
||||
return `Un resultado de ${vph} y una citología ${citologia || 'sin resultado'}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The sentence over the curves: the index results and, at the longest horizon the outcomes of the first one's index
|
||||
* date share, each outcome's
|
||||
* cumulative risk of being present at the index visit or developing afterwards, "respectivamente" when there are
|
||||
* several. `null` without the index results.
|
||||
*/
|
||||
export function fraseRiesgo(todos: LoteRiesgoCacu[]): string | null {
|
||||
const scored = conRiesgo(todos);
|
||||
const riesgos = scored.filter(r => r.fecha_indice === scored[0]?.fecha_indice); // the outcomes of the same visit
|
||||
const inicio = resultado(riesgos.find(r => r.resultados_indice)?.resultados_indice ?? null);
|
||||
if (!inicio) return null;
|
||||
const comunes = filasRiesgo(riesgos).filter(f => f.celdas.every(c => c !== null));
|
||||
const ultima = comunes[comunes.length - 1];
|
||||
if (!ultima) return null;
|
||||
const fecha = riesgos[0].fecha_indice;
|
||||
const junta = (xs: string[]) => xs.length > 1 ? `${xs.slice(0, -1).join(', ')} y ${xs[xs.length - 1]}` : xs[0];
|
||||
const desenlaces = junta(riesgos.map(etiquetaDesenlace));
|
||||
const valores = junta(ultima.celdas.map(c => conIntervalo(c!)));
|
||||
const anios = ultima.horizonte_anios === 1 ? '1 año' : `${ultima.horizonte_anios} años`;
|
||||
return `${inicio} (${fecha}) tienen un riesgo acumulado a ${anios} de estar presente o de aparecer ${desenlaces} `
|
||||
+ `de ${valores}${riesgos.length > 1 ? ', respectivamente' : ''}.`;
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { of, Subject, throwError } from 'rxjs';
|
||||
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
|
||||
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
|
||||
import { prediccion, riesgoCacuEjemplo } from './paciente-riesgo.testing';
|
||||
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
|
||||
import { instanteUtc, PacienteRiesgoTabla } from './paciente-riesgo-tabla';
|
||||
|
||||
describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
function setup(provider?: PacienteRiesgoProvider) {
|
||||
@@ -44,13 +44,14 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
const baseline = structuredClone(data);
|
||||
const f = setup({ obtener }), root: HTMLElement = f.nativeElement;
|
||||
expect(obtener).toHaveBeenCalledExactlyOnceWith('42');
|
||||
// horizon, CIN2+ (LIEAG+) and cancer (without a model here: "No disponible"), each risk with its interval
|
||||
expect(root.querySelectorAll('thead th')).toHaveLength(3);
|
||||
expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true);
|
||||
expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3);
|
||||
expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['8 %', '21 %', '34 %']);
|
||||
expect(root.querySelector('.interval')!.textContent).toContain('5 % – 12 %');
|
||||
expect(root.querySelector('.interval')!.textContent).toContain('(5 – 12 %)');
|
||||
expect(root.textContent).toContain('Final (final)');
|
||||
for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', '2026-06-01', 'CIN2+ por biopsia']) {
|
||||
for (const value of ['modelo-cacu', '2.1.0', '2026-10-01 00:00 UTC', '2026-06-01', 'CIN2+ por biopsia']) {
|
||||
expect(root.textContent).toContain(value);
|
||||
}
|
||||
// The record no longer shows the cohort's internals (its definition, version or model variables).
|
||||
@@ -86,7 +87,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement;
|
||||
expect([...root.querySelectorAll('tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']);
|
||||
expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['0 %', '100 %', '0.123 %']);
|
||||
expect([...root.querySelectorAll('.interval')].map(c => c.textContent!.trim())).toEqual(['0 % – 0 %', 'No disponible', 'No disponible']);
|
||||
expect([...root.querySelectorAll('.interval')].map(c => c.textContent!.trim())).toEqual(['(0 – 0 %)', '(IC no disponible)', '(IC no disponible)']);
|
||||
expect(root.textContent).toContain('Preliminar (preliminary)');
|
||||
});
|
||||
|
||||
@@ -135,3 +136,10 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
expect(f.nativeElement.textContent).toContain('Recomendaciones no disponibles');
|
||||
});
|
||||
});
|
||||
|
||||
describe('instanteUtc', () => {
|
||||
it('shows the day and the minute of a UTC instant, and leaves anything else as it came', () => {
|
||||
expect(instanteUtc('2026-11-21T23:17:45.120Z')).toBe('2026-11-21 23:17 UTC');
|
||||
expect(instanteUtc('no es una fecha')).toBe('no es una fecha');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { RiesgoPacienteCacu } from './paciente-riesgo.models';
|
||||
import { LoteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models';
|
||||
|
||||
const CS = 'https://isssteleon.org/fhir/CodeSystem';
|
||||
export const INTERVALO = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza';
|
||||
export const ESTIMANDO = 'https://isssteleon.org/fhir/StructureDefinition/estimando';
|
||||
|
||||
/** A FHIR prediction: probability `p` from `inicio` to `fin`, with its interval when given. */
|
||||
export function prediccion(p: number, inicio: string, fin: string, ic?: [number, number]): any {
|
||||
@@ -37,9 +38,7 @@ export function riesgoCacuEjemplo(): any {
|
||||
|
||||
/** TEST ONLY. What the record shows from `riesgoCacuEjemplo()`. */
|
||||
export function riesgoCacuVista(): RiesgoPacienteCacu {
|
||||
return {
|
||||
simulado: true,
|
||||
riesgo: {
|
||||
const riesgo: LoteRiesgoCacu = {
|
||||
id: '12-42', modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0', fecha_indice: '2026-06-01',
|
||||
evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final', desenlace: 'cin2_mas', desenlace_texto: 'CIN2+ por biopsia',
|
||||
horizontes: [
|
||||
@@ -47,6 +46,68 @@ export function riesgoCacuVista(): RiesgoPacienteCacu {
|
||||
{ horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28 },
|
||||
{ horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 },
|
||||
],
|
||||
},
|
||||
estimando: null,
|
||||
resultados_indice: null,
|
||||
sin_estimacion: null,
|
||||
};
|
||||
return { simulado: true, riesgo, riesgos: [riesgo] };
|
||||
}
|
||||
|
||||
/** TEST ONLY. `riesgoCacuEjemplo()` from a model whose scenario says what its number is (extension `estimando`). */
|
||||
export function riesgoCacuConEstimando(): any {
|
||||
const data = riesgoCacuEjemplo();
|
||||
const resource = data.entry[0].resource;
|
||||
resource.method.text = 'Riesgo acumulado';
|
||||
resource.extension = [{ url: ESTIMANDO, extension: [
|
||||
{ url: 'quantity', valueString: 'Riesgo acumulado' },
|
||||
{ url: 'description', valueString: 'Probabilidad de CIN2+ antes de cada horizonte.' },
|
||||
{ url: 'outcome', valueString: 'CIN2+: biopsia LIEAG, CIS o carcinoma' },
|
||||
{ url: 'horizons_unit', valueString: 'años' },
|
||||
{ url: 'interval', valueString: 'IC 95 % por método delta' },
|
||||
{ url: 'otra', valueString: 'se ignora' },
|
||||
] }];
|
||||
return data;
|
||||
}
|
||||
|
||||
export const RESULTADOS_INDICE = 'https://isssteleon.org/fhir/StructureDefinition/resultados-indice';
|
||||
|
||||
/** TEST ONLY. `riesgoCacuConEstimando()` plus a cancer `RiskAssessment` of the same visit, both with the index
|
||||
* cytology's results: the Bundle a patient scored by the CIN2+ and the cancer models gets. Cancer comes first, as
|
||||
* the newer batch would. */
|
||||
export function riesgoCacuDosDesenlaces(): any {
|
||||
const data = riesgoCacuConEstimando();
|
||||
const cin2 = data.entry[0].resource;
|
||||
const resultados = { url: RESULTADOS_INDICE, extension: [
|
||||
{ url: 'escamosas', valueString: 'LIEBG' }, { url: 'vph', valueString: 'POSITIVO' }] };
|
||||
cin2.extension.push(resultados);
|
||||
const cancer = structuredClone(cin2);
|
||||
cancer.id = '13-42';
|
||||
cancer.method.coding[0].code = 'modelo-cacu-cancer';
|
||||
cancer.extension[0].extension = cancer.extension[0].extension.map((e: any) =>
|
||||
e.url === 'outcome' ? { ...e, valueString: 'Cáncer: biopsia de carcinoma' } : e);
|
||||
cancer.prediction = [
|
||||
prediccion(0.004, '2026-06-01', '2027-06-01', [0.002, 0.008]),
|
||||
prediccion(0.009, '2026-06-01', '2029-06-01', [0.005, 0.016]),
|
||||
prediccion(0.015, '2026-06-01', '2031-06-01', [0.008, 0.028]),
|
||||
].map(p => ({ ...p, outcome: { coding: [{ system: 'https://isssteleon.org/fhir/CodeSystem/desenlace', code: 'cancer',
|
||||
display: 'Cáncer cervicouterino por biopsia' }] } }));
|
||||
data.entry.unshift({ fullUrl: 'http://localhost/cacu/fhir/RiskAssessment/13-42', resource: cancer });
|
||||
data.total = 2;
|
||||
return data;
|
||||
}
|
||||
|
||||
export const SIN_ESTIMACION = 'https://isssteleon.org/fhir/StructureDefinition/sin-estimacion';
|
||||
|
||||
/** TEST ONLY. `riesgoCacuConEstimando()` plus a current cancer model that didn't score her: a `RiskAssessment` with
|
||||
* no prediction, marked `sin-estimacion`. */
|
||||
export function riesgoCacuCancerSinEstimar(): any {
|
||||
const data = riesgoCacuConEstimando();
|
||||
const cancer = structuredClone(data.entry[0].resource);
|
||||
cancer.id = '13-42';
|
||||
delete cancer.prediction;
|
||||
cancer.extension = [{ url: SIN_ESTIMACION, extension: [{ url: 'desenlace', valueCode: 'cancer' },
|
||||
{ url: 'motivo', valueString: 'queda fuera de su población' }] }];
|
||||
data.entry.push({ fullUrl: 'http://localhost/cacu/fhir/RiskAssessment/13-42', resource: cancer });
|
||||
data.total = 2;
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { isoDate } from '../cacu-seguimiento.models';
|
||||
import { HorizonteRiesgoCacu, LoteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models';
|
||||
import { EstimandoRiesgo, HorizonteRiesgoCacu, LoteRiesgoCacu, ResultadosIndice, RiesgoPacienteCacu } from './paciente-riesgo.models';
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
||||
@@ -9,6 +9,11 @@ const probability = (v: unknown): v is number => finite(v) && v >= 0 && v <= 1;
|
||||
const DAYS_PER_YEAR = 365.25;
|
||||
const INTERVAL = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza';
|
||||
const SIMULATED = 'simulado';
|
||||
const ESTIMAND = 'https://isssteleon.org/fhir/StructureDefinition/estimando';
|
||||
const NOT_SCORED = 'https://isssteleon.org/fhir/StructureDefinition/sin-estimacion';
|
||||
const INDEX_RESULTS = 'https://isssteleon.org/fhir/StructureDefinition/resultados-indice';
|
||||
const INDEX_RESULT_KEYS: readonly (keyof ResultadosIndice)[] = ['escamosas', 'glandulares', 'vph'];
|
||||
const ESTIMAND_KEYS: readonly (keyof EstimandoRiesgo)[] = ['quantity', 'description', 'outcome', 'index_date', 'horizons_unit'];
|
||||
|
||||
function utcTimestamp(v: unknown): v is string {
|
||||
return typeof v === 'string'
|
||||
@@ -39,6 +44,40 @@ function interval(prediction: Record<string, unknown>): { ic_bajo: number | null
|
||||
return { ic_bajo: low, ic_alto: high };
|
||||
}
|
||||
|
||||
/** The resource's extension `url` as its known `keys` with a text value; `null` without that extension. */
|
||||
function stringExtension<K extends string>(resource: Record<string, unknown>, url: string,
|
||||
keys: readonly K[]): Partial<Record<K, string>> | null {
|
||||
const extensions = resource['extension'];
|
||||
if (extensions === undefined) return null;
|
||||
if (!Array.isArray(extensions)) invalid();
|
||||
const found = extensions.find(e => record(e) && e['url'] === url);
|
||||
if (found === undefined) return null;
|
||||
if (!Array.isArray(found['extension'])) invalid();
|
||||
const result: Partial<Record<K, string>> = {};
|
||||
for (const item of found['extension']) {
|
||||
if (!record(item) || !text(item['url'])) invalid();
|
||||
const key = item['url'] as K;
|
||||
if (keys.includes(key) && text(item['valueString'])) result[key] = item['valueString'];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const estimand = (resource: Record<string, unknown>): EstimandoRiesgo | null =>
|
||||
stringExtension(resource, ESTIMAND, ESTIMAND_KEYS);
|
||||
|
||||
/** The `sin-estimacion` extension: the outcome of a current model that didn't score her, and why; `null` without it. */
|
||||
function notScoredOutcome(resource: Record<string, unknown>): { desenlace: string; motivo: string } | null {
|
||||
const extensions = resource['extension'];
|
||||
if (!Array.isArray(extensions)) return null;
|
||||
const found = extensions.find(e => record(e) && e['url'] === NOT_SCORED);
|
||||
if (found === undefined) return null;
|
||||
const items = Array.isArray(found['extension']) ? found['extension'].filter(record) : invalid();
|
||||
const desenlace = items.find(i => i['url'] === 'desenlace')?.['valueCode'];
|
||||
const motivo = items.find(i => i['url'] === 'motivo')?.['valueString'];
|
||||
if (!text(desenlace)) invalid();
|
||||
return { desenlace, motivo: text(motivo) ? motivo : 'el modelo no estima a esta paciente' };
|
||||
}
|
||||
|
||||
function horizon(prediction: unknown, start: string | undefined): { horizonte: HorizonteRiesgoCacu; start: string } {
|
||||
if (!record(prediction) || !probability(prediction['probabilityDecimal'])) invalid();
|
||||
const period = prediction['whenPeriod'];
|
||||
@@ -62,6 +101,15 @@ function riskAssessment(v: unknown, pacId: string | null): LoteRiesgoCacu {
|
||||
const method = v['method'];
|
||||
const model = record(method) && Array.isArray(method['coding']) ? method['coding'][0] : undefined;
|
||||
if (!record(model) || !text(model['code']) || !text(model['version'])) invalid();
|
||||
const notScored = notScoredOutcome(v);
|
||||
if (notScored !== null && v['prediction'] === undefined) {
|
||||
return {
|
||||
id: v['id'] as string, modelo_nombre: model['code'] as string, modelo_version: model['version'] as string,
|
||||
fecha_indice: '', evaluado_en: v['occurrenceDateTime'] as string, estado_lote: v['status'] as 'preliminary' | 'final',
|
||||
desenlace: notScored.desenlace, desenlace_texto: null, horizontes: [], estimando: estimand(v),
|
||||
resultados_indice: null, sin_estimacion: notScored.motivo,
|
||||
};
|
||||
}
|
||||
const predictions = v['prediction'];
|
||||
if (!Array.isArray(predictions) || predictions.length === 0) invalid();
|
||||
let start: string | undefined;
|
||||
@@ -80,7 +128,8 @@ function riskAssessment(v: unknown, pacId: string | null): LoteRiesgoCacu {
|
||||
id: v['id'] as string, modelo_nombre: model['code'] as string, modelo_version: model['version'] as string,
|
||||
fecha_indice: start!, evaluado_en: v['occurrenceDateTime'] as string, estado_lote: v['status'] as 'preliminary' | 'final',
|
||||
desenlace: outcome['code'] as string, desenlace_texto: text(outcome['display']) ? outcome['display'] : null,
|
||||
horizontes,
|
||||
horizontes, estimando: estimand(v), resultados_indice: stringExtension(v, INDEX_RESULTS, INDEX_RESULT_KEYS),
|
||||
sin_estimacion: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -89,16 +138,27 @@ function simulated(resource: Record<string, unknown>): boolean {
|
||||
return record(meta) && Array.isArray(meta['tag']) && meta['tag'].some(t => record(t) && t['code'] === SIMULATED);
|
||||
}
|
||||
|
||||
/** Validate at the boundary: a `searchset` Bundle of the patient's `RiskAssessment`, tagged `simulado` (DEV only).
|
||||
* `null` when the Bundle is empty (no confirmed risk). Rejects real data, coercions and malformed fields. */
|
||||
/** Where an outcome goes among the patient's risks: CIN2+ first, then cancer, then any other. */
|
||||
export function ordenDesenlace(desenlace: string): number {
|
||||
return desenlace.startsWith('cin2') ? 0 : desenlace === 'cancer' ? 1 : 2;
|
||||
}
|
||||
|
||||
/** Validate at the boundary: a `searchset` Bundle of the patient's `RiskAssessment`s, one per outcome, each tagged
|
||||
* `simulado` (DEV only), and one with no prediction for a current model that didn't score her. `riesgo` is the first
|
||||
* that has a risk. `null` when the Bundle is empty (no confirmed risk). Rejects real data, coercions and
|
||||
* malformed fields. */
|
||||
export function riesgoPacienteResponse(v: unknown, pacId: string | null = null): RiesgoPacienteCacu | null {
|
||||
if (!record(v) || v['resourceType'] !== 'Bundle' || v['type'] !== 'searchset' || !finite(v['total'])) invalid();
|
||||
const entries = v['entry'] ?? [];
|
||||
if (!Array.isArray(entries)) invalid();
|
||||
if (entries.length === 0) return null;
|
||||
const resource = record(entries[0]) ? entries[0]['resource'] : undefined;
|
||||
if (!record(resource) || !simulated(resource)) invalid();
|
||||
return { simulado: true, riesgo: riskAssessment(structuredClone(resource), pacId) };
|
||||
const riesgos = entries.map(entry => {
|
||||
const resource = record(entry) ? entry['resource'] : undefined;
|
||||
if (!record(resource) || !simulated(resource)) invalid();
|
||||
return riskAssessment(structuredClone(resource), pacId);
|
||||
});
|
||||
riesgos.sort((a, b) => ordenDesenlace(a.desenlace) - ordenDesenlace(b.desenlace));
|
||||
return { simulado: true, riesgo: riesgos.find(r => r.horizontes.length) ?? riesgos[0], riesgos };
|
||||
}
|
||||
|
||||
/** Presentation helper: an incomplete interval must never become a fabricated range. */
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
// What this module covers: the screening route chart's model and figure. The model turns the seven C3r payloads of the
|
||||
// route (days from the sample and days from the previous event, per event) into one row per event for a period, and
|
||||
// chains the steps one after another; the figure draws them as horizontal bars of days.
|
||||
// Fixtures: `payload`, synthetic C3r /datos shaped like the WebApi's, with the values of the chart's mockup: a
|
||||
// cytology result at 7.9 days, a colposcopy at 35.7, a biopsy result at 52.1 and a diagnosis after it at 64.9.
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import { C2_PALETTE } from './indicadores-c2-palette';
|
||||
import { drawnRows, ROUTE_IDS, routeCellText, routeFigure, routeHasData, routeModel, RouteIncompatible } from './screening-route';
|
||||
|
||||
type Box = [number, number, number, number];
|
||||
const row = (periodo: string, [n, q1, mediana, q3]: Box, extra: Record<string, unknown> = {}) =>
|
||||
({ periodo, grupo: 'TOTAL', estrato: null, n, q1, mediana, q3, n_sin_evento: 0, n_excluido: 0, suprimido: 0, unidad: 'dias', ...extra });
|
||||
const payload = (id: string, filas: Record<string, unknown>[], periodos = ['2025-S1', '2025-S2']): IndicadorDatos =>
|
||||
({ id, contrato: 'C3r', tipo_periodo: 'semestre', periodos, filas, version: '1' });
|
||||
const S2: Record<string, Box> = {
|
||||
cacu_eu_tiempo_reporte: [4855, 4.9, 7.9, 12.2],
|
||||
cacu_dias_toma_colposcopia: [864, 22.2, 35.7, 55.4],
|
||||
cacu_dias_resultado_colposcopia: [864, 17, 27.8, 44],
|
||||
cacu_dias_toma_biopsia: [454, 32.4, 52.1, 80.8],
|
||||
cacu_dias_colposcopia_biopsia: [454, 10, 16.4, 26],
|
||||
cacu_dias_toma_diagnostico: [4999, 11.4, 18.4, 28.5],
|
||||
cacu_dias_biopsia_diagnostico: [454, 8, 12.8, 20],
|
||||
};
|
||||
function all(): Record<string, IndicadorDatos> {
|
||||
return Object.fromEntries(ROUTE_IDS.map(id => [id, payload(id, [row('2025-S1', [10, 1, 2, 3]), row('2025-S2', S2[id])])]));
|
||||
}
|
||||
const figure = (view: 'cumulative' | 'steps', data = all(), period?: string) => routeFigure(routeModel(data, 'semestre', period), view, 'claro');
|
||||
|
||||
describe('Ruta del tamizaje: modelo', () => {
|
||||
it('una fila por evento del periodo más reciente, con los pasos encadenados uno tras otro', () => {
|
||||
// Pins down: the newest period is the default and each step starts where the previous one ends (7.9 + 27.8 = 35.7,
|
||||
// + 16.4 = 52.1, + 12.8 = 64.9). Fails if the chain restarts at zero or follows another order.
|
||||
const m = routeModel(all(), 'semestre');
|
||||
expect(m.periods).toEqual(['2025-S2', '2025-S1']);
|
||||
expect(m.period).toBe('2025-S2');
|
||||
expect(m.rows.map(r => r.step.id)).toEqual(['cytology', 'colposcopy', 'biopsy', 'diagnosis']);
|
||||
expect(m.rows.map(r => [r.start, r.end!.toFixed(1)])).toEqual([[0, '7.9'], [7.9, '35.7'], [35.7, '52.1'], [52.1, '64.9']]);
|
||||
expect(m.rows[1].fromSample).toEqual({ estado: 'Publicado', n: 864, q1: 22.2, mediana: 35.7, q3: 55.4 });
|
||||
});
|
||||
it('un periodo pedido y publicado se usa; uno que no existe cae al más reciente', () => {
|
||||
// Fails if a period nobody published is shown empty instead of falling back.
|
||||
expect(routeModel(all(), 'semestre', '2025-S1').period).toBe('2025-S1');
|
||||
expect(routeModel(all(), 'semestre', '2024-S1').period).toBe('2025-S2');
|
||||
});
|
||||
it('sin periodo pedido, el más reciente vacío no se elige: se usa el más reciente con cajas publicadas', () => {
|
||||
// Fails if the chart opens on a semester that has just begun and shows nothing while an earlier one has data.
|
||||
const vacio = (id: string) => payload(id, [row('2025-S2', S2[id]), row('2026-S1', [0, null as never, null as never, null as never], { suprimido: 1 })], ['2025-S2', '2026-S1']);
|
||||
const data = Object.fromEntries(ROUTE_IDS.map(id => [id, vacio(id)]));
|
||||
expect(routeModel(data, 'semestre').period).toBe('2025-S2');
|
||||
expect(routeModel(data, 'semestre', '2026-S1').period).toBe('2026-S1');
|
||||
});
|
||||
it('un paso suprimido o sin datos no se dibuja y la cadena sigue desde el último publicado', () => {
|
||||
// Pins down: nothing is drawn as zero and the next step starts at the last published end. Fails if a suppressed box
|
||||
// becomes a bar or leaves a gap in the chain.
|
||||
const d = all();
|
||||
d['cacu_dias_colposcopia_biopsia'] = payload('cacu_dias_colposcopia_biopsia', [row('2025-S2', [454, 10, 16.4, 26], { suprimido: 1 })]);
|
||||
const m = routeModel(d, 'semestre');
|
||||
expect(m.rows[2]).toMatchObject({ start: null, end: null });
|
||||
expect(m.rows[3].start!.toFixed(1)).toBe('35.7');
|
||||
expect(drawnRows(m, 'steps').map(r => r.step.id)).toEqual(['cytology', 'colposcopy', 'diagnosis']);
|
||||
d['cacu_dias_toma_biopsia'] = payload('cacu_dias_toma_biopsia', []);
|
||||
expect(drawnRows(routeModel(d, 'semestre'), 'cumulative').map(r => r.step.id)).toEqual(['cytology', 'colposcopy', 'diagnosis']);
|
||||
});
|
||||
it('rechaza datos de otro indicador, contrato, tipo de periodo o unidad, y dos totales por periodo', () => {
|
||||
// Fails if a payload that doesn't belong to the route is drawn as if it did.
|
||||
const con = (id: string, cambio: Partial<IndicadorDatos>) => ({ ...all(), [id]: { ...all()[id], ...cambio } });
|
||||
expect(() => routeModel(con('cacu_eu_tiempo_reporte', { id: 'otro' }), 'semestre')).toThrow(RouteIncompatible);
|
||||
expect(() => routeModel(con('cacu_eu_tiempo_reporte', { contrato: 'C1' }), 'semestre')).toThrow(RouteIncompatible);
|
||||
expect(() => routeModel(all(), 'mes')).toThrow(RouteIncompatible);
|
||||
expect(() => routeModel(con('cacu_eu_tiempo_reporte', { filas: [row('2025-S2', S2['cacu_eu_tiempo_reporte'], { unidad: 'horas' })] }), 'semestre')).toThrow(RouteIncompatible);
|
||||
expect(() => routeModel(con('cacu_eu_tiempo_reporte', { filas: [row('2025-S2', [1, 1, 1, 1]), row('2025-S2', [2, 2, 2, 2])] }), 'semestre')).toThrow(RouteIncompatible);
|
||||
const sinUno = all(); delete sinUno['cacu_dias_toma_biopsia'];
|
||||
expect(() => routeModel(sinUno, 'semestre')).toThrow(RouteIncompatible);
|
||||
});
|
||||
it('sin periodos publicados no hay nada que dibujar', () => {
|
||||
// Fails if an empty catalog throws or draws an empty bar.
|
||||
const vacio = Object.fromEntries(ROUTE_IDS.map(id => [id, payload(id, [], [])]));
|
||||
const m = routeModel(vacio, 'semestre');
|
||||
expect(m.period).toBeUndefined();
|
||||
expect(routeHasData(m)).toBe(false);
|
||||
expect(routeFigure(m, 'cumulative', 'claro')).toEqual({ data: [], layout: {} });
|
||||
});
|
||||
it('la celda de la tabla dice el estado si no hay caja publicada', () => {
|
||||
expect(routeCellText({ estado: 'Suprimido' })).toBe('Suprimido');
|
||||
expect(routeCellText(routeModel(all(), 'semestre').rows[0].fromSample)).toBe('n = 4,855, Q1 4.9, mediana 7.9, Q3 12.2 días');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Ruta del tamizaje: figura', () => {
|
||||
it('acumulado: barras horizontales hasta la mediana con el intervalo de Q1 a Q3 y el número de casos', () => {
|
||||
// Pins down: orientation, bar lengths, the asymmetric interval, the case counts in the labels and the first
|
||||
// event on top. Fails if the bars stop being horizontal or the interval stops being Q1 to Q3.
|
||||
const f = figure('cumulative');
|
||||
const trace = f.data[0] as Record<string, any>;
|
||||
expect(trace['type']).toBe('bar');
|
||||
expect(trace['orientation']).toBe('h');
|
||||
expect(trace['x']).toEqual([7.9, 35.7, 52.1, 18.4]);
|
||||
expect(trace['error_x'].array.map((v: number) => +v.toFixed(1))).toEqual([4.3, 19.7, 28.7, 10.1]);
|
||||
expect(trace['error_x'].arrayminus.map((v: number) => +v.toFixed(1))).toEqual([3, 13.5, 19.7, 7]);
|
||||
expect(trace['y'][0]).toBe('Resultado de citología<br>n = 4,855');
|
||||
expect(trace['y']).toHaveLength(4);
|
||||
expect((f.layout['yaxis'] as Record<string, unknown>)['autorange']).toBe('reversed');
|
||||
expect(JSON.stringify(f.data)).not.toContain('null');
|
||||
});
|
||||
it('por pasos: cada barra flota desde donde termina la anterior y la más lenta lleva el color', () => {
|
||||
// Pins down: `base` equals the chained starts, the length is the step's own median, the slowest step (colposcopy,
|
||||
// 27.8 days) is the only one in colour. Fails if the steps stop floating or the emphasis moves.
|
||||
const f = figure('steps');
|
||||
const trace = f.data[0] as Record<string, any>;
|
||||
expect(trace['base'].map((v: number) => +v.toFixed(1))).toEqual([0, 7.9, 35.7, 52.1]);
|
||||
expect(trace['x']).toEqual([7.9, 27.8, 16.4, 12.8]);
|
||||
expect(trace['text']).toEqual(['+7.9 d', '+27.8 d', '+16.4 d', '+12.8 d']);
|
||||
expect(trace['marker'].color).toEqual([C2_PALETTE.states.noData, C2_PALETTE.series[0], C2_PALETTE.states.noData, C2_PALETTE.states.noData]);
|
||||
expect(trace['y'][1]).toBe('Del resultado de citología a la colposcopía<br>n = 864');
|
||||
expect(trace['hovertemplate']).toContain('Hasta el día');
|
||||
});
|
||||
it('un paso sin caja se omite de la figura sin dejar huecos', () => {
|
||||
// Fails if an undrawn step keeps its label or leaves a null in the traces.
|
||||
const d = all();
|
||||
d['cacu_dias_toma_biopsia'] = payload('cacu_dias_toma_biopsia', [row('2025-S2', S2['cacu_dias_toma_biopsia'], { suprimido: 1 })]);
|
||||
const trace = figure('cumulative', d).data[0] as Record<string, any>;
|
||||
expect(trace['y']).toHaveLength(3);
|
||||
expect(trace['x']).toEqual([7.9, 35.7, 18.4]);
|
||||
});
|
||||
it('el tema oscuro cambia fondo y texto, no los datos', () => {
|
||||
const claro = figure('steps'), oscuro = routeFigure(routeModel(all(), 'semestre'), 'steps', 'oscuro');
|
||||
expect(oscuro.layout['paper_bgcolor']).toBe('#081839');
|
||||
expect(claro.layout['paper_bgcolor']).toBe('#FFFFFF');
|
||||
expect(oscuro.data[0]['x']).toEqual(claro.data[0]['x']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
import { IndicadorDatos, PlotlyFigure, Tema, TipoPeriodo } from './indicadores.models';
|
||||
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
|
||||
import { Caja, caja } from './indicadores-tiempos-pareados';
|
||||
|
||||
/**
|
||||
* The screening route as a chain of events timed from the sample: the cytology result, the colposcopy, the biopsy
|
||||
* result and the diagnosis. Each event has two C3r measures: the days from the sample and the days from the previous
|
||||
* event. The cytology's step is its own days from the sample.
|
||||
*/
|
||||
export interface RouteStep {
|
||||
id: 'cytology' | 'colposcopy' | 'biopsy' | 'diagnosis';
|
||||
label: string;
|
||||
stepLabel: string;
|
||||
sinceSample: string;
|
||||
sinceStep: string;
|
||||
}
|
||||
export const ROUTE_STEPS: readonly RouteStep[] = [
|
||||
{ id: 'cytology', label: 'Resultado de citología', stepLabel: 'Toma a resultado de citología',
|
||||
sinceSample: 'cacu_eu_tiempo_reporte', sinceStep: 'cacu_eu_tiempo_reporte' },
|
||||
{ id: 'colposcopy', label: 'Resultado de colposcopía', stepLabel: 'Del resultado de citología a la colposcopía',
|
||||
sinceSample: 'cacu_dias_toma_colposcopia', sinceStep: 'cacu_dias_resultado_colposcopia' },
|
||||
{ id: 'biopsy', label: 'Resultado de biopsia', stepLabel: 'De la colposcopía al resultado de biopsia',
|
||||
sinceSample: 'cacu_dias_toma_biopsia', sinceStep: 'cacu_dias_colposcopia_biopsia' },
|
||||
{ id: 'diagnosis', label: 'Diagnóstico', stepLabel: 'Del resultado de biopsia al diagnóstico',
|
||||
sinceSample: 'cacu_dias_toma_diagnostico', sinceStep: 'cacu_dias_biopsia_diagnostico' },
|
||||
];
|
||||
/** Every measure the chart reads, once each. */
|
||||
export const ROUTE_IDS: readonly string[] = [...new Set(ROUTE_STEPS.flatMap(s => [s.sinceSample, s.sinceStep]))];
|
||||
|
||||
/** The measures only this chart draws: the cytology's and the diagnosis' keep their own cards. */
|
||||
/** CaCu's measures with no card on the page: the two times to treatment, the proportions without a figure and the risk by band. They are in the history. */
|
||||
export const CACU_SIN_TARJETA: readonly string[] = ['cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'ind1', 'cacu_eu13', 'cacu_riesgo_banda'];
|
||||
export const ROUTE_ONLY_IDS: readonly string[] = ROUTE_IDS.filter(id => id !== 'cacu_eu_tiempo_reporte' && id !== 'cacu_dias_toma_diagnostico');
|
||||
|
||||
export type RouteView = 'cumulative' | 'steps';
|
||||
export interface RouteRow {
|
||||
step: RouteStep;
|
||||
fromSample: Caja;
|
||||
fromPrevious: Caja;
|
||||
/** Where the step starts and ends on the days axis, when chained one after another; null without a published box. */
|
||||
start: number | null;
|
||||
end: number | null;
|
||||
}
|
||||
export interface RouteModel { period: string | undefined; periods: string[]; rows: RouteRow[]; }
|
||||
export class RouteIncompatible extends Error {}
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const fail = (message: string): never => { throw new RouteIncompatible(message); };
|
||||
const NOT_AVAILABLE: Caja = { estado: 'No disponible' };
|
||||
|
||||
/** The seven C3r /datos payloads -> one row per event for a period, newest period first when none is requested. */
|
||||
export function routeModel(data: Record<string, IndicadorDatos>, tipo: TipoPeriodo, requested?: string): RouteModel {
|
||||
const boxes: Record<string, Record<string, Caja>> = {};
|
||||
for (const id of ROUTE_IDS) {
|
||||
const d = data[id];
|
||||
if (!d || d.id !== id || d.contrato !== 'C3r' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos)
|
||||
|| new Set(d.periodos).size !== d.periodos.length) {
|
||||
fail('Los datos de tiempos no corresponden a los indicadores de la ruta del tamizaje.');
|
||||
}
|
||||
boxes[id] = {};
|
||||
for (const row of d.filas) {
|
||||
if (!record(row) || typeof row['periodo'] !== 'string' || !d.periodos.includes(row['periodo'])) fail('Fila C3r fuera de los periodos publicados.');
|
||||
if (row['grupo'] !== 'TOTAL' || row['estrato'] != null) continue;
|
||||
if (row['unidad'] !== undefined && row['unidad'] !== 'dias') fail('Unidad de tiempo distinta de días.');
|
||||
const period = row['periodo'] as string;
|
||||
if (boxes[id][period]) fail('Más de una fila total por periodo.');
|
||||
boxes[id][period] = caja(row);
|
||||
}
|
||||
}
|
||||
const periods = [...new Set(ROUTE_IDS.flatMap(id => data[id].periodos))].sort().reverse();
|
||||
// Without a valid request the newest period that has a published box: a semester that has just begun is empty.
|
||||
const hasData = (p: string) => ROUTE_IDS.some(id => boxes[id][p]?.estado === 'Publicado');
|
||||
const period = requested && periods.includes(requested) ? requested : periods.find(hasData) ?? periods[0];
|
||||
let cursor = 0;
|
||||
const rows = ROUTE_STEPS.map((step): RouteRow => {
|
||||
const fromSample = period ? boxes[step.sinceSample][period] ?? NOT_AVAILABLE : NOT_AVAILABLE;
|
||||
const fromPrevious = period ? boxes[step.sinceStep][period] ?? NOT_AVAILABLE : NOT_AVAILABLE;
|
||||
if (fromPrevious.estado !== 'Publicado') return { step, fromSample, fromPrevious, start: null, end: null };
|
||||
const start = cursor;
|
||||
cursor += fromPrevious.mediana!;
|
||||
return { step, fromSample, fromPrevious, start, end: cursor };
|
||||
});
|
||||
return { period, periods, rows };
|
||||
}
|
||||
|
||||
/** The rows with a published box for the view. */
|
||||
export function drawnRows(model: RouteModel, view: RouteView): RouteRow[] {
|
||||
return model.rows.filter(row => (view === 'cumulative' ? row.fromSample : row.fromPrevious).estado === 'Publicado');
|
||||
}
|
||||
export const routeHasData = (model: RouteModel) => drawnRows(model, 'cumulative').length > 0 || drawnRows(model, 'steps').length > 0;
|
||||
|
||||
const days = (v: number) => v.toLocaleString('es-MX', { maximumFractionDigits: 1 });
|
||||
const count = (v: number) => v.toLocaleString('es-MX');
|
||||
|
||||
/**
|
||||
* Horizontal bars of days. Cumulative: from the sample to each event, with the Q1 to Q3 range as the interval. Steps:
|
||||
* each step floats from where the previous one ends, and the slowest is the one in colour.
|
||||
*/
|
||||
export function routeFigure(model: RouteModel, view: RouteView, tema: Tema): PlotlyFigure {
|
||||
const t = c2Theme(tema);
|
||||
const rows = drawnRows(model, view);
|
||||
if (!rows.length) return { data: [], layout: {} };
|
||||
const base = { autosize: true, height: 360, showlegend: false, paper_bgcolor: t.background, plot_bgcolor: t.background, font: { color: t.text },
|
||||
margin: { t: 24, l: 150, r: 32, b: 56 } };
|
||||
const axes = {
|
||||
xaxis: { title: { text: 'Días' }, rangemode: 'tozero', gridcolor: t.grid, zeroline: false, fixedrange: true },
|
||||
yaxis: { autorange: 'reversed', type: 'category', automargin: true, fixedrange: true },
|
||||
};
|
||||
if (view === 'cumulative') {
|
||||
const boxes = rows.map(row => row.fromSample);
|
||||
return { data: [{
|
||||
type: 'bar', orientation: 'h', y: rows.map((row, i) => `${row.step.label}<br>n = ${count(boxes[i].n!)}`), x: boxes.map(b => b.mediana),
|
||||
marker: { color: C2_PALETTE.series[0] },
|
||||
error_x: { type: 'data', symmetric: false, color: t.text, thickness: 1.5, width: 6,
|
||||
array: boxes.map(b => b.q3! - b.mediana!), arrayminus: boxes.map(b => b.mediana! - b.q1!) },
|
||||
customdata: boxes.map(b => [count(b.n!), days(b.q1!), days(b.mediana!), days(b.q3!)]),
|
||||
hovertemplate: '%{y}<br>Mediana: %{customdata[2]} días<br>Q1 a Q3: %{customdata[1]} a %{customdata[3]} días<extra></extra>',
|
||||
}], layout: { ...base, ...axes }, config: { displayModeBar: false } };
|
||||
}
|
||||
const slowest = rows.reduce((best, row, i) => (row.fromPrevious.mediana! > rows[best].fromPrevious.mediana! ? i : best), 0);
|
||||
const boxes = rows.map(row => row.fromPrevious);
|
||||
return { data: [{
|
||||
type: 'bar', orientation: 'h', y: rows.map((row, i) => `${row.step.stepLabel}<br>n = ${count(boxes[i].n!)}`), x: boxes.map(b => b.mediana),
|
||||
base: rows.map(row => row.start),
|
||||
marker: { color: rows.map((_, i) => (i === slowest ? C2_PALETTE.series[0] : C2_PALETTE.states.noData)) },
|
||||
text: boxes.map(b => `+${days(b.mediana!)} d`), textposition: 'inside', insidetextanchor: 'start', textfont: { color: '#081839' }, cliponaxis: false,
|
||||
customdata: rows.map((row, i) => [count(boxes[i].n!), days(boxes[i].q1!), days(boxes[i].mediana!), days(boxes[i].q3!), days(row.end!)]),
|
||||
hovertemplate: '%{y}<br>Tramo: %{customdata[2]} días (Q1 a Q3: %{customdata[1]} a %{customdata[3]})<br>Hasta el día %{customdata[4]}<extra></extra>',
|
||||
}], layout: { ...base, ...axes }, config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
export function routeCellText(box: Caja): string {
|
||||
return box.estado !== 'Publicado' ? box.estado : `n = ${count(box.n!)}, Q1 ${days(box.q1!)}, mediana ${days(box.mediana!)}, Q3 ${days(box.q3!)} días`;
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common
|
||||
import fixtureData from './fixtures/cama_seguimiento.json';
|
||||
import finalResponse from './fixtures/cama_seguimiento-final.json';
|
||||
import outsideResponse from './fixtures/cama_seguimiento-out-of-range.json';
|
||||
import { PAGE_SIZE_MAX, SeguimientoInvalido, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse, validQuery } from './seguimiento-tabla.service';
|
||||
import { acotarTamano, PAGE_SIZE_MAX, SeguimientoInvalido, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse, validQuery } from './seguimiento-tabla.service';
|
||||
|
||||
const clonar = () => structuredClone(fixtureData) as unknown as Record<string, any>;
|
||||
const consulta: SeguimientoTablaQuery = { meses: 3, page: 1, page_size: 50 };
|
||||
@@ -132,3 +132,16 @@ describe('Seguimiento genérico: petición', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('acotarTamano', () => {
|
||||
it('brings a typed page size into 1 to the maximum, and falls back when it is not a number', () => {
|
||||
expect(acotarTamano(500)).toBe(PAGE_SIZE_MAX);
|
||||
expect(acotarTamano('999')).toBe(PAGE_SIZE_MAX);
|
||||
expect(acotarTamano(0)).toBe(1);
|
||||
expect(acotarTamano(-7)).toBe(1);
|
||||
expect(acotarTamano(25.9)).toBe(25);
|
||||
expect(acotarTamano('')).toBe(1);
|
||||
expect(acotarTamano('x')).toBe(50);
|
||||
expect(acotarTamano(undefined, 20)).toBe(20);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -44,6 +44,11 @@ export type MesesVentana = typeof MESES_VENTANA[number];
|
||||
/** What the window is called on screen and in the files: the whole cohort or a number of months. */
|
||||
export const etiquetaVentana = (meses: number) => meses === 0 ? 'Toda la cohorte' : `${meses} ${meses === 1 ? 'mes' : 'meses'}`;
|
||||
export const PAGE_SIZE_MAX = 200;
|
||||
/** A page size typed in a form, brought into 1..PAGE_SIZE_MAX: an input's `max` only flags the field, it does not stop a larger number. */
|
||||
export const acotarTamano = (valor: unknown, defecto = 50) => {
|
||||
const n = Math.trunc(Number(valor));
|
||||
return Number.isFinite(n) ? Math.min(PAGE_SIZE_MAX, Math.max(1, n)) : defecto;
|
||||
};
|
||||
const RESERVADAS = ['meses', 'page', 'page_size', 'corte', ...CLAVES_CONTEXTO];
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
Experiment,
|
||||
ExperimentDetail,
|
||||
ExperimentRequest,
|
||||
NotebookTemplate,
|
||||
ModelLineage,
|
||||
ModelVersion,
|
||||
PromotionCheck,
|
||||
@@ -85,10 +86,17 @@ export class GovernanceApi {
|
||||
return this.http.get<{ experiments: Experiment[] }>('/governance/experiments', { params: toParams(filters) });
|
||||
}
|
||||
|
||||
/** Starts the notebook on the build in the background; answers with the run while it is still `en_curso`. */
|
||||
/** The domain's notebooks kept in the code, each with the scenarios it can run for. */
|
||||
notebookTemplates(domain: string): Observable<{ templates: NotebookTemplate[] }> {
|
||||
return this.http.get<{ templates: NotebookTemplate[] }>('/governance/notebook-templates', { params: toParams({ domain }) });
|
||||
}
|
||||
|
||||
/** Starts the notebook (an upload, or a template the API reads from the code) on the build in the background;
|
||||
* answers with the run while it is still `en_curso`. */
|
||||
runExperiment(request: ExperimentRequest): Observable<ExperimentDetail> {
|
||||
const form = new FormData();
|
||||
form.append('file', request.file);
|
||||
if (request.template) form.append('template', request.template);
|
||||
else if (request.file) form.append('file', request.file);
|
||||
form.append('domain', request.domain);
|
||||
form.append('scenario', request.scenario);
|
||||
form.append('url', request.build.url);
|
||||
|
||||
@@ -79,8 +79,20 @@ export interface ExperimentDetail extends Experiment {
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/** A notebook kept in the code (`models/<domain>/<scenario>/notebooks/`), and the scenarios it can run for. */
|
||||
export interface NotebookTemplate {
|
||||
id: string;
|
||||
domain: Domain;
|
||||
scenario: string;
|
||||
name: string;
|
||||
scenarios: string[];
|
||||
title: string;
|
||||
}
|
||||
|
||||
/** One of `file` (an upload) or `template` (a notebook kept in the code, by its id). */
|
||||
export interface ExperimentRequest {
|
||||
file: File;
|
||||
file?: File | null;
|
||||
template?: string | null;
|
||||
domain: Domain;
|
||||
scenario: string;
|
||||
build: CohortBuildFile;
|
||||
|
||||
@@ -83,24 +83,25 @@
|
||||
|
||||
<section aria-labelledby="routines-title">
|
||||
<h3 id="routines-title">Rutinas del entrenamiento</h3>
|
||||
<p class="muted">Lo que cada rutina hizo, registrado por la corrida mientras entrenaba (ML-01a).</p>
|
||||
<ul class="artifacts">
|
||||
@for (routine of routineKinds; track routine.kind) {
|
||||
@let record = l.routines[routine.kind];
|
||||
<li [class.checks__fail]="!record">
|
||||
<mat-icon aria-hidden="true">{{ record ? 'check_circle' : 'cancel' }}</mat-icon>
|
||||
<span class="artifacts__kind">{{ routine.label }}</span>
|
||||
@if (record) {
|
||||
<p class="muted">Lo que cada rutina hizo, registrado por la corrida mientras entrenaba. No todos los modelos
|
||||
tienen cada rutina; no se piden para promover (ML-01a lo cumple la corrida misma).</p>
|
||||
@let recorded = recordedRoutines(l.routines);
|
||||
@if (recorded.length) {
|
||||
<ul class="artifacts">
|
||||
@for (routine of recorded; track routine.kind) {
|
||||
<li>
|
||||
<mat-icon aria-hidden="true">check_circle</mat-icon>
|
||||
<span class="artifacts__kind">{{ routine.label }}</span>
|
||||
<details class="routine">
|
||||
<summary>{{ record['method'] ?? 'Ver registro' }}</summary>
|
||||
<pre>{{ record | json }}</pre>
|
||||
<summary>{{ routine.record['method'] ?? 'Ver registro' }}</summary>
|
||||
<pre>{{ routine.record | json }}</pre>
|
||||
</details>
|
||||
} @else {
|
||||
<span class="muted">La corrida no la registró.</span>
|
||||
}
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
} @else {
|
||||
<p class="muted">La corrida no guardó registros de rutina.</p>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="artifacts-title">
|
||||
|
||||
@@ -55,7 +55,10 @@ export class ModelVersionDialog {
|
||||
private readonly version = inject<ModelVersion>(MAT_DIALOG_DATA);
|
||||
private readonly dialog = inject(MatDialog);
|
||||
|
||||
readonly routineKinds = ROUTINES;
|
||||
/** The routines the run recorded, in `ROUTINES`' order; the others aren't listed. */
|
||||
recordedRoutines(routines: ModelLineage['routines']) {
|
||||
return ROUTINES.filter((r) => routines[r.kind]).map((r) => ({ ...r, record: routines[r.kind]! }));
|
||||
}
|
||||
readonly lineage = signal<ModelLineage | null>(null);
|
||||
readonly busy = signal(false);
|
||||
readonly error = signal<string | null>(null);
|
||||
|
||||
@@ -2,19 +2,39 @@
|
||||
|
||||
<mat-dialog-content class="content">
|
||||
<p class="hint">
|
||||
El notebook corre aislado en el servidor, sin red y con los datos de la cohorte que elija como única información: no
|
||||
Elija un notebook del código (<code>models/<dominio>/<escenario>/notebooks/</code>) o suba uno. Corre
|
||||
aislado en el servidor, sin red y con los datos de la cohorte que elija como única información: no
|
||||
ve las bases de datos ni los demás archivos. Dentro usa <code>from models.notebook import experiment</code> para leer
|
||||
la cohorte, cargar la versión elegida o entrenar; lo que entrene se registra como versión de desarrollo al terminar.
|
||||
La corrida guarda el notebook, la página con sus resultados y con qué datos se corrió.
|
||||
</p>
|
||||
|
||||
<div class="file">
|
||||
<button mat-stroked-button type="button" [disabled]="busy()" (click)="fileInput.click()">
|
||||
<mat-icon aria-hidden="true">upload_file</mat-icon>Elegir notebook
|
||||
</button>
|
||||
<span class="file__name">{{ file()?.name ?? 'Ningún archivo (.ipynb)' }}</span>
|
||||
<input #fileInput type="file" accept=".ipynb,application/x-ipynb+json" hidden (change)="pick($event)" />
|
||||
</div>
|
||||
<mat-button-toggle-group [value]="source()" (change)="source.set($event.value)" aria-label="Origen del notebook">
|
||||
<mat-button-toggle value="plantilla" [disabled]="!templates().length">Del código</mat-button-toggle>
|
||||
<mat-button-toggle value="archivo">Subir archivo</mat-button-toggle>
|
||||
</mat-button-toggle-group>
|
||||
|
||||
@if (source() === 'plantilla') {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Notebook del código</mat-label>
|
||||
<mat-select [ngModel]="template()" (ngModelChange)="setTemplate($event)" [compareWith]="sameTemplate">
|
||||
@for (option of templates(); track option.id) {
|
||||
<mat-option [value]="option">{{ templateLabel(option) }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
@if (template(); as chosen) {
|
||||
<mat-hint>Corre para: {{ chosen.scenarios.join(', ') }}</mat-hint>
|
||||
}
|
||||
</mat-form-field>
|
||||
} @else {
|
||||
<div class="file">
|
||||
<button mat-stroked-button type="button" [disabled]="busy()" (click)="fileInput.click()">
|
||||
<mat-icon aria-hidden="true">upload_file</mat-icon>Elegir notebook
|
||||
</button>
|
||||
<span class="file__name">{{ file()?.name ?? 'Ningún archivo (.ipynb)' }}</span>
|
||||
<input #fileInput type="file" accept=".ipynb,application/x-ipynb+json" hidden (change)="pick($event)" />
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="grid">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
@@ -31,6 +51,8 @@
|
||||
<input matInput [ngModel]="scenario()" (ngModelChange)="setScenario($event)" placeholder="cin2_logistic" />
|
||||
@if (scenario() && !scenarioValid()) {
|
||||
<mat-error>Solo letras, números, guion y guion bajo.</mat-error>
|
||||
} @else if (source() === 'plantilla' && template() && !notebookReady()) {
|
||||
<mat-hint>Esta plantilla no corre para ese escenario.</mat-hint>
|
||||
} @else {
|
||||
<mat-hint>El de un modelo existente o uno nuevo para el experimento.</mat-hint>
|
||||
}
|
||||
|
||||
@@ -2,18 +2,28 @@ import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
|
||||
import { NotebookTemplate } from '../../api/governance.types';
|
||||
import { NotebookRunDialog } from './notebook-run-dialog';
|
||||
|
||||
/**
|
||||
* The dialog that uploads a notebook and runs it on a cohort build: it starts
|
||||
* from a version's defaults, offers the domain's exported builds, and sends
|
||||
* the build the person chose. The API is `HttpTestingController`; the dialog
|
||||
* The dialog that runs a notebook on a cohort build, one kept in the code or an
|
||||
* upload: it starts from a version's defaults, offers the domain's templates and
|
||||
* exported builds, and sends the notebook and build the person chose. The API is `HttpTestingController`; the dialog
|
||||
* reference is a stub that records how it closed.
|
||||
*/
|
||||
describe('NotebookRunDialog', () => {
|
||||
let http: HttpTestingController;
|
||||
const close = vi.fn();
|
||||
const build = { url: 'cacu/cohorte_vigilancia', source: 'dbt', build: 4, datos_as_of: '2025-12-31', n_members: '10' };
|
||||
const pim: NotebookTemplate = {
|
||||
id: 'cacu/cin2_pim/reporte_subgrupos', domain: 'cacu', scenario: 'cin2_pim', name: 'reporte_subgrupos',
|
||||
scenarios: ['cin2_pim', 'cin2_pim_post_colposcopy'], title: 'Riesgo acumulado de CIN2+ por combinación',
|
||||
};
|
||||
|
||||
function templates(found: object[] = []) {
|
||||
http.expectOne((r) => r.url === '/governance/notebook-templates' && r.params.get('domain') === 'cacu')
|
||||
.flush({ templates: found });
|
||||
}
|
||||
|
||||
function open(data: object) {
|
||||
TestBed.configureTestingModule({
|
||||
@@ -39,10 +49,12 @@ describe('NotebookRunDialog', () => {
|
||||
it('sends the chosen build and version with the notebook, and closes with the run', () => {
|
||||
// Fails if the form stops carrying the build's url, source and number, or drops the version it was opened with.
|
||||
const fixture = open({ domain: 'cacu', scenario: 'cin2_logistic', version: '3' });
|
||||
templates();
|
||||
http.expectOne((r) => r.url === '/governance/cohort-files' && r.params.get('domain') === 'cacu').flush({ builds: [build] });
|
||||
http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] });
|
||||
const dialog = fixture.componentInstance;
|
||||
expect(dialog.ready()).toBe(false);
|
||||
expect(dialog.source()).toBe('archivo'); // no templates in the domain: the upload is the only source
|
||||
|
||||
dialog.file.set(new File(['{}'], 'analisis.ipynb'));
|
||||
expect(dialog.ready()).toBe(true);
|
||||
@@ -60,6 +72,7 @@ describe('NotebookRunDialog', () => {
|
||||
it('refuses a scenario that the API would reject', () => {
|
||||
// Fails if `ready` stops checking the scenario's characters before uploading.
|
||||
const fixture = open({});
|
||||
templates();
|
||||
http.expectOne((r) => r.url === '/governance/cohort-files').flush({ builds: [build] });
|
||||
const dialog = fixture.componentInstance;
|
||||
dialog.file.set(new File(['{}'], 'a.ipynb'));
|
||||
@@ -69,4 +82,33 @@ describe('NotebookRunDialog', () => {
|
||||
http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] });
|
||||
expect(dialog.ready()).toBe(true);
|
||||
});
|
||||
|
||||
it('runs a template from the code for a scenario it serves, sending its id and no file', () => {
|
||||
// Fails if choosing a template stops filling its scenario, the form sends a file with it, or a scenario the
|
||||
// template doesn't serve is let through.
|
||||
const fixture = open({});
|
||||
templates([pim]);
|
||||
http.expectOne((r) => r.url === '/governance/cohort-files').flush({ builds: [build] });
|
||||
const dialog = fixture.componentInstance;
|
||||
expect(dialog.source()).toBe('plantilla');
|
||||
|
||||
dialog.setTemplate(pim);
|
||||
http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] });
|
||||
expect(dialog.scenario()).toBe('cin2_pim');
|
||||
expect(dialog.ready()).toBe(true);
|
||||
dialog.setScenario('survival');
|
||||
http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] });
|
||||
expect(dialog.ready()).toBe(false);
|
||||
dialog.setScenario('cin2_pim_post_colposcopy');
|
||||
http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] });
|
||||
dialog.run();
|
||||
|
||||
const request = http.expectOne('/governance/experiments');
|
||||
const form = request.request.body as FormData;
|
||||
expect([form.get('template'), form.get('file'), form.get('scenario')]).toEqual([
|
||||
'cacu/cin2_pim/reporte_subgrupos', null, 'cin2_pim_post_colposcopy',
|
||||
]);
|
||||
request.flush({ run_id: 'r2', status: 'en_curso' });
|
||||
expect(close).toHaveBeenCalledWith(expect.objectContaining({ run_id: 'r2' }));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Component, computed, inject, signal } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
@@ -10,7 +11,7 @@ import { MatSelectModule } from '@angular/material/select';
|
||||
import { Domain, apiErrorMessage } from '../../../connect/api/api.types';
|
||||
import { DOMAINS } from '../../../connect/state/connect-workspace.store';
|
||||
import { GovernanceApi } from '../../api/governance.api';
|
||||
import { CohortBuildFile, ExperimentDetail, ModelVersion } from '../../api/governance.types';
|
||||
import { CohortBuildFile, ExperimentDetail, ModelVersion, NotebookTemplate } from '../../api/governance.types';
|
||||
|
||||
/** What the dialog starts with: a version's dialog passes its own domain, scenario and version. */
|
||||
export interface NotebookRunDefaults {
|
||||
@@ -21,15 +22,20 @@ export interface NotebookRunDefaults {
|
||||
|
||||
const SCENARIO = /^[\w-]{1,100}$/;
|
||||
|
||||
/** Where the notebook comes from: one kept in the code (a template) or an upload. */
|
||||
export type NotebookSource = 'plantilla' | 'archivo';
|
||||
|
||||
/**
|
||||
* Uploads a Jupyter notebook and runs it on a cohort build's file, optionally
|
||||
* with a registered version to try. Closes with the run once it has started.
|
||||
* Runs a Jupyter notebook on a cohort build's file, optionally with a registered
|
||||
* version to try: one kept in the code (`models/<domain>/<scenario>/notebooks/`,
|
||||
* for the scenarios it serves) or an upload. Closes with the run once it has started.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-notebook-run-dialog',
|
||||
imports: [
|
||||
FormsModule,
|
||||
MatButtonModule,
|
||||
MatButtonToggleModule,
|
||||
MatDialogModule,
|
||||
MatFormFieldModule,
|
||||
MatIconModule,
|
||||
@@ -49,7 +55,10 @@ export class NotebookRunDialog {
|
||||
readonly domain = signal<Domain>(this.defaults.domain ?? 'cacu');
|
||||
readonly scenario = signal(this.defaults.scenario ?? '');
|
||||
readonly version = signal<string>(this.defaults.version ?? '');
|
||||
readonly source = signal<NotebookSource>('plantilla');
|
||||
readonly file = signal<File | null>(null);
|
||||
readonly templates = signal<NotebookTemplate[]>([]);
|
||||
readonly template = signal<NotebookTemplate | null>(null);
|
||||
readonly builds = signal<CohortBuildFile[]>([]);
|
||||
readonly build = signal<CohortBuildFile | null>(null);
|
||||
readonly versions = signal<ModelVersion[]>([]);
|
||||
@@ -57,13 +66,34 @@ export class NotebookRunDialog {
|
||||
readonly error = signal<string | null>(null);
|
||||
|
||||
readonly scenarioValid = computed(() => SCENARIO.test(this.scenario()));
|
||||
readonly ready = computed(() => !!this.file() && !!this.build() && this.scenarioValid() && !this.busy());
|
||||
/** The template serves the scenario typed, or the upload is chosen. */
|
||||
readonly notebookReady = computed(() => {
|
||||
if (this.source() === 'archivo') return !!this.file();
|
||||
const template = this.template();
|
||||
return !!template && template.scenarios.includes(this.scenario());
|
||||
});
|
||||
readonly ready = computed(() => this.notebookReady() && !!this.build() && this.scenarioValid() && !this.busy());
|
||||
|
||||
constructor() {
|
||||
this.loadTemplates();
|
||||
this.loadBuilds();
|
||||
this.loadVersions();
|
||||
}
|
||||
|
||||
templateLabel(template: NotebookTemplate): string {
|
||||
return `${template.scenario}/${template.name} · ${template.title}`;
|
||||
}
|
||||
|
||||
sameTemplate(a: NotebookTemplate | null, b: NotebookTemplate | null): boolean {
|
||||
return !!a && !!b && a.id === b.id;
|
||||
}
|
||||
|
||||
/** Choosing a template puts its scenario when the one typed isn't one it serves. */
|
||||
setTemplate(template: NotebookTemplate | null): void {
|
||||
this.template.set(template);
|
||||
if (template && !template.scenarios.includes(this.scenario())) this.setScenario(template.scenario);
|
||||
}
|
||||
|
||||
buildLabel(build: CohortBuildFile): string {
|
||||
const members = build.n_members ? ` · ${build.n_members} miembros` : '';
|
||||
const asOf = build.datos_as_of ? ` · datos al ${build.datos_as_of}` : '';
|
||||
@@ -77,6 +107,7 @@ export class NotebookRunDialog {
|
||||
setDomain(domain: Domain): void {
|
||||
this.domain.set(domain);
|
||||
this.version.set('');
|
||||
this.loadTemplates();
|
||||
this.loadBuilds();
|
||||
this.loadVersions();
|
||||
}
|
||||
@@ -94,13 +125,13 @@ export class NotebookRunDialog {
|
||||
}
|
||||
|
||||
run(): void {
|
||||
const file = this.file();
|
||||
const build = this.build();
|
||||
if (!file || !build || !this.ready()) return;
|
||||
if (!build || !this.ready()) return;
|
||||
const notebook = this.source() === 'plantilla' ? { template: this.template()!.id } : { file: this.file() };
|
||||
this.busy.set(true);
|
||||
this.error.set(null);
|
||||
this.api
|
||||
.runExperiment({ file, domain: this.domain(), scenario: this.scenario(), build, version: this.version() || null })
|
||||
.runExperiment({ ...notebook, domain: this.domain(), scenario: this.scenario(), build, version: this.version() || null })
|
||||
.subscribe({
|
||||
next: (run) => this.dialogRef.close(run),
|
||||
error: (error) => {
|
||||
@@ -110,6 +141,18 @@ export class NotebookRunDialog {
|
||||
});
|
||||
}
|
||||
|
||||
private loadTemplates(): void {
|
||||
this.templates.set([]);
|
||||
this.template.set(null);
|
||||
this.api.notebookTemplates(this.domain()).subscribe({
|
||||
next: ({ templates }) => {
|
||||
this.templates.set(templates);
|
||||
if (!templates.length) this.source.set('archivo');
|
||||
},
|
||||
error: () => this.templates.set([]),
|
||||
});
|
||||
}
|
||||
|
||||
private loadBuilds(): void {
|
||||
this.builds.set([]);
|
||||
this.build.set(null);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Covers the risk batches panel's domain choice: it lists the pending batches of the domain shown (CaCu first, CaMa on
|
||||
// request) and decides a batch in that domain. Fixtures: a stub of `RiskBatchesApi` that records the domain of each call,
|
||||
// request) and decides a batch in that domain, one decision at a time. Fixtures: a stub of `RiskBatchesApi` that records the domain of each call,
|
||||
// and an account that reaches every domain.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { of } from 'rxjs';
|
||||
import { of, Subject } from 'rxjs';
|
||||
import { vi } from 'vitest';
|
||||
import { AuthService } from '../../../auth/auth.service';
|
||||
import { RiskBatchesApi } from '../../api/risk-batches.api';
|
||||
@@ -45,4 +45,21 @@ describe('RiskBatchesPanel domains', () => {
|
||||
|
||||
expect(api['confirm']).toHaveBeenCalledExactlyOnceWith('cama', 5, 'revisado');
|
||||
});
|
||||
|
||||
// Fails if a double click sends the decision twice: the second one finds nothing to decide or collides with the first.
|
||||
it('sends one decision while another is on its way', () => {
|
||||
const answer = new Subject<{ lote_id: number; evaluaciones_cambiadas: number }>();
|
||||
api['confirm'].mockReturnValue(answer);
|
||||
const f = TestBed.createComponent(RiskBatchesPanel);
|
||||
f.detectChanges();
|
||||
const batch = f.componentInstance.batches()[0];
|
||||
f.componentInstance.reasonFor(batch).setValue('revisado');
|
||||
|
||||
f.componentInstance.confirm(batch);
|
||||
f.componentInstance.confirm(batch);
|
||||
f.componentInstance.void(batch);
|
||||
|
||||
expect(api['confirm']).toHaveBeenCalledTimes(1);
|
||||
expect(api['void']).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -111,7 +111,8 @@ export class RiskBatchesPanel implements OnInit {
|
||||
verb: string,
|
||||
): void {
|
||||
const reason = this.reasonFor(batch).value.trim();
|
||||
if (!reason) return;
|
||||
// a double click reaches here before the disabled button is drawn: one decision at a time
|
||||
if (!reason || this.deciding() !== null) return;
|
||||
this.deciding.set(batch.lote_id);
|
||||
request(reason).subscribe({
|
||||
next: () => {
|
||||
|
||||
Reference in New Issue
Block a user