diff --git a/src/app/features/indicadores/cacu-seguimiento.spec.ts b/src/app/features/indicadores/cacu-seguimiento.spec.ts index f4650bb..8604caf 100644 --- a/src/app/features/indicadores/cacu-seguimiento.spec.ts +++ b/src/app/features/indicadores/cacu-seguimiento.spec.ts @@ -39,6 +39,9 @@ describe('Seguimiento CaCu con contrato de demostración', () => { expect(root.textContent).not.toContain('Las reglas de selección son provisionales'); expect(root.textContent).toContain('Ventana consultada:'); expect(root.textContent).toContain('INSATISFACTORIO'); expect(root.textContent).toContain('Normal'); expect(root.textContent).toContain('No detectado'); + expect(root.textContent).toContain('Insatisfactoria'); + expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: 'SATISFACTORIO' })).toBe('Sin resultado al corte'); + expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: null })).toBe('Sin resultado al corte'); expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(8); expect(root.querySelector('form input[name="corte"]')).not.toBeNull(); expect(root.querySelector('form select[name="meses"]')).not.toBeNull(); diff --git a/src/app/features/indicadores/indicador-eu7-escenario.ts b/src/app/features/indicadores/indicador-eu7-escenario.ts index 0b38357..b6be0ba 100644 --- a/src/app/features/indicadores/indicador-eu7-escenario.ts +++ b/src/app/features/indicadores/indicador-eu7-escenario.ts @@ -8,6 +8,7 @@ import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './in import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory'; import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; import { httpMessage } from './indicadores-http'; +import { percentText } from './indicadores-format'; import { stratifiedCapabilities } from './indicadores-stratified'; import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje, periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario'; @@ -64,7 +65,7 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy { { escenario: s.etiqueta, categoria: m.sinDatoEtiqueta, celda: s.celdas['SIN_DATO'], den: null, pct: null }]); } cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); } - percentText(value: number | null) { return value === null ? 'No disponible' : value.toFixed(1) + ' %'; } + percentText(value: number | null) { return percentText(value); } toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); } ngOnChanges(changes: SimpleChanges) { diff --git a/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts b/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts index 49b17da..fd35bd1 100644 --- a/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts +++ b/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts @@ -1,6 +1,7 @@ import fixture from './fixtures/eu7-c2-ejemplos.json'; import { IndicadorDatos } from './indicadores.models'; import { barras, clic, dona, modelo, porcentaje, periodosCompatibles, Seleccion } from './indicadores-eu7-escenario'; +import { percentNumber } from './indicadores-format'; function eu7Datos() { return structuredClone({ general: fixture.general as IndicadorDatos, escenarios: fixture.estatus_seguimiento as IndicadorDatos }); @@ -44,7 +45,7 @@ describe('EU7 modelo de presentación del entregable', () => { expect(category.data).toHaveLength(1); expect(category.data[0]['x']).toEqual(m.escenarios.map(s => 100 * s.celdas['LIEAG'].n! / s.den!)); expect((category.layout['annotations'] as { text: string }[]).map(a => a.text)) - .toEqual(m.escenarios.map(s => `${(100 * s.celdas['LIEAG'].n! / s.den!).toFixed(1)} % (${s.celdas['LIEAG'].n}/${s.den})`)); + .toEqual(m.escenarios.map(s => `${percentNumber(100 * s.celdas['LIEAG'].n! / s.den!)} % (${s.celdas['LIEAG'].n}/${s.den})`)); expect(m.escenarios.map(s => s.den)).toEqual([682, 140, 60, 64]); }); it.each(['estrato', 'categorias', 'periodos', 'orden', 'duplicado', 'version', 'filtros', 'total', 'diferencia'])('rechaza incompatibilidad de %s', kind => { diff --git a/src/app/features/indicadores/indicadores-eu7-escenario.ts b/src/app/features/indicadores/indicadores-eu7-escenario.ts index 3e8c505..04eaaa5 100644 --- a/src/app/features/indicadores/indicadores-eu7-escenario.ts +++ b/src/app/features/indicadores/indicadores-eu7-escenario.ts @@ -1,5 +1,6 @@ import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; import { c2Theme } from './indicadores-c2-palette'; +import { percentNumber, shareText } from './indicadores-format'; // Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts. // This boundary is intentionally specific to EU7. Unknown cells never become zero. @@ -189,12 +190,12 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure { const centro = sel.categoria ? m.celdas[sel.categoria].n! : sel.grupo ? nGrupo(m, sel.grupo)! : m.total; const rotulos = (values: number[], labels: string[], pct: boolean) => { const total = values.reduce((s, n) => s + n, 0); - return values.map((v, i) => !total || v / total < .05 ? '' : escapar(labels[i]) + (pct ? `
${(100 * v / total).toFixed(0)} %` : '')); + return values.map((v, i) => !total || v / total < .05 ? '' : escapar(labels[i]) + (pct ? `
${shareText(v, total)}` : '')); }; const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, textinfo: 'text', insidetextorientation: 'horizontal', showlegend: false, textposition: 'inside' }; const hover = { hovertemplate: '%{label}
%{customdata[0]} pacientes · %{customdata[1]} % del total con resultado' }; - const custom = (values: number[]) => values.map(n => [miles(n), (100 * n / m.total!).toFixed(1)]); + const custom = (values: number[]) => values.map(n => [miles(n), percentNumber(100 * n / m.total!)]); return { data: [ { ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, text: [`${miles(centro)}
${escapar(seleccionEtiqueta(m, sel))}`], textfont: { size: 18, color: p.text }, @@ -220,7 +221,7 @@ export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure { const x = m.escenarios.map(s => porcentaje(s, c.id)); return { type: 'bar', orientation: 'h', name: escapar(c.etiqueta), y, x, marker: { color: c.color, line: { color: p.background, width: 1 } }, - text: x.map(v => v !== null && v >= 6 ? `${v.toFixed(0)} %` : ''), textposition: 'inside', insidetextanchor: 'middle', + text: x.map(v => v !== null && v >= 6 ? `${percentNumber(v)} %` : ''), textposition: 'inside', insidetextanchor: 'middle', customdata: m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]), hovertemplate: `%{y}
${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})` }; }), layout: { barmode: 'stack', autosize: true, height: Math.max(440, 130 + m.escenarios.length * 65), @@ -232,7 +233,7 @@ export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure { tickvals: sel.grupo || sel.categoria ? undefined : [0, 20, 40, 60, 80, 100] }, annotations: m.escenarios.map((s, i) => ({ y: y[i], x: sumas[i] ?? 0, xanchor: 'left', xshift: 6, showarrow: false, font: { size: 12, color: p.text }, text: s.den === null ? s.estado : s.den === 0 ? 'Sin pacientes con resultado' - : sel.grupo || sel.categoria ? `${sumas[i]!.toFixed(1)} % (${visibles.reduce((n, c) => n + s.celdas[c].n!, 0)}/${miles(s.den)})` + : sel.grupo || sel.categoria ? `${percentNumber(sumas[i]!)} % (${visibles.reduce((n, c) => n + s.celdas[c].n!, 0)}/${miles(s.den)})` : miles(s.den) })), }, config: { displayModeBar: false } }; } diff --git a/src/app/features/indicadores/indicadores-format.spec.ts b/src/app/features/indicadores/indicadores-format.spec.ts new file mode 100644 index 0000000..c904b7a --- /dev/null +++ b/src/app/features/indicadores/indicadores-format.spec.ts @@ -0,0 +1,24 @@ +import { percentNumber, percentText, roundPercent, sharePercent, shareText } from './indicadores-format'; + +describe('regla de redondeo de porcentajes', () => { + it('una décima, medio hacia arriba, calculada con enteros', () => { + expect(sharePercent(2, 303)).toBe(0.7); + expect(sharePercent(1, 8)).toBe(12.5); + expect(sharePercent(1, 3)).toBe(33.3); + expect(sharePercent(2, 3)).toBe(66.7); + expect(shareText(0, 9)).toBe('0.0 %'); + expect(shareText(5, 5)).toBe('100.0 %'); + }); + it('entre 0 y 0.1, la primera cifra significativa', () => { + expect(shareText(1, 2000)).toBe('0.05 %'); + expect(shareText(1, 1600)).toBe('0.06 %'); + expect(percentText(0.0432)).toBe('0.04 %'); + }); + it('un porcentaje publicado redondea igual, sin sorpresas de coma flotante', () => { + expect(roundPercent(0.6600660066)).toBe(0.7); + expect(roundPercent(12.25)).toBe(12.3); + expect(roundPercent(1.005 * 10)).toBe(10.1); + expect(percentNumber(100)).toBe('100.0'); + expect(percentText(null)).toBe('No disponible'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-format.ts b/src/app/features/indicadores/indicadores-format.ts new file mode 100644 index 0000000..dbd30ef --- /dev/null +++ b/src/app/features/indicadores/indicadores-format.ts @@ -0,0 +1,33 @@ +// One rounding rule for every percentage shown: one decimal, half up; between 0 and 0.1 +// the first significant digit (0.04 %, not 0.0 %). Integer counts round exactly, without +// binary floating-point surprises (1.005 → 1.0 with toFixed). + +/** The percentage of `k` in `n`, rounded by the rule, computed from integers. */ +export function sharePercent(k: number, n: number): number { + if (k > 0 && 1000 * k < n) return Number((100 * k / n).toPrecision(1)); + return Math.floor((2000 * k + n) / (2 * n)) / 10; +} + +/** A published percentage (0 to 100), rounded by the rule. */ +export function roundPercent(value: number): number { + if (value > 0 && value < 0.1) return Number(value.toPrecision(1)); + // Snap to 9 decimals first so 12.25 published as 12.2499999999 still rounds up. + return Math.floor(Math.round(value * 1e9) / 1e8 + 0.5) / 10; +} + +/** Text of a rounded percentage: «12.3», «0.04», «100.0». */ +export function percentNumber(value: number): string { + const rounded = roundPercent(value); + return rounded > 0 && rounded < 0.1 ? String(rounded) : rounded.toFixed(1); +} + +/** «12.3 %» from a published percentage, or the fallback when there is none. */ +export function percentText(value: number | null | undefined, fallback = 'No disponible'): string { + return typeof value === 'number' && Number.isFinite(value) ? `${percentNumber(value)} %` : fallback; +} + +/** «12.3 %» from a count over its denominator. */ +export function shareText(k: number, n: number): string { + const value = sharePercent(k, n); + return `${value > 0 && value < 0.1 ? String(value) : value.toFixed(1)} %`; +} diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index 12f08c4..3c93d98 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -1,5 +1,6 @@ import { Dominio, IndicadorDatos } from './indicadores.models'; import { GlobalApplied } from './indicadores-memory'; +import { percentNumber } from './indicadores-format'; export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; } // Provisional (oct 2026): titles are copied by hand from the `title` of each indicator's TOML @@ -72,7 +73,7 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai } if (definition.contrato === 'C1') { if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100 || !count(row['numerador']) || !count(row['denominador']) || row['numerador'] > row['denominador']) return empty; - return { state: 'Disponible', value: row['valor'].toFixed(1), info: C1_INFO[domain](row['numerador'], row['denominador']) }; + return { state: 'Disponible', value: percentNumber(row['valor']), info: C1_INFO[domain](row['numerador'], row['denominador']) }; } if (!finite(row['mediana']) || !count(row['n']) || !finite(row['q1']) || !finite(row['q3']) || row['q1'] < 0 || row['q1'] > row['mediana'] || row['mediana'] > row['q3'] || row['unidad'] !== 'dias') return empty; return { state: 'Disponible', value: row['mediana'], info: C3R_INFO[domain](row['n'], row['q1'], row['q3']) }; diff --git a/src/app/features/indicadores/indicadores-numeric-rows.ts b/src/app/features/indicadores/indicadores-numeric-rows.ts index 94cfd39..8e83824 100644 --- a/src/app/features/indicadores/indicadores-numeric-rows.ts +++ b/src/app/features/indicadores/indicadores-numeric-rows.ts @@ -1,4 +1,5 @@ import { IndicadorDatos } from './indicadores.models'; +import { percentText } from './indicadores-format'; export interface NumericRow { period: string; group: string; category: string; value: string; detail: string; state: string; } const record = (value: unknown): value is Record => value !== null && typeof value === 'object' && !Array.isArray(value); @@ -6,6 +7,9 @@ function number(value: unknown, suffix = ''): string { if (value === null) return 'Sin valor (nulo)'; return typeof value === 'number' && Number.isFinite(value) ? `${value}${suffix}` : 'No disponible'; } +function percent(value: unknown): string { + return typeof value === 'number' ? percentText(value) : number(value); +} function label(dictionary: unknown, key: unknown, fallback: string): string { const entry = record(dictionary) && typeof key === 'string' ? dictionary[key] : undefined; return typeof entry === 'string' ? entry : record(entry) && typeof entry['etiqueta'] === 'string' ? entry['etiqueta'] : fallback; @@ -27,8 +31,8 @@ export function numericRows(data: IndicadorDatos): NumericRow[] { let primary: unknown; if (data.contrato === 'C1') { primary = row['valor']; - return { ...base, value: number(primary, ' %'), state: typeof primary === 'number' && Number.isFinite(primary) ? 'Disponible' : 'Sin valor disponible', - detail: `Intervalo publicado: ${number(row['ic_bajo'])} a ${number(row['ic_alto'])} %. Numerador: ${number(row['numerador'])}; denominador: ${number(row['denominador'])}.` }; + return { ...base, value: percent(primary), state: typeof primary === 'number' && Number.isFinite(primary) ? 'Disponible' : 'Sin valor disponible', + detail: `Intervalo publicado: ${percent(row['ic_bajo'])} a ${percent(row['ic_alto'])}. Numerador: ${number(row['numerador'])}; denominador: ${number(row['denominador'])}.` }; } if (data.contrato === 'C2') { primary = row['n']; diff --git a/src/app/features/indicadores/indicadores-numeric-summary.spec.ts b/src/app/features/indicadores/indicadores-numeric-summary.spec.ts index da4f8b6..e5fd277 100644 --- a/src/app/features/indicadores/indicadores-numeric-summary.spec.ts +++ b/src/app/features/indicadores/indicadores-numeric-summary.spec.ts @@ -37,8 +37,8 @@ describe('MD-19 lecturas y celdas numéricas', () => { }); it('C1 conserva cero, intervalo publicado y poblaciones sin recalcular Wilson', () => { const row = numericRows(data('C1'))[0]; - expect(row.value).toBe('0 %'); expect(row.state).toBe('Disponible'); - expect(row.detail).toBe('Intervalo publicado: 0 a 16.1 %. Numerador: 0; denominador: 20.'); + expect(row.value).toBe('0.0 %'); expect(row.state).toBe('Disponible'); + expect(row.detail).toBe('Intervalo publicado: 0.0 % a 16.1 %. Numerador: 0; denominador: 20.'); }); it('C2 conserva categorías, grupos y conteos; no suma poblaciones superpuestas', () => { const sample = data(); sample['grupos'] = { other: 'Otra población' }; sample.filas.push({ ...sample.filas[0], grupo: 'other', n: 11 }); diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html index d85ef6a..2eded43 100644 --- a/src/app/features/indicadores/indicadores-tracking.html +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -37,7 +37,7 @@ @for (item of response.items; track item.id_seudonimo) { {{ item.id_seudonimo }}{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}{{ item.estatus.etiqueta }} - @if (item.ultima_citologia; as c) { {{ cytologyLabel(c.bethesda) }}Fecha: {{ c.fecha }}Calidad: {{ c.calidad ?? '—' }} } @else { No disponible } + @if (item.ultima_citologia; as c) { {{ cytologyLabel(c) }}Fecha: {{ c.fecha }}Calidad: {{ c.calidad ?? '—' }} } @else { No disponible } @if (item.ultimo_vph; as v) { {{ v.resultado }}Fecha: {{ v.fecha }}Genotipo 16/18: {{ v.genotipo_16_18 === null ? 'No disponible' : v.genotipo_16_18 ? 'Presente' : 'No detectado' }} } @else { No disponible } {{ latestStudy(item) ?? 'No disponible' }}{{ item.dias_toma_diagnostico ?? 'No disponible' }}{{ item.prioridad?.etiqueta ?? 'No disponible' }} diff --git a/src/app/features/indicadores/indicadores-tracking.ts b/src/app/features/indicadores/indicadores-tracking.ts index b0dba78..f0115e8 100644 --- a/src/app/features/indicadores/indicadores-tracking.ts +++ b/src/app/features/indicadores/indicadores-tracking.ts @@ -77,5 +77,10 @@ export class IndicadoresTracking implements OnChanges { if (!this.data || page < 1 || page > this.data.paginacion.total_pages) return; this.load({ ...this.applied, page }); } - cytologyLabel(code: string | null) { return code === null ? 'No disponible' : this.categories[code]?.etiqueta ?? code; } + // The shown cytology is the patient's latest in the window. Without a Bethesda result it is either + // unsatisfactory (`cacu.calidad_insatisfactoria` in the kit) or not yet reported at the cut-off. + cytologyLabel(c: { bethesda: string | null; calidad: string | null }) { + if (c.bethesda !== null) return this.categories[c.bethesda]?.etiqueta ?? c.bethesda; + return c.calidad?.trim().toUpperCase() === 'INSATISFACTORIO' ? 'Insatisfactoria' : 'Sin resultado al corte'; + } }