File size: 10,656 Bytes
70e641d
 
 
 
 
 
 
 
c0b119e
70e641d
 
 
 
 
5b69117
70e641d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b69117
 
 
 
70e641d
c205c6b
70e641d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b69117
 
 
 
 
 
 
 
 
 
70e641d
 
 
 
5b69117
70e641d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b69117
 
 
 
70e641d
 
 
 
 
 
5b69117
70e641d
c205c6b
 
 
 
 
70e641d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ab7946
c0b119e
70e641d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0b119e
 
c205c6b
c0b119e
70e641d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
// Orquestación de la app. Puerto TS de js/main.js, adaptado a la nueva capa de IA
// (llamarIA envía hallazgos/patrones + imágenes al backend /api/interpret).

import './tooltip.js';
import { analizarResultados } from './analisis.js';
import { colapsarPatrones, inicializarSincMob, imagenesDataUrl, capturasMicroscopio } from './ui.js';
import { llamarIA, inicializarConfigBackend } from './ia.js';
import { inicializarParserPdf } from './pdf-parser.js';
import { inicializarPanelesVacios } from './panel-vacio.js';
import { inicializarImportLab } from './lab-import.js';
import { verificarAuth, abrirModalAuth } from './auth.js';
import { abrirModalPapers, inicializarModalPapers } from './papers.js';
import { elId } from './dom.js';
import { manejadorAsync, sinEsperar } from './async.js';
import type { AjustesClinicos, Alteraciones, Gravedad, Hallazgo, Paciente, Referencias, ResultadoAnalisis, ValoresFormulario } from './tipos.js';

// Tema oscuro/claro

const temaGuardado = localStorage.getItem('mx-theme');
const temaPreferido = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
document.documentElement.dataset.theme = temaGuardado || temaPreferido;

const btnTema = document.getElementById('btn-tema');
if (btnTema) {
  btnTema.addEventListener('click', () => {
    const siguienteTema = document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
    document.documentElement.dataset.theme = siguienteTema;
    localStorage.setItem('mx-theme', siguienteTema);
  });
}

// Data

let referencias: Referencias = {};
let alteraciones: Alteraciones = {};
// Reglas clínicas compartidas con el motor del servidor. Se cargan como los demás datos y NO se
// empaquetan en el bundle: si se inlinearan, editar el JSON no tendría efecto sin recompilar, y
// el objetivo es justo que un veterinario pueda ajustar un umbral sin pasar por un build.
let ajustes: AjustesClinicos | null = null;
let ultimoAnalisis: ResultadoAnalisis = { hallazgos: [], patrones: [] };
let ultimosValores: ValoresFormulario = {};

const cargarReferencias = async (): Promise<void> => {
  try {
    const response = await fetch('data/valores_referencia.json');
    if (!response.ok) throw new Error(`Error HTTP: ${response.status}`);
    referencias = await response.json();
  } catch (error) {
    console.error('Error cargando valores de referencia:', error);
  }
};

const cargarAlteraciones = async (): Promise<void> => {
  try {
    const response = await fetch('data/alteraciones.json');
    if (!response.ok) throw new Error(`Error HTTP: ${response.status}`);
    alteraciones = await response.json();
  } catch (error) {
    console.error('Error cargando alteraciones:', error);
  }
};

const cargarAjustes = async (): Promise<void> => {
  try {
    const response = await fetch('data/ajustes_clinicos.json');
    if (!response.ok) throw new Error(`Error HTTP: ${response.status}`);
    ajustes = await response.json();
  } catch (error) {
    console.error('Error cargando ajustes clínicos:', error);
  }
};

// Precargas de arranque: nada que esperar aquí, pero un fallo no puede quedar en silencio
// (sin rangos de referencia el motor no puede clasificar nada).
sinEsperar('Carga de rangos de referencia', cargarReferencias());
sinEsperar('Carga de alteraciones', cargarAlteraciones());
sinEsperar('Carga de ajustes clínicos', cargarAjustes());

// Colección de datos de formulario

const obtenerDatosPaciente = (): Paciente => {
  const especieCruda = (document.getElementById('pt-especie') as HTMLSelectElement).value;
  const valorEdad = (document.getElementById('pt-edad') as HTMLInputElement).value;
  const edadUnidad = (document.getElementById('pt-edad-unidad') as HTMLSelectElement).value;
  // Normaliza la edad siempre a meses para que analisis.ts aplique ajustes por edad
  const edadMeses = valorEdad === '' ? null
    : edadUnidad === 'meses' ? parseFloat(valorEdad)
      : parseFloat(valorEdad) * 12;
  return {
    especie: especieCruda === 'Canino' ? 'canino' : especieCruda === 'Felino' ? 'felino' : null,
    raza: (document.getElementById('pt-raza') as HTMLInputElement).value,
    edadMeses,
    sexo: (document.getElementById('pt-sexo') as HTMLSelectElement).value,
  };
};

const obtenerValoresFormulario = (): Record<string, number> => {
  const valores: Record<string, number> = {};
  document.querySelectorAll<HTMLInputElement>('input[type="number"]').forEach((input) => {
    if (input.name && input.value !== '') valores[input.name] = parseFloat(input.value);
  });
  return valores;
};

// Renderizado

const ETIQUETA_GRAVEDAD: Record<Gravedad, string> = { leve: 'Leve', moderado: 'Moderado', grave: 'Grave' };

document.querySelectorAll<HTMLInputElement>('.fila-campo input[type="number"]').forEach((input) => {
  const span = document.createElement('span');
  span.className = 'estado-campo';
  input.before(span);
});

const actualizarClasesInputs = (hallazgos: Hallazgo[]): void => {
  document.querySelectorAll<HTMLInputElement>('input[type="number"]').forEach((input) => {
    input.classList.remove('alto', 'bajo');
    const span = input.previousElementSibling;
    if (span?.classList.contains('estado-campo')) {
      span.textContent = '';
      span.className = 'estado-campo';
    }
  });
  hallazgos.forEach((h) => {
    const input = document.querySelector<HTMLInputElement>(`input[name="${h.clave}"]`);
    if (!input) return;
    input.classList.add(h.direccion);
    const span = input.previousElementSibling;
    if (span?.classList.contains('estado-campo')) {
      span.textContent = `${h.direccion === 'alto' ? 'Alto' : 'Bajo'} · ${ETIQUETA_GRAVEDAD[h.gravedad]}`;
      span.className = `estado-campo estado-campo--${h.direccion}`;
    }
  });
};

const renderizarPatrones = (patrones: ResultadoAnalisis['patrones']): void => {
  const contenedor = document.getElementById('patrones-lista');
  if (!contenedor) return;

  contenedor.innerHTML = patrones.length === 0
    ? '<p class="sin-hallazgos">Sin patrones detectados.</p>'
    : patrones.map((p) => `
      <div class="elemento-patron gravedad-${p.gravedad}">
        <div class="titulo-patron">${p.nombre}</div>
        <div class="cuerpo-patron">${p.descripcion}</div>
      </div>`).join('');
};

// Evaluación

const evaluar = (): void => {
  const paciente = obtenerDatosPaciente();

  // Si no hay especie o aun no cargaron los datos, limpia la UI para evitar falsos positivos.
  // Sin `ajustes` no se evalúa: hacerlo con los rangos SIN ajustar sacaría hiperfosforémico a
  // todo cachorro e hipotiroideo a todo galgo, que es justo lo que esos factores evitan.
  if (!paciente.especie || !referencias[paciente.especie] || !ajustes) {
    actualizarClasesInputs([]);
    renderizarPatrones([]);
    return;
  }

  const valores = obtenerValoresFormulario();
  const { hallazgos, patrones } = analizarResultados(valores, paciente, referencias, alteraciones, ajustes);
  ultimoAnalisis = { hallazgos, patrones };
  // Los valores crudos van aparte y NO dentro de ResultadoAnalisis: eso es la salida del motor,
  // que sólo devuelve lo alterado. Aquí interesa el panel completo, incluidos los que salieron
  // en rango. El backend los recalcula por su cuenta (§1.1): lo que manda este cliente es una
  // PISTA, y el suelo de seguridad ya no depende de que sea correcta.
  ultimosValores = valores;

  actualizarClasesInputs(hallazgos);
  renderizarPatrones(patrones);
};

// Eventos

document.addEventListener('input', (e) => {
  const target = e.target as HTMLInputElement;
  if (target.type !== 'number') return;
  // Impide valores por debajo del mínimo del campo; permite negativos cuando min lo indica
  const minPermitido = target.min !== '' ? parseFloat(target.min) : 0;
  if (parseFloat(target.value) < minPermitido) target.value = String(minPermitido);
  if (target.value.replace('.', '').length > 4) target.value = target.value.slice(0, 4);
  target.classList.toggle('max-chars', target.value.replace('.', '').length >= 4);
  evaluar();
});

elId<HTMLSelectElement>('pt-especie').addEventListener('change', evaluar);
elId<HTMLInputElement>('pt-raza').addEventListener('input', evaluar);
elId<HTMLInputElement>('pt-edad').addEventListener('input', evaluar);
elId<HTMLSelectElement>('pt-edad-unidad').addEventListener('change', evaluar);
elId<HTMLSelectElement>('pt-sexo').addEventListener('change', evaluar);

inicializarSincMob(evaluar);
void inicializarConfigBackend();  // pide la lista de modelos al servidor; no bloquea el arranque
inicializarPanelesVacios();
inicializarParserPdf(evaluar);
inicializarImportLab(evaluar);
inicializarModalPapers();

document.addEventListener('click', (e) => {
  const btn = (e.target as Element).closest<HTMLElement>('.btn-limpiar-panel');
  if (!btn) return;
  const panel = document.getElementById(`panel-${btn.dataset.panel}`);
  if (!panel) return;
  // Recorre todos los campos editables del panel y los resetea, incluyendo indicadores de estado
  panel.querySelectorAll<HTMLInputElement | HTMLSelectElement>('input[type="number"], input[type="text"], input[type="url"], select').forEach((el) => {
    if (el.tagName === 'SELECT') {
      (el as HTMLSelectElement).selectedIndex = 0;
    } else {
      el.value = '';
      el.classList.remove('alto', 'bajo', 'max-chars');
      const span = el.previousElementSibling;
      if (span?.classList.contains('estado-campo')) {
        span.textContent = '';
        span.className = 'estado-campo';
      }
    }
  });
  evaluar();
});

const imagenesActuales = (): string[] =>
  [...imagenesDataUrl.filter((x): x is string => Boolean(x)), ...capturasMicroscopio];

const dispararIA = (): void => {
  colapsarPatrones(true);
  // Se encola desde un callback síncrono (abrirModalAuth), así que no se puede await aquí.
  sinEsperar(
    'Análisis IA',
    llamarIA(obtenerDatosPaciente, () => ({ ...ultimoAnalisis, valores: ultimosValores }), imagenesActuales),
  );
};

const botonAnalizar = document.querySelector<HTMLElement>('.boton-analizar');
botonAnalizar?.addEventListener('click', manejadorAsync('Análisis IA', async () => {
  // Si el usuario no esta logueado, abre el modal de auth y encola la llamada a IA como callback
  const autenticado = await verificarAuth();
  if (!autenticado) {
    abrirModalAuth(dispararIA);
    return;
  }
  dispararIA();
}));

const botonPapers = document.querySelector<HTMLElement>('.boton-papers');
botonPapers?.addEventListener('click', () => {
  sinEsperar('Literatura', abrirModalPapers(ultimoAnalisis.patrones));
});

// obtenerValoresFormulario se conserva para depuración/consumidores futuros del formulario.
void obtenerValoresFormulario;