diff --git a/src/app/features/indicadores/fixtures/regresion_cacu_tea_mapeo.json b/src/app/features/indicadores/fixtures/regresion_cacu_tea_mapeo.json index fb039d4..5942e66 100644 --- a/src/app/features/indicadores/fixtures/regresion_cacu_tea_mapeo.json +++ b/src/app/features/indicadores/fixtures/regresion_cacu_tea_mapeo.json @@ -384,7 +384,7 @@ "estrato": null, "valores_estrato": [], "grupos": { - "principal": "principal" + "total": "Total" }, "categorias": {}, "grupos_de_categoria": {}, @@ -410,7 +410,7 @@ "filas": [ { "periodo": "2021-S1", - "grupo": "principal", + "grupo": "total", "estrato": null, "suprimido": 0, "numerador": 0, @@ -423,7 +423,7 @@ }, { "periodo": "2025-S2", - "grupo": "principal", + "grupo": "total", "estrato": null, "suprimido": 0, "numerador": 1, @@ -463,7 +463,7 @@ "<25": "<25" }, "grupos": { - "principal": "principal" + "total": "Total" }, "categorias": {}, "grupos_de_categoria": {}, @@ -489,7 +489,7 @@ "filas": [ { "periodo": "2025-S2", - "grupo": "principal", + "grupo": "total", "estrato": "25-34", "suprimido": 0, "numerador": 0, @@ -502,7 +502,7 @@ }, { "periodo": "2025-S2", - "grupo": "principal", + "grupo": "total", "estrato": "35-44", "suprimido": 0, "numerador": 0, @@ -515,7 +515,7 @@ }, { "periodo": "2025-S2", - "grupo": "principal", + "grupo": "total", "estrato": "45-54", "suprimido": 0, "numerador": 1, @@ -528,7 +528,7 @@ }, { "periodo": "2025-S2", - "grupo": "principal", + "grupo": "total", "estrato": "55-64", "suprimido": 0, "numerador": 0, @@ -541,7 +541,7 @@ }, { "periodo": "2025-S2", - "grupo": "principal", + "grupo": "total", "estrato": "<25", "suprimido": 0, "numerador": 0, @@ -573,7 +573,7 @@ "PRE_COLPOSCOPIA": "PRE_COLPOSCOPIA" }, "grupos": { - "principal": "principal" + "total": "Total" }, "categorias": {}, "grupos_de_categoria": {}, @@ -599,7 +599,7 @@ "filas": [ { "periodo": "2025-S2", - "grupo": "principal", + "grupo": "total", "estrato": "PRE_COLPOSCOPIA", "suprimido": 0, "numerador": 1, @@ -845,7 +845,7 @@ "estrato": null, "valores_estrato": [], "grupos": { - "principal": "principal" + "total": "Total" }, "categorias": {}, "grupos_de_categoria": {}, @@ -871,7 +871,7 @@ "filas": [ { "periodo": "2021-S1", - "grupo": "principal", + "grupo": "total", "estrato": null, "suprimido": 0, "numerador": 0, @@ -884,7 +884,7 @@ }, { "periodo": "2025-S2", - "grupo": "principal", + "grupo": "total", "estrato": null, "suprimido": 0, "numerador": 19, diff --git a/src/app/features/indicadores/indicador-screening-route.html b/src/app/features/indicadores/indicador-screening-route.html new file mode 100644 index 0000000..fef2e09 --- /dev/null +++ b/src/app/features/indicadores/indicador-screening-route.html @@ -0,0 +1,46 @@ +
+

Tiempos de la ruta del tamizaje

+ @switch (status()) { + @case ('deferred') {

La vista se cargará al acercarse a esta región.

} + @case ('loading') {

Cargando los tiempos de la ruta…

} + @case ('error') {

{{ message() }}

} + @case ('incompatible') {

{{ message() }}

} + } + @if (model(); as m) { +
+ + Periodo + + @for (period of m.periods; track period) { {{ periodLabel(period) }} } + + + + Acumulado desde la toma + Por pasos + +
+ @if (status() === 'empty') {

No hay tiempos publicados para esta ruta.

} + @else if (figure(); as figure) { + +

+ @if (view() === 'cumulative') { + Cada barra es la mediana de días desde la toma de muestra hasta ese evento y el bigote va de Q1 a Q3. Cada fila cuenta solo a quienes llegaron a ese evento. + El diagnóstico incluye a quienes lo recibieron tras el tamizaje, en la colposcopía o tras la biopsia, por eso su barra puede salir antes que la de biopsia. + } @else { + Cada barra es el tramo desde el evento anterior y empieza donde termina el tramo previo; la de color es el tramo más lento. Cada tramo cuenta solo a quienes llegaron a sus dos eventos. + Las medianas de los tramos no tienen que sumar el tiempo acumulado. + } +

+ } +
Valores publicados +
+ + + @for (row of m.rows; track row.step.id) { + + } +
Días por evento en {{ m.period ? periodLabel(m.period) : 'el periodo' }}
EventoDesde la tomaDesde el paso anterior
{{ row.step.label }}{{ cellText(row.fromSample) }}{{ cellText(row.fromPrevious) }}
+
+
+ } +
diff --git a/src/app/features/indicadores/indicador-screening-route.scss b/src/app/features/indicadores/indicador-screening-route.scss new file mode 100644 index 0000000..d4a1da2 --- /dev/null +++ b/src/app/features/indicadores/indicador-screening-route.scss @@ -0,0 +1,13 @@ +:host { display: block; min-width: 0; } +.route { min-width: 0; padding-top: var(--issste-space-3); } +p, h3, summary { overflow-wrap: anywhere; } +h3 { font-size: 1rem; line-height: 1.5; } +.controls { display: flex; flex-wrap: wrap; gap: 1rem 1.5rem; align-items: center; margin-block: .75rem; } +.note { color: var(--issste-text-secondary); max-width: 70ch; } +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; } diff --git a/src/app/features/indicadores/indicador-screening-route.spec.ts b/src/app/features/indicadores/indicador-screening-route.spec.ts new file mode 100644 index 0000000..7a804b5 --- /dev/null +++ b/src/app/features/indicadores/indicador-screening-route.spec.ts @@ -0,0 +1,112 @@ +// 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//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(); label = input(); showNotes = input(); } + +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 = { + 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>; + 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)['base']).toBeUndefined(); + f.componentInstance.selectView('steps'); f.detectChanges(); + expect((f.componentInstance.figure()!.data[0] as Record)['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(); + }); +}); diff --git a/src/app/features/indicadores/indicador-screening-route.ts b/src/app/features/indicadores/indicador-screening-route.ts new file mode 100644 index 0000000..c1d66fe --- /dev/null +++ b/src/app/features/indicadores/indicador-screening-route.ts @@ -0,0 +1,86 @@ +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 { 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, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart], + templateUrl: './indicador-screening-route.html', + styleUrl: './indicador-screening-route.scss', +}) +export class IndicadorScreeningRoute { + readonly dominio = input.required(); + readonly tema = input.required(); + readonly tipo = input('semestre'); + /** 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('cumulative'); + readonly requestedPeriod = signal(undefined); + private readonly payloads = signal | undefined>(undefined); + readonly model = computed(() => { + const data = this.payloads(); + return data ? routeModel(data, this.tipo(), this.requestedPeriod()) : undefined; + }); + readonly figure = computed(() => { + const model = this.model(); + return model && routeHasData(model) ? routeFigure(model, this.view(), this.tema()) : undefined; + }); + 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)); + }); + 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'); + } +} diff --git a/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts b/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts index be2a426..a4a773b 100644 --- a/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts @@ -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([]); + } + }); }); diff --git a/src/app/features/indicadores/indicadores-cacu-fhir.ts b/src/app/features/indicadores/indicadores-cacu-fhir.ts index a4adba9..fb0f1ac 100644 --- a/src/app/features/indicadores/indicadores-cacu-fhir.ts +++ b/src/app/features/indicadores/indicadores-cacu-fhir.ts @@ -6,6 +6,11 @@ // the correspondence is explicit, as CaMa's is, and a measure outside it keeps the generic rule. export const CACU_MEASURE_IDS: Readonly> = { 'CACU-CONFIRMACION-CITOLOGIA': 'cacu_confirmacion_citologia', + 'CACU-DIAS-BIOPSIA-DIAGNOSTICO': 'cacu_dias_biopsia_diagnostico', + 'CACU-DIAS-COLPOSCOPIA-BIOPSIA': 'cacu_dias_colposcopia_biopsia', + '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-EU-TIEMPO-REPORTE': 'cacu_eu_tiempo_reporte', 'CACU-EU13': 'cacu_eu13', diff --git a/src/app/features/indicadores/indicadores-fhir.ts b/src/app/features/indicadores/indicadores-fhir.ts index 5a5e54a..70c7867 100644 --- a/src/app/features/indicadores/indicadores-fhir.ts +++ b/src/app/features/indicadores/indicadores-fhir.ts @@ -56,6 +56,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. @@ -146,7 +148,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, }; @@ -251,10 +253,10 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP : { ...declaradas, ...Object.fromEntries([...extras].map(([categoria, etiqueta]) => [categoria, { etiqueta, color: null, grupo: null }])) }; const totales: Record[] = []; - // CaMa's page names the primary group of a proportion `total`; the WebApi names it `principal`. + // The page names the primary group of a proportion `total`; the WebApi names it `principal`. const nombre = (codigo: string | undefined) => { const grupo = codigo ?? 'TOTAL'; - return cama && kind === 'C1' && grupo === GRUPO_PRINCIPAL_FHIR ? GRUPO_PRINCIPAL_PAGINA : grupo; + return kind === 'C1' && grupo === GRUPO_PRINCIPAL_FHIR ? GRUPO_PRINCIPAL_PAGINA : grupo; }; const grupos = Object.fromEntries((measure.group ?? []).map(g => { const id = nombre(code(g.code)); diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index 55283b3..b03db42 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -115,6 +115,7 @@ Incluye el periodo y los indicadores seleccionados. Elige «Guardar como PDF» en el cuadro de impresión. } + @if (screeningRouteAvailable) { }
@if (histopatologiaPendiente) { } @for (item of searchResults().items; track cardIdentity(item)) { diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index ff59629..160bbbf 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -20,6 +20,8 @@ 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 { TeaResumenPeriodo } from './tea-resumen-periodo'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; +import { IndicadorScreeningRoute } from './indicador-screening-route'; +import { ROUTE_IDS, ROUTE_ONLY_IDS } from './screening-route'; import { IndicadorKpiCard } from './indicador-kpi-card'; import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection'; import { identityElementId, indicatorIdentity } from './indicadores-identities'; @@ -52,7 +54,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', }) @@ -334,6 +336,10 @@ 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)); } // TEA shows a summary paragraph instead of its cards for exactly one explicitly chosen period. @@ -363,8 +369,10 @@ export class IndicadoresPage { // Stable presentation order. Pins no longer reorder the summary. readonly catalogOrder = computed(() => { const catalog = this.catalog(); + // The route chart draws its own measures: they get no card of their own once it is there. + const route = this.screeningRouteAvailable ? ROUTE_ONLY_IDS : []; 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' && !route.includes(item.id))] : this.dominio === 'cama' ? this.cardsDeCama(catalog) : catalog.filter(item => !item.vistas || item.vistas.includes('resumen')); }); diff --git a/src/app/features/indicadores/indicadores-regresion-fhir.spec.ts b/src/app/features/indicadores/indicadores-regresion-fhir.spec.ts index 0d166ab..fd28502 100644 --- a/src/app/features/indicadores/indicadores-regresion-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-regresion-fhir.spec.ts @@ -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)); diff --git a/src/app/features/indicadores/indicadores-screening-route-page.spec.ts b/src/app/features/indicadores/indicadores-screening-route-page.spec.ts new file mode 100644 index 0000000..e80d3a8 --- /dev/null +++ b/src/app/features/indicadores/indicadores-screening-route-page.spec.ts @@ -0,0 +1,57 @@ +// 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 { IndicadoresPage } from './indicadores-page'; +import { IndicadoresMemory } from './indicadores-memory'; +import { Dominio } from './indicadores.models'; +import { 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>, 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 sus medidas exclusivas no tienen tarjeta', () => { + // Pins down: the chart replaces the cards of the five measures only it draws, while the cytology's and the diagnosis' + // keep theirs. Fails if the chart stops appearing, or a measure it draws also shows as a card. + abrir('cacu', [item('cacu_eu7', 'C2'), ...ROUTE_IDS.map(id => item(id))]); + expect(ruta()).not.toBeNull(); + const ids = tarjetas(); + for (const id of ROUTE_ONLY_IDS) expect(ids).not.toContain(id); + expect(ids).toContain('cacu_eu_tiempo_reporte'); + expect(ids).toContain('cacu_eu7'); + }); + 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(); + }); +}); diff --git a/src/app/features/indicadores/indicadores-tiempos-pareados.ts b/src/app/features/indicadores/indicadores-tiempos-pareados.ts index bb2067f..33d187d 100644 --- a/src/app/features/indicadores/indicadores-tiempos-pareados.ts +++ b/src/app/features/indicadores/indicadores-tiempos-pareados.ts @@ -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 | undefined): Caja { +export function caja(fila: Record | undefined): Caja { if (!fila) return { estado: 'No disponible' }; if (fila['suprimido'] === 1) return { estado: 'Suprimido' }; const { n, q1, mediana, q3 } = fila; diff --git a/src/app/features/indicadores/screening-route.spec.ts b/src/app/features/indicadores/screening-route.spec.ts new file mode 100644 index 0000000..090b023 --- /dev/null +++ b/src/app/features/indicadores/screening-route.spec.ts @@ -0,0 +1,124 @@ +// 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 = {}) => + ({ 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[], periodos = ['2025-S1', '2025-S2']): IndicadorDatos => + ({ id, contrato: 'C3r', tipo_periodo: 'semestre', periodos, filas, version: '1' }); +const S2: Record = { + 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 { + 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('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) => ({ ...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; + 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
n = 4,855'); + expect(trace['y']).toHaveLength(4); + expect((f.layout['yaxis'] as Record)['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; + 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
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; + 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']); + }); +}); diff --git a/src/app/features/indicadores/screening-route.ts b/src/app/features/indicadores/screening-route.ts new file mode 100644 index 0000000..d782659 --- /dev/null +++ b/src/app/features/indicadores/screening-route.ts @@ -0,0 +1,130 @@ +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. */ +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 => !!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, tipo: TipoPeriodo, requested?: string): RouteModel { + const boxes: Record> = {}; + 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(); + const period = requested && periods.includes(requested) ? requested : 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}
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}
Mediana: %{customdata[2]} días
Q1 a Q3: %{customdata[1]} a %{customdata[3]} días', + }], 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}
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}
Tramo: %{customdata[2]} días (Q1 a Q3: %{customdata[1]} a %{customdata[3]})
Hasta el día %{customdata[4]}', + }], 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`; +} diff --git a/src/app/governance/api/governance.api.ts b/src/app/governance/api/governance.api.ts index b2c8637..4c539b6 100644 --- a/src/app/governance/api/governance.api.ts +++ b/src/app/governance/api/governance.api.ts @@ -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 { 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); diff --git a/src/app/governance/api/governance.types.ts b/src/app/governance/api/governance.types.ts index d8f4abf..6683796 100644 --- a/src/app/governance/api/governance.types.ts +++ b/src/app/governance/api/governance.types.ts @@ -79,8 +79,20 @@ export interface ExperimentDetail extends Experiment { error: string | null; } +/** A notebook kept in the code (`models///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; diff --git a/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.html b/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.html index a382def..fe64140 100644 --- a/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.html +++ b/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.html @@ -2,19 +2,39 @@

- 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 (models/<dominio>/<escenario>/notebooks/) 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 from models.notebook import experiment 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ó.

-
- - {{ file()?.name ?? 'Ningún archivo (.ipynb)' }} - -
+ + Del código + Subir archivo + + + @if (source() === 'plantilla') { + + Notebook del código + + @for (option of templates(); track option.id) { + {{ templateLabel(option) }} + } + + @if (template(); as chosen) { + Corre para: {{ chosen.scenarios.join(', ') }} + } + + } @else { +
+ + {{ file()?.name ?? 'Ningún archivo (.ipynb)' }} + +
+ }
@@ -31,6 +51,8 @@ @if (scenario() && !scenarioValid()) { Solo letras, números, guion y guion bajo. + } @else if (source() === 'plantilla' && template() && !notebookReady()) { + Esta plantilla no corre para ese escenario. } @else { El de un modelo existente o uno nuevo para el experimento. } diff --git a/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.spec.ts b/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.spec.ts index 90880f1..33c8ae5 100644 --- a/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.spec.ts +++ b/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.spec.ts @@ -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' })); + }); }); diff --git a/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.ts b/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.ts index d894e87..f2043e9 100644 --- a/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.ts +++ b/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.ts @@ -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///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(this.defaults.domain ?? 'cacu'); readonly scenario = signal(this.defaults.scenario ?? ''); readonly version = signal(this.defaults.version ?? ''); + readonly source = signal('plantilla'); readonly file = signal(null); + readonly templates = signal([]); + readonly template = signal(null); readonly builds = signal([]); readonly build = signal(null); readonly versions = signal([]); @@ -57,13 +66,34 @@ export class NotebookRunDialog { readonly error = signal(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);