47a0ab5f1b
Preserve dev governance and risk-batch UI. Validate cohort navigation, API contracts and shared summary/history measures. Production build passes; 1785 tests pass with the six known Node 26 localStorage failures.
156 lines
12 KiB
TypeScript
156 lines
12 KiB
TypeScript
import { Dominio, filasDelGrupo, 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; singleAppliedPeriod?: boolean;
|
|
// C1 only: replaces the domain's explanatory line when the numerator is not the domain's usual one.
|
|
c1Info?: (numerador: number, denominador: number) => string;
|
|
// C3r only: a median over zero observations is no value, not zero days.
|
|
requiresObservations?: boolean;
|
|
}
|
|
// Same laboratory-result source used by PARES_TIEMPOS; diagnosis has its own ID.
|
|
export const CACU_RESULTADO_KPI: KpiDefinition = {
|
|
id: 'cacu_eu_tiempo_reporte', title: 'Días de toma a resultado', contrato: 'C3r', unit: 'días (mediana)', singleAppliedPeriod: true,
|
|
};
|
|
export const CAMA_TAMIZAJE_RESULTADO_KPI: KpiDefinition = {
|
|
id: 'cama_eu38a', title: 'Tiempo de mastografía a resultado', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true,
|
|
};
|
|
// Institutional definitions retained for consumers outside the opportunity strip.
|
|
export const CAMA_CONFIRMACION_KPI: KpiDefinition = {
|
|
id: 'cama_confirmacion_birads45', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%',
|
|
};
|
|
export const CAMA_TOMA_DIAGNOSTICO_KPI: KpiDefinition = {
|
|
id: 'cama_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)',
|
|
};
|
|
export const CAMA_TASA_DETECCION_KPI: KpiDefinition = {
|
|
id: 'cama_tasa_deteccion_histopatologica', title: 'Tasa de detección histopatológica', contrato: 'C1', unit: '%',
|
|
c1Info: (n, d) => `${n} de ${d} biopsias con resultado maligno.`,
|
|
};
|
|
export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = {
|
|
id: 'cama_dias_resultado_diagnostico', title: 'Tiempo de resultado a diagnóstico', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true,
|
|
};
|
|
// Provisional (oct 2026): titles are copied by hand from the `title` of each indicator's TOML
|
|
// in indicadores_kit, except the C2 patient counts, whose card shows the sum of the categories
|
|
// (patients), not the distribution. If a TOML title changes, change it here too, until the
|
|
// cards read the `titulo` that the API already sends.
|
|
// M28's stages at the period's end: a child finishes the screening with a good EEG; the other stages are in process.
|
|
export const M28_COMPLETO = 'EEG';
|
|
export const M28_EN_PROCESO = ['SOLO_MCHAT', 'PSICOLOGIA', 'NEUROPEDIATRIA'];
|
|
// What only TEA's summary paragraph needs: the children by stage and the time of each screening step.
|
|
export const KPI_RESUMEN_TEA: KpiDefinition[] = [
|
|
{ id: 'M28_casos_por_estado', title: 'Niños en el tamizaje', contrato: 'C2', unit: 'pacientes' },
|
|
{ id: 'M26_dias_mchat_ados2', title: 'Tiempo de M-CHAT a ADOS-2', contrato: 'C3r', unit: 'días (mediana)' },
|
|
{ id: 'M27_dias_ados2_diagnostico', title: 'Tiempo de ADOS-2 a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
|
|
];
|
|
export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
|
|
tea: [
|
|
{ id: 'M23_pacientes_evaluados', title: 'Total de pacientes evaluados', contrato: 'C2', unit: 'pacientes' },
|
|
{ id: 'M24_confirmacion_diagnostico', title: 'Porcentaje de confirmación diagnóstica', contrato: 'C1', unit: '%' },
|
|
{ id: 'M25_dias_mchat_diagnostico', title: 'Tiempo de aplicación de M-CHAT (psicología) a diagnóstico positivo', contrato: 'C3r', unit: 'días (mediana)' },
|
|
{ id: 'M21_diagnosticados_con_eeg', title: 'Porcentaje de pacientes con diagnóstico de TEA con EEG', contrato: 'C1', unit: '%',
|
|
c1Info: (n, d) => `${n} de ${d} pacientes con diagnóstico confirmado tienen un EEG de buena calidad.` },
|
|
{ id: 'M22_diagnosticados_sin_eeg', title: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG', contrato: 'C1', unit: '%',
|
|
c1Info: (n, d) => `${n} de ${d} pacientes con diagnóstico confirmado no tienen todavía un EEG de buena calidad.` },
|
|
],
|
|
cacu: [
|
|
{ id: 'cacu_eu7', title: 'Pacientes evaluadas', contrato: 'C2', unit: 'pacientes' },
|
|
{ id: 'cacu_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
|
|
],
|
|
cama: [
|
|
{ id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 y 6', contrato: 'C2', unit: 'pacientes' },
|
|
CAMA_TAMIZAJE_RESULTADO_KPI,
|
|
],
|
|
};
|
|
|
|
// CaMa's four opportunity cards, in display order. Two of them have no measure in the FHIR catalog yet
|
|
// (`cama_tasa_deteccion_histopatologica` and `cama_dias_resultado_diagnostico`), so they stay outside
|
|
// KPI_BY_DOMAIN: they are queried only once the catalog publishes them.
|
|
export const CAMA_OPORTUNIDAD_KPIS: KpiDefinition[] = [
|
|
KPI_BY_DOMAIN.cama[0],
|
|
CAMA_TASA_DETECCION_KPI,
|
|
CAMA_TAMIZAJE_RESULTADO_KPI,
|
|
CAMA_RESULTADO_DIAGNOSTICO_KPI,
|
|
];
|
|
export interface KpiCardSlot { definition: KpiDefinition; pending: boolean; }
|
|
// The four opportunity cards, each pending while its indicator is not in the catalog. Nothing at all
|
|
// (not even pending cards) until the catalog publishes one of them.
|
|
export function camaKpiCards(published: (id: string) => boolean): KpiCardSlot[] {
|
|
const cards = CAMA_OPORTUNIDAD_KPIS.map(definition => ({ definition, pending: !published(definition.id) }));
|
|
return cards.some(card => !card.pending) ? cards : [];
|
|
}
|
|
// Published CaMa indicators whose card the summary does not draw.
|
|
// The summary draws the paired card and the histopathology card; the rest of CaMa's indicators are in Histórico
|
|
// and in Datos y definiciones, which still list the whole catalog.
|
|
// The two published opportunity indicators draw their KPI card only; their evolution is in Histórico.
|
|
// `cama_birads` is replaced by the exams' and patients' counts, and `cama_birads_cancer_invasor` is the
|
|
// epidemiological analysis' measure: neither has a card of its own.
|
|
export const CAMA_FUERA_DEL_RESUMEN: readonly string[] = ['cama_biopsias', 'cama_birads', 'cama_birads_cancer_invasor',
|
|
'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_tasa_deteccion_histopatologica',
|
|
'cama_dias_resultado_diagnostico'];
|
|
export const ID_HISTOPATOLOGIA_CAMA = 'cama_histopatologia_birads';
|
|
// C1 rows of CaCu/CaMa carry the linkId `total`; TEA's ficha names its single group `TOTAL`.
|
|
const C1_GROUP: Record<Dominio, string> = { tea: 'TOTAL', cacu: 'total', cama: 'total' };
|
|
const C1_INFO: Record<Dominio, (numerador: number, denominador: number) => string> = {
|
|
tea: (n, d) => `${n} de ${d} pacientes con nota médica con diagnóstico CIE-10 F84.0.`,
|
|
cacu: (n, d) => `${n} de ${d} pacientes con lesión de alto grado o mayor en biopsia.`,
|
|
cama: (n, d) => `${n} de ${d} mastografías BI-RADS 4 y 5 con reporte de biopsia.`,
|
|
};
|
|
const C3R_INFO: Record<Dominio, (n: number, q1: number, q3: number) => string> = {
|
|
tea: (n, q1, q3) => `${n} pacientes; Q1 a Q3: ${q1} a ${q3} días.`,
|
|
cacu: (n, q1, q3) => `${n} citologías; primer cuartil: ${q1} días; tercer cuartil: ${q3} días.`,
|
|
cama: (n, q1, q3) => `${n} mastografías; Q1 a Q3: ${q1} a ${q3} días.`,
|
|
};
|
|
export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; categorias?: Record<string, number>; }
|
|
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
|
const count = (v: unknown): v is number => finite(v) && Number.isSafeInteger(v) && v >= 0;
|
|
const unscoped = { state: 'Selección no consolidable', info: 'Elige un único periodo. No hay una regla aprobada para consolidar periodos, grupos o estratos.' };
|
|
|
|
// C2 definitions count each patient once per period, in disjoint categories of TOTAL.
|
|
// C1/C3r publish a single total row. Never combine totals, strata, or periods.
|
|
export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domain: Dominio, applied: GlobalApplied): KpiResult {
|
|
if (definition.singleAppliedPeriod && (applied.selection.mode !== 'explicit' || applied.selection.periodos.length !== 1)) return unscoped;
|
|
if (data.id !== definition.id || data.contrato !== definition.contrato || data.tipo_periodo !== applied.tipo) {
|
|
return { state: 'Error de contrato', info: 'Los datos recibidos no corresponden al indicador o periodo aplicado.' };
|
|
}
|
|
if (!data.periodos.length && !data.filas.length) return { state: 'Sin filas utilizables' };
|
|
if (data.periodos.length !== 1 || new Set(data.filas.map(row => row['periodo'])).size > 1) return unscoped;
|
|
const period = data.periodos[0];
|
|
if (applied.selection.mode === 'explicit' && (applied.selection.periodos.length !== 1 || applied.selection.periodos[0] !== period)) return unscoped;
|
|
const group = definition.contrato === 'C1' ? C1_GROUP[domain] : 'TOTAL';
|
|
const rows = definition.contrato === 'C1' ? filasDelGrupo(data, group) : data.filas;
|
|
if (!rows.length) return { state: 'Sin filas utilizables' };
|
|
if (rows.some(row => row['periodo'] !== period || row['grupo'] !== group || row['estrato'] != null)) return unscoped;
|
|
if (definition.contrato !== 'C2' && rows.length !== 1) return unscoped;
|
|
if (rows.some(row => finite(row['suprimido']) && row['suprimido'] !== 0)) return { state: 'Dato oculto por tamaño' };
|
|
if (rows.some(row => row['suprimido'] !== 0)) return { state: 'Sin filas utilizables', info: 'No se puede determinar el estado de supresión.' };
|
|
const empty = { state: 'Sin valor disponible' };
|
|
const row = rows[0];
|
|
if (definition.contrato === 'C2') {
|
|
const categories = rows.map(row => row['categoria']);
|
|
if (categories.some(c => typeof c !== 'string' || !c) || new Set(categories).size !== categories.length) return unscoped;
|
|
const catalog = data['categorias'];
|
|
if (!catalog || typeof catalog !== 'object' || Array.isArray(catalog)) return { state: 'Error de contrato', info: 'Falta el catálogo de categorías para verificar el total.' };
|
|
const expected = Object.keys(catalog);
|
|
if (expected.length !== categories.length || expected.some(c => !categories.includes(c))) return { state: 'Sin filas utilizables', info: 'Las categorías recibidas no permiten verificar un total completo.' };
|
|
if (!rows.every(row => count(row['n']))) return empty;
|
|
const value = rows.reduce((sum, row) => sum + (row['n'] as number), 0);
|
|
if (!count(value)) return empty;
|
|
return { state: 'Disponible', value, categorias: Object.fromEntries(rows.map(row => [row['categoria'] as string, row['n'] as number])),
|
|
info: domain === 'cacu' ? 'Pacientes con citología tomada en el periodo.'
|
|
: domain === 'cama' ? 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.' : 'Conteo de pacientes únicos en el periodo.' };
|
|
}
|
|
if (definition.contrato === 'C1') {
|
|
if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100) return empty;
|
|
const numerator = row['numerador'], denominator = row['denominador'];
|
|
if (numerator == null || denominator == null) return empty;
|
|
if (!count(numerator) || !count(denominator) || numerator > denominator) {
|
|
return { state: 'Error de contrato', info: 'El numerador y el denominador deben ser conteos no negativos compatibles.' };
|
|
}
|
|
if (denominator === 0) return empty;
|
|
return { state: 'Disponible', value: percentNumber(row['valor']), info: (definition.c1Info ?? C1_INFO[domain])(numerator, denominator) };
|
|
}
|
|
if (!finite(row['mediana']) || !count(row['n']) || ((definition.id === CACU_RESULTADO_KPI.id || definition.requiresObservations) && row['n'] === 0) || !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']) };
|
|
}
|