@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 d832e88..6377ded 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-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`;
+}