|
| 1 | +document.addEventListener('DOMContentLoaded', () => { |
| 2 | + // Verificar si el usuario está autenticado |
| 3 | + const token = localStorage.getItem('token'); |
| 4 | + if (!token) { |
| 5 | + window.location.href = 'login.html'; |
| 6 | + return; |
| 7 | + } |
| 8 | + |
| 9 | + // Obtener datos del usuario actual |
| 10 | + const currentUser = JSON.parse(localStorage.getItem('currentUser')); |
| 11 | + document.getElementById('userName').textContent = currentUser.nombre; |
| 12 | + |
| 13 | + // Manejar cierre de sesión |
| 14 | + document.getElementById('logoutBtn').addEventListener('click', () => { |
| 15 | + localStorage.removeItem('token'); |
| 16 | + localStorage.removeItem('currentUser'); |
| 17 | + window.location.href = 'login.html'; |
| 18 | + }); |
| 19 | + |
| 20 | + // Inicializar elementos |
| 21 | + const tabs = document.querySelectorAll('.tab-btn'); |
| 22 | + const tabPanels = document.querySelectorAll('.tab-panel'); |
| 23 | + const gastoForm = document.getElementById('gastoForm'); |
| 24 | + const ingresoForm = document.getElementById('ingresoForm'); |
| 25 | + const patrimonioForm = document.getElementById('patrimonioForm'); |
| 26 | + const objetivoForm = document.getElementById('objetivoForm'); |
| 27 | + const gastosList = document.getElementById('gastosList'); |
| 28 | + const ingresosList = document.getElementById('ingresosList'); |
| 29 | + const patrimonioList = document.getElementById('patrimonioList'); |
| 30 | + const objetivosList = document.getElementById('objetivosList'); |
| 31 | + const totalGastos = document.getElementById('totalGastos'); |
| 32 | + const totalIngresos = document.getElementById('totalIngresos'); |
| 33 | + const totalPatrimonio = document.getElementById('totalPatrimonio'); |
| 34 | + const flujoNeto = document.getElementById('flujoNeto'); |
| 35 | + const saldoDisponible = document.getElementById('saldoDisponible'); |
| 36 | + const ratioAhorro = document.getElementById('ratioAhorro'); |
| 37 | + const ratioEndeudamiento = document.getElementById('ratioEndeudamiento'); |
| 38 | + const ratioLiquidez = document.getElementById('ratioLiquidez'); |
| 39 | + const ratioSolvencia = document.getElementById('ratioSolvencia'); |
| 40 | + const recomendacionesList = document.getElementById('recomendacionesList'); |
| 41 | + |
| 42 | + // Inicializar datos del usuario actual |
| 43 | + let gastos = currentUser.gastos || []; |
| 44 | + let ingresos = currentUser.ingresos || []; |
| 45 | + let patrimonio = currentUser.patrimonio || []; |
| 46 | + let objetivos = currentUser.objetivos || []; |
| 47 | + |
| 48 | + // Guardar cambios en el usuario actual |
| 49 | + function actualizarUsuario() { |
| 50 | + const users = JSON.parse(localStorage.getItem('users')) || []; |
| 51 | + const userIndex = users.findIndex(u => u.id === currentUser.id); |
| 52 | + if (userIndex !== -1) { |
| 53 | + users[userIndex] = { |
| 54 | + ...currentUser, |
| 55 | + gastos, |
| 56 | + ingresos, |
| 57 | + patrimonio, |
| 58 | + objetivos |
| 59 | + }; |
| 60 | + localStorage.setItem('users', JSON.stringify(users)); |
| 61 | + localStorage.setItem('currentUser', JSON.stringify(users[userIndex])); |
| 62 | + } |
| 63 | + } |
| 64 | + // Inicializar elementos |
| 65 | + const tabs = document.querySelectorAll('.tab-btn'); |
| 66 | + const tabPanels = document.querySelectorAll('.tab-panel'); |
| 67 | + const gastoForm = document.getElementById('gastoForm'); |
| 68 | + const ingresoForm = document.getElementById('ingresoForm'); |
| 69 | + const patrimonioForm = document.getElementById('patrimonioForm'); |
| 70 | + const objetivoForm = document.getElementById('objetivoForm'); |
| 71 | + const gastosList = document.getElementById('gastosList'); |
| 72 | + const ingresosList = document.getElementById('ingresosList'); |
| 73 | + const patrimonioList = document.getElementById('patrimonioList'); |
| 74 | + const objetivosList = document.getElementById('objetivosList'); |
| 75 | + const totalGastos = document.getElementById('totalGastos'); |
| 76 | + const totalIngresos = document.getElementById('totalIngresos'); |
| 77 | + const totalPatrimonio = document.getElementById('totalPatrimonio'); |
| 78 | + const flujoNeto = document.getElementById('flujoNeto'); |
| 79 | + const saldoDisponible = document.getElementById('saldoDisponible'); |
| 80 | + const ratioAhorro = document.getElementById('ratioAhorro'); |
| 81 | + const ratioEndeudamiento = document.getElementById('ratioEndeudamiento'); |
| 82 | + const ratioLiquidez = document.getElementById('ratioLiquidez'); |
| 83 | + const ratioSolvencia = document.getElementById('ratioSolvencia'); |
| 84 | + const recomendacionesList = document.getElementById('recomendacionesList'); |
| 85 | + |
| 86 | + // Inicializar datos |
| 87 | + let gastos = JSON.parse(localStorage.getItem('gastos')) || []; |
| 88 | + let ingresos = JSON.parse(localStorage.getItem('ingresos')) || []; |
| 89 | + let patrimonio = JSON.parse(localStorage.getItem('patrimonio')) || []; |
| 90 | + let objetivos = JSON.parse(localStorage.getItem('objetivos')) || []; |
| 91 | + |
| 92 | + // Manejar cambio de pestañas |
| 93 | + tabs.forEach(tab => { |
| 94 | + tab.addEventListener('click', () => { |
| 95 | + tabs.forEach(t => t.classList.remove('active')); |
| 96 | + tabPanels.forEach(panel => panel.classList.remove('active')); |
| 97 | + |
| 98 | + tab.classList.add('active'); |
| 99 | + document.getElementById(tab.dataset.tab).classList.add('active'); |
| 100 | + }); |
| 101 | + }); |
| 102 | + |
| 103 | + // Funciones de análisis financiero |
| 104 | + function calcularIndicadores() { |
| 105 | + const totalG = gastos.reduce((sum, gasto) => sum + gasto.monto, 0); |
| 106 | + const totalI = ingresos.reduce((sum, ingreso) => sum + ingreso.monto, 0); |
| 107 | + const totalP = patrimonio.reduce((sum, activo) => sum + activo.valor, 0); |
| 108 | + const pasivos = calcularPasivos(); |
| 109 | + const activosLiquidos = calcularActivosLiquidos(); |
| 110 | + |
| 111 | + // Ratio de ahorro |
| 112 | + const ratioA = (totalI - totalG) / totalI * 100; |
| 113 | + ratioAhorro.textContent = ratioA.toFixed(1); |
| 114 | + |
| 115 | + // Ratio de endeudamiento |
| 116 | + const ratioE = (pasivos / totalP) * 100; |
| 117 | + ratioEndeudamiento.textContent = ratioE.toFixed(1); |
| 118 | + |
| 119 | + // Ratio de liquidez |
| 120 | + const ratioL = (activosLiquidos / pasivos); |
| 121 | + ratioLiquidez.textContent = ratioL.toFixed(2); |
| 122 | + |
| 123 | + // Ratio de solvencia |
| 124 | + const ratioS = (totalP / pasivos); |
| 125 | + ratioSolvencia.textContent = ratioS.toFixed(2); |
| 126 | + |
| 127 | + // Saldo disponible |
| 128 | + saldoDisponible.textContent = (totalI - totalG).toFixed(2); |
| 129 | + |
| 130 | + // Generar recomendaciones |
| 131 | + generarRecomendaciones(ratioA, ratioE, ratioL, ratioS); |
| 132 | + } |
| 133 | + |
| 134 | + function calcularPasivos() { |
| 135 | + // Aquí podríamos agregar más lógica para calcular pasivos específicos |
| 136 | + return gastos.reduce((sum, gasto) => sum + gasto.monto, 0); |
| 137 | + } |
| 138 | + |
| 139 | + function calcularActivosLiquidos() { |
| 140 | + return patrimonio.reduce((sum, activo) => { |
| 141 | + if (activo.tipo === 'inversion') return sum + activo.valor; |
| 142 | + return sum; |
| 143 | + }, 0); |
| 144 | + } |
| 145 | + |
| 146 | + function generarRecomendaciones(ratioA, ratioE, ratioL, ratioS) { |
| 147 | + recomendacionesList.innerHTML = ''; |
| 148 | + |
| 149 | + // Ratio de ahorro |
| 150 | + if (ratioA < 20) { |
| 151 | + agregarRecomendacion('Considera aumentar tu ratio de ahorro. Es recomendable ahorrar al menos el 20% de tus ingresos.'); |
| 152 | + } |
| 153 | + |
| 154 | + // Ratio de endeudamiento |
| 155 | + if (ratioE > 30) { |
| 156 | + agregarRecomendacion('Tu ratio de endeudamiento es alto. Considera reducir tus deudas.'); |
| 157 | + } |
| 158 | + |
| 159 | + // Ratio de liquidez |
| 160 | + if (ratioL < 1) { |
| 161 | + agregarRecomendacion('Tu ratio de liquidez es bajo. Considera aumentar tus activos líquidos.'); |
| 162 | + } |
| 163 | + |
| 164 | + // Ratio de solvencia |
| 165 | + if (ratioS < 2) { |
| 166 | + agregarRecomendacion('Tu ratio de solvencia es bajo. Considera mejorar tu estructura de capital.'); |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + function agregarRecomendacion(texto) { |
| 171 | + const recomendacion = document.createElement('div'); |
| 172 | + recomendacion.className = 'recomendacion-item'; |
| 173 | + recomendacion.textContent = texto; |
| 174 | + recomendacionesList.appendChild(recomendacion); |
| 175 | + } |
| 176 | + |
| 177 | + // Funciones para objetivos |
| 178 | + function mostrarObjetivos() { |
| 179 | + objetivosList.innerHTML = ''; |
| 180 | + objetivos.forEach((objetivo, index) => { |
| 181 | + const objetivoElement = document.createElement('div'); |
| 182 | + objetivoElement.className = 'objetivo-item'; |
| 183 | + |
| 184 | + // Calcular progreso |
| 185 | + const diasTotales = Math.ceil((new Date(objetivo.fecha) - new Date()) / (1000 * 60 * 60 * 24)); |
| 186 | + const diasPasados = Math.max(0, diasTotales - Math.ceil((new Date() - new Date()) / (1000 * 60 * 60 * 24))); |
| 187 | + const progreso = (diasPasados / diasTotales) * 100; |
| 188 | + |
| 189 | + objetivoElement.innerHTML = ` |
| 190 | + <div> |
| 191 | + <p><strong>${objetivo.nombre}</strong></p> |
| 192 | + <p>Monto: $${objetivo.monto}</p> |
| 193 | + <p>Fecha objetivo: ${new Date(objetivo.fecha).toLocaleDateString()}</p> |
| 194 | + <div class="progreso"> |
| 195 | + <div class="barra" style="width: ${progreso}%"></div> |
| 196 | + </div> |
| 197 | + </div> |
| 198 | + <div class="actions"> |
| 199 | + <button onclick="eliminarObjetivo(${index})">Eliminar</button> |
| 200 | + </div> |
| 201 | + `; |
| 202 | + objetivosList.appendChild(objetivoElement); |
| 203 | + }); |
| 204 | + } |
| 205 | + |
| 206 | + // Eventos de formularios |
| 207 | + gastoForm.addEventListener('submit', (e) => { |
| 208 | + e.preventDefault(); |
| 209 | + const descripcion = document.getElementById('descripcion').value; |
| 210 | + const monto = parseFloat(document.getElementById('monto').value); |
| 211 | + const categoria = document.getElementById('categoria').value; |
| 212 | + |
| 213 | + const nuevoGasto = { |
| 214 | + descripcion, |
| 215 | + monto, |
| 216 | + categoria, |
| 217 | + fecha: new Date().toISOString() |
| 218 | + }; |
| 219 | + |
| 220 | + gastos.push(nuevoGasto); |
| 221 | + guardarDatos(); |
| 222 | + mostrarGastos(); |
| 223 | + gastoForm.reset(); |
| 224 | + }); |
| 225 | + |
| 226 | + ingresoForm.addEventListener('submit', (e) => { |
| 227 | + e.preventDefault(); |
| 228 | + const descripcion = document.getElementById('ingresoDescripcion').value; |
| 229 | + const monto = parseFloat(document.getElementById('ingresoMonto').value); |
| 230 | + const categoria = document.getElementById('ingresoCategoria').value; |
| 231 | + |
| 232 | + const nuevoIngreso = { |
| 233 | + descripcion, |
| 234 | + monto, |
| 235 | + categoria, |
| 236 | + fecha: new Date().toISOString() |
| 237 | + }; |
| 238 | + |
| 239 | + ingresos.push(nuevoIngreso); |
| 240 | + guardarDatos(); |
| 241 | + mostrarIngresos(); |
| 242 | + ingresoForm.reset(); |
| 243 | + }); |
| 244 | + |
| 245 | + patrimonioForm.addEventListener('submit', (e) => { |
| 246 | + e.preventDefault(); |
| 247 | + const nombre = document.getElementById('activoNombre').value; |
| 248 | + const valor = parseFloat(document.getElementById('activoValor').value); |
| 249 | + const tipo = document.getElementById('activoTipo').value; |
| 250 | + |
| 251 | + const nuevoActivo = { |
| 252 | + nombre, |
| 253 | + valor, |
| 254 | + tipo, |
| 255 | + fecha: new Date().toISOString() |
| 256 | + }; |
| 257 | + |
| 258 | + patrimonio.push(nuevoActivo); |
| 259 | + guardarDatos(); |
| 260 | + mostrarPatrimonio(); |
| 261 | + patrimonioForm.reset(); |
| 262 | + }); |
| 263 | + |
| 264 | + objetivoForm.addEventListener('submit', (e) => { |
| 265 | + e.preventDefault(); |
| 266 | + const nombre = document.getElementById('objetivoNombre').value; |
| 267 | + const monto = parseFloat(document.getElementById('objetivoMonto').value); |
| 268 | + const fecha = document.getElementById('objetivoFecha').value; |
| 269 | + |
| 270 | + const nuevoObjetivo = { |
| 271 | + nombre, |
| 272 | + monto, |
| 273 | + fecha, |
| 274 | + fechaCreacion: new Date().toISOString() |
| 275 | + }; |
| 276 | + |
| 277 | + objetivos.push(nuevoObjetivo); |
| 278 | + guardarDatos(); |
| 279 | + mostrarObjetivos(); |
| 280 | + objetivoForm.reset(); |
| 281 | + }); |
| 282 | + |
| 283 | + // Funciones de eliminación |
| 284 | + window.eliminarGasto = (index) => { |
| 285 | + if (confirm('¿Estás seguro de que deseas eliminar este gasto?')) { |
| 286 | + gastos.splice(index, 1); |
| 287 | + guardarDatos(); |
| 288 | + mostrarGastos(); |
| 289 | + } |
| 290 | + }; |
| 291 | + |
| 292 | + window.eliminarIngreso = (index) => { |
| 293 | + if (confirm('¿Estás seguro de que deseas eliminar este ingreso?')) { |
| 294 | + ingresos.splice(index, 1); |
| 295 | + guardarDatos(); |
| 296 | + mostrarIngresos(); |
| 297 | + } |
| 298 | + }; |
| 299 | + |
| 300 | + window.eliminarActivo = (index) => { |
| 301 | + if (confirm('¿Estás seguro de que deseas eliminar este activo?')) { |
| 302 | + patrimonio.splice(index, 1); |
| 303 | + guardarDatos(); |
| 304 | + mostrarPatrimonio(); |
| 305 | + } |
| 306 | + }; |
| 307 | + |
| 308 | + window.eliminarObjetivo = (index) => { |
| 309 | + if (confirm('¿Estás seguro de que deseas eliminar este objetivo?')) { |
| 310 | + objetivos.splice(index, 1); |
| 311 | + guardarDatos(); |
| 312 | + mostrarObjetivos(); |
| 313 | + } |
| 314 | + }; |
| 315 | + |
| 316 | + // Funciones comunes |
| 317 | + function guardarDatos() { |
| 318 | + localStorage.setItem('gastos', JSON.stringify(gastos)); |
| 319 | + localStorage.setItem('ingresos', JSON.stringify(ingresos)); |
| 320 | + localStorage.setItem('patrimonio', JSON.stringify(patrimonio)); |
| 321 | + localStorage.setItem('objetivos', JSON.stringify(objetivos)); |
| 322 | + calcularIndicadores(); |
| 323 | + } |
| 324 | + |
| 325 | + // Mostrar datos al cargar |
| 326 | + mostrarGastos(); |
| 327 | + mostrarIngresos(); |
| 328 | + mostrarPatrimonio(); |
| 329 | + mostrarObjetivos(); |
| 330 | + calcularIndicadores(); |
| 331 | +}); |
0 commit comments