File size: 4,531 Bytes
3ce36cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b66255
 
3ce36cf
 
 
 
 
 
 
 
 
 
 
 
 
 
4b66255
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
/**
 * api.js — Capa de comunicación con el backend Flask
 * Reemplaza todas las llamadas eel.función() del frontend original.
 */

const api = (() => {
  const BASE = '';

  // Páginas que NO deben redirigir al login (para evitar loops)
  const ON_LOGIN_PAGE = window.location.pathname.includes('auth-login');

  async function request(method, path, body = null) {
    const opts = {
      method,
      headers: { 'Content-Type': 'application/json' },
      credentials: 'same-origin',
    };
    if (body !== null) opts.body = JSON.stringify(body);

    let data;
    try {
      const res = await fetch(BASE + path, opts);
      data = await res.json();
    } catch (e) {
      if (!ON_LOGIN_PAGE) window.location.href = '/auth-login.html';
      return { success: false, error: 'Error de conexión' };
    }

    // Solo redirigir si NO estamos ya en la página de login
    if (data.redirect_to_login && !ON_LOGIN_PAGE) {
      window.location.href = '/auth-login.html';
    }

    return data;
  }

  const get  = (path)       => request('GET',    path);
  const post = (path, body) => request('POST',   path, body);
  const put  = (path, body) => request('PUT',    path, body);
  const del  = (path)       => request('DELETE', path);

  return {
    /* ── SESIÓN ─────────────────────────────────────────── */
    login:      (username, password) => post('/api/login',  { username, password }),
    logout:     ()                   => post('/api/logout', {}),
    getSession: ()                   => get('/api/session'),

    /* ── USUARIOS (solo Admin) ───────────────────────────── */
    getUsers:   ()                         => get('/api/users'),
    createUser: (username, password, role) => post('/api/users', { username, password, role }),
    updateUser: (userId, data)             => put(`/api/users/${userId}`, data),
    deleteUser: (userId)                   => del(`/api/users/${userId}`),

    /* ── PACIENTES ──────────────────────────────────────── */
    getPatients:   (search = '') => get(`/api/patients${search ? '?search=' + encodeURIComponent(search) : ''}`),
    createPatient: (data)        => post('/api/patients', data),
    getPatient:    (id)          => get(`/api/patients/${id}`),
    updatePatient: (id, data)    => put(`/api/patients/${id}`, data),
    deletePatient: (id)          => del(`/api/patients/${id}`),

    /* ── FACTORES DE RIESGO ─────────────────────────────── */
    getRiskFactors:          ()          => get('/api/risk-factors'),
    addPatientRiskFactor:    (pid, rfid) => post(`/api/patients/${pid}/risk-factors`, { riskFactorID: rfid }),
    removePatientRiskFactor: (pid, rfid) => del(`/api/patients/${pid}/risk-factors/${rfid}`),

    /* ── PREDICCIÓN / IA ────────────────────────────────── */
    predict: (imageData, filename) =>
      post('/api/predict', { imageData, filename }),

    gradcam: (imageData, filename, predictionResult) =>
      post('/api/gradcam', { imageData, filename, predictionResult }),

    /* ── CONSULTAS ──────────────────────────────────────── */
    getConsultations: (page = 1, perPage = 10, search = '', filter = 'all') =>
      get(`/api/consultations?page=${page}&per_page=${perPage}&search=${encodeURIComponent(search)}&filter=${filter}`),

    getConsultation: (id) => get(`/api/consultations/${id}`),

    saveConsultation: (data) => post('/api/consultations', data),

    /* ── DASHBOARD ──────────────────────────────────────── */
    getDashboardStats: () => get('/api/dashboard/stats'),
    getModelInfo:      () => get('/api/model/info'),

    /* ── TAREAS ─────────────────────────────────────────── */
    getTasks:   ()     => get('/api/tasks'),
    addTask:    (text) => post('/api/tasks', { text }),
    toggleTask: (id)   => post(`/api/tasks/${id}/toggle`, {}),
    deleteTask: (id)   => del(`/api/tasks/${id}`),
  };
})();

if (typeof window !== 'undefined') window.api = api;