Spaces:
Configuration error
Configuration error
Upload 5 files
Browse files- .gitignore +11 -0
- README.md +197 -9
- app.py +231 -196
- index.html +49 -1255
- requirements.txt +1 -10
.gitignore
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.py[cod]
|
| 3 |
+
*$py.class
|
| 4 |
+
*.so
|
| 5 |
+
.Python
|
| 6 |
+
*.db-journal
|
| 7 |
+
.env
|
| 8 |
+
.venv
|
| 9 |
+
env/
|
| 10 |
+
venv/
|
| 11 |
+
.DS_Store
|
README.md
CHANGED
|
@@ -1,11 +1,199 @@
|
|
| 1 |
-
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
---
|
| 10 |
|
| 11 |
-
|
|
|
|
| 1 |
+
# 🏃♂️ Osorno Runners - Sistema de Planes de Entrenamiento
|
| 2 |
+
|
| 3 |
+
Sistema profesional para crear y gestionar planes de entrenamiento personalizados para corredores.
|
| 4 |
+
|
| 5 |
+
## 🚀 Características
|
| 6 |
+
|
| 7 |
+
- ✅ Generación automática de planes de entrenamiento
|
| 8 |
+
- ✅ Base de datos SQLite persistente
|
| 9 |
+
- ✅ Sistema de autenticación (Usuario/Admin)
|
| 10 |
+
- ✅ Exportación a PDF
|
| 11 |
+
- ✅ Cálculo de zonas de frecuencia cardíaca
|
| 12 |
+
- ✅ IMC y datos antropométricos
|
| 13 |
+
- ✅ Cross training integrado
|
| 14 |
+
- ✅ Carreras preparatorias
|
| 15 |
+
- ✅ Mensajes motivacionales personalizados
|
| 16 |
+
|
| 17 |
+
## 📦 Tecnologías
|
| 18 |
+
|
| 19 |
+
- **Frontend**: HTML, CSS, JavaScript
|
| 20 |
+
- **Backend**: Python + Gradio
|
| 21 |
+
- **Base de Datos**: SQLite
|
| 22 |
+
- **Hosting**: HuggingFace Spaces
|
| 23 |
+
|
| 24 |
+
## 🔐 Credenciales por Defecto
|
| 25 |
+
|
| 26 |
+
### Usuario Regular
|
| 27 |
+
- **Usuario**: USER
|
| 28 |
+
- **Contraseña**: 123
|
| 29 |
+
- **Permisos**: Ver planes propios
|
| 30 |
+
|
| 31 |
+
### Administrador
|
| 32 |
+
- **Usuario**: ADMIN
|
| 33 |
+
- **Contraseña**: 123
|
| 34 |
+
- **Permisos**: Crear, ver y eliminar todos los planes
|
| 35 |
+
|
| 36 |
+
## 🏗️ Estructura del Proyecto
|
| 37 |
+
|
| 38 |
+
```
|
| 39 |
+
osorno-runners-hf/
|
| 40 |
+
├── app.py # Aplicación principal Gradio
|
| 41 |
+
├── index.html # Frontend
|
| 42 |
+
├── requirements.txt # Dependencias Python
|
| 43 |
+
├── README.md # Este archivo
|
| 44 |
+
└── osorno_runners.db # Base de datos SQLite (se crea automáticamente)
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
## 🚀 Despliegue en HuggingFace Spaces
|
| 48 |
+
|
| 49 |
+
### Paso 1: Crear Space
|
| 50 |
+
|
| 51 |
+
1. Ve a [HuggingFace Spaces](https://huggingface.co/spaces)
|
| 52 |
+
2. Click en "Create new Space"
|
| 53 |
+
3. Nombre: `osorno-runners` (o el que prefieras)
|
| 54 |
+
4. SDK: **Gradio**
|
| 55 |
+
5. Visibility: Public o Private
|
| 56 |
+
6. Click "Create Space"
|
| 57 |
+
|
| 58 |
+
### Paso 2: Subir Archivos
|
| 59 |
+
|
| 60 |
+
**Opción A - Mediante la interfaz web:**
|
| 61 |
+
1. Click en "Files" en tu Space
|
| 62 |
+
2. Click "Add file" → "Upload files"
|
| 63 |
+
3. Arrastra todos los archivos del proyecto
|
| 64 |
+
|
| 65 |
+
**Opción B - Mediante Git:**
|
| 66 |
+
```bash
|
| 67 |
+
git clone https://huggingface.co/spaces/TU_USUARIO/osorno-runners
|
| 68 |
+
cd osorno-runners
|
| 69 |
+
# Copia los archivos del proyecto aquí
|
| 70 |
+
git add .
|
| 71 |
+
git commit -m "Initial commit"
|
| 72 |
+
git push
|
| 73 |
+
```
|
| 74 |
+
|
| 75 |
+
### Paso 3: Configuración
|
| 76 |
+
|
| 77 |
+
El Space se desplegará automáticamente. La base de datos SQLite se creará en el primer inicio.
|
| 78 |
+
|
| 79 |
+
## 💻 Desarrollo Local
|
| 80 |
+
|
| 81 |
+
```bash
|
| 82 |
+
# Instalar dependencias
|
| 83 |
+
pip install -r requirements.txt
|
| 84 |
+
|
| 85 |
+
# Ejecutar aplicación
|
| 86 |
+
python app.py
|
| 87 |
+
|
| 88 |
+
# Abrir navegador en http://localhost:7860
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
## 📊 Base de Datos
|
| 92 |
+
|
| 93 |
+
### Tabla: planes
|
| 94 |
+
```sql
|
| 95 |
+
CREATE TABLE planes (
|
| 96 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 97 |
+
plan_data TEXT NOT NULL,
|
| 98 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
| 99 |
+
created_by TEXT NOT NULL,
|
| 100 |
+
athlete_name TEXT NOT NULL,
|
| 101 |
+
distance TEXT NOT NULL,
|
| 102 |
+
race_date TEXT NOT NULL
|
| 103 |
+
)
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
### Tabla: users
|
| 107 |
+
```sql
|
| 108 |
+
CREATE TABLE users (
|
| 109 |
+
username TEXT PRIMARY KEY,
|
| 110 |
+
password TEXT NOT NULL,
|
| 111 |
+
role TEXT NOT NULL,
|
| 112 |
+
name TEXT NOT NULL
|
| 113 |
+
)
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
## 🎯 Funcionalidades Principales
|
| 117 |
+
|
| 118 |
+
### Generación de Planes
|
| 119 |
+
- Cálculo automático de duración según distancia y experiencia
|
| 120 |
+
- Periodización (Base, Específico, Competencia, Transición)
|
| 121 |
+
- Distribución inteligente de volumen
|
| 122 |
+
- Zonas de FC personalizadas (Karvonen)
|
| 123 |
+
|
| 124 |
+
### Tipos de Sesiones
|
| 125 |
+
- Trote continuo base
|
| 126 |
+
- Intervalos de velocidad
|
| 127 |
+
- Tempo run
|
| 128 |
+
- Long run (carrera larga)
|
| 129 |
+
- Recuperación activa
|
| 130 |
+
- Cross training
|
| 131 |
+
|
| 132 |
+
### Exportación PDF
|
| 133 |
+
- Diseño profesional
|
| 134 |
+
- Toda la información del atleta
|
| 135 |
+
- Desglose semanal completo
|
| 136 |
+
- Zonas de frecuencia cardíaca
|
| 137 |
+
|
| 138 |
+
## 🔧 Personalización
|
| 139 |
+
|
| 140 |
+
### Agregar Nuevos Usuarios
|
| 141 |
+
Edita `app.py` en la función `init_db()`:
|
| 142 |
+
|
| 143 |
+
```python
|
| 144 |
+
cursor.execute("INSERT INTO users VALUES ('NUEVO_USER', 'pass123', 'user', 'Nombre')")
|
| 145 |
+
```
|
| 146 |
+
|
| 147 |
+
### Modificar Algoritmos
|
| 148 |
+
Los algoritmos de generación están en `index.html` en las funciones JavaScript:
|
| 149 |
+
- `calculateWeeks()`: Duración del plan
|
| 150 |
+
- `getBaseKm()`: Kilometraje base
|
| 151 |
+
- `generateWeekSessions()`: Sesiones semanales
|
| 152 |
+
|
| 153 |
+
## 📈 Mejoras Futuras
|
| 154 |
+
|
| 155 |
+
- [ ] Integración con IA (HuggingFace Inference API)
|
| 156 |
+
- [ ] Análisis de progreso
|
| 157 |
+
- [ ] Gráficos de volumen
|
| 158 |
+
- [ ] Exportar a Google Calendar
|
| 159 |
+
- [ ] Notificaciones por email
|
| 160 |
+
- [ ] Versión móvil nativa
|
| 161 |
+
|
| 162 |
+
## 🤝 Contribuciones
|
| 163 |
+
|
| 164 |
+
Las contribuciones son bienvenidas. Por favor:
|
| 165 |
+
1. Fork el repositorio
|
| 166 |
+
2. Crea una rama para tu feature
|
| 167 |
+
3. Commit tus cambios
|
| 168 |
+
4. Push a la rama
|
| 169 |
+
5. Abre un Pull Request
|
| 170 |
+
|
| 171 |
+
## 📄 Licencia
|
| 172 |
+
|
| 173 |
+
MIT License
|
| 174 |
+
|
| 175 |
+
## 👨💻 Autor
|
| 176 |
+
|
| 177 |
+
Desarrollado para Osorno Runners
|
| 178 |
+
|
| 179 |
+
## 🐛 Reporte de Bugs
|
| 180 |
+
|
| 181 |
+
Si encuentras algún bug, por favor:
|
| 182 |
+
1. Ve a la pestaña "Community" del Space
|
| 183 |
+
2. Abre una nueva discusión
|
| 184 |
+
3. Describe el problema detalladamente
|
| 185 |
+
|
| 186 |
+
## ⚡ Notas Importantes
|
| 187 |
+
|
| 188 |
+
- La base de datos SQLite es persistente en HuggingFace Spaces
|
| 189 |
+
- Los datos se mantienen entre reinicios del Space
|
| 190 |
+
- Para backup, descarga `osorno_runners.db` desde Files
|
| 191 |
+
- Máximo 50MB de almacenamiento en plan gratuito
|
| 192 |
+
|
| 193 |
+
## 🌟 Showcase
|
| 194 |
+
|
| 195 |
+
Ejemplo de uso: [Demo en vivo](https://huggingface.co/spaces/TU_USUARIO/osorno-runners)
|
| 196 |
+
|
| 197 |
---
|
| 198 |
|
| 199 |
+
**¡Dale una ⭐ si te gusta el proyecto!**
|
app.py
CHANGED
|
@@ -1,196 +1,231 @@
|
|
| 1 |
-
import
|
| 2 |
-
import json
|
| 3 |
-
|
| 4 |
-
from
|
| 5 |
-
from
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import json
|
| 3 |
+
import sqlite3
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
# Configuración de la base de datos
|
| 9 |
+
DB_FILE = 'osorno_runners.db'
|
| 10 |
+
|
| 11 |
+
def init_db():
|
| 12 |
+
"""Inicializar base de datos SQLite"""
|
| 13 |
+
conn = sqlite3.connect(DB_FILE)
|
| 14 |
+
cursor = conn.cursor()
|
| 15 |
+
|
| 16 |
+
# Tabla de planes
|
| 17 |
+
cursor.execute('''
|
| 18 |
+
CREATE TABLE IF NOT EXISTS planes (
|
| 19 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 20 |
+
plan_data TEXT NOT NULL,
|
| 21 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
| 22 |
+
created_by TEXT NOT NULL,
|
| 23 |
+
athlete_name TEXT NOT NULL,
|
| 24 |
+
distance TEXT NOT NULL,
|
| 25 |
+
race_date TEXT NOT NULL
|
| 26 |
+
)
|
| 27 |
+
''')
|
| 28 |
+
|
| 29 |
+
# Tabla de usuarios
|
| 30 |
+
cursor.execute('''
|
| 31 |
+
CREATE TABLE IF NOT EXISTS users (
|
| 32 |
+
username TEXT PRIMARY KEY,
|
| 33 |
+
password TEXT NOT NULL,
|
| 34 |
+
role TEXT NOT NULL,
|
| 35 |
+
name TEXT NOT NULL
|
| 36 |
+
)
|
| 37 |
+
''')
|
| 38 |
+
|
| 39 |
+
# Insertar usuarios por defecto si no existen
|
| 40 |
+
cursor.execute('SELECT COUNT(*) FROM users')
|
| 41 |
+
if cursor.fetchone()[0] == 0:
|
| 42 |
+
cursor.execute("INSERT INTO users VALUES ('USER', '123', 'user', 'Usuario')")
|
| 43 |
+
cursor.execute("INSERT INTO users VALUES ('ADMIN', '123', 'admin', 'Administrador')")
|
| 44 |
+
print("✅ Usuarios por defecto creados: USER/123 y ADMIN/123")
|
| 45 |
+
|
| 46 |
+
conn.commit()
|
| 47 |
+
conn.close()
|
| 48 |
+
print("✅ Base de datos inicializada correctamente")
|
| 49 |
+
|
| 50 |
+
def save_plan_to_db(plan_data, username):
|
| 51 |
+
"""Guardar plan en la base de datos"""
|
| 52 |
+
try:
|
| 53 |
+
conn = sqlite3.connect(DB_FILE)
|
| 54 |
+
cursor = conn.cursor()
|
| 55 |
+
|
| 56 |
+
cursor.execute('''
|
| 57 |
+
INSERT INTO planes (plan_data, created_by, athlete_name, distance, race_date)
|
| 58 |
+
VALUES (?, ?, ?, ?, ?)
|
| 59 |
+
''', (
|
| 60 |
+
json.dumps(plan_data),
|
| 61 |
+
username,
|
| 62 |
+
plan_data['userData']['name'],
|
| 63 |
+
plan_data['userData']['distance'],
|
| 64 |
+
plan_data['userData']['raceDate']
|
| 65 |
+
))
|
| 66 |
+
|
| 67 |
+
conn.commit()
|
| 68 |
+
plan_id = cursor.lastrowid
|
| 69 |
+
conn.close()
|
| 70 |
+
|
| 71 |
+
print(f"✅ Plan guardado con ID: {plan_id}")
|
| 72 |
+
return plan_id
|
| 73 |
+
except Exception as e:
|
| 74 |
+
print(f"❌ Error al guardar plan: {e}")
|
| 75 |
+
return None
|
| 76 |
+
|
| 77 |
+
def get_all_plans(username=None, role='user'):
|
| 78 |
+
"""Obtener todos los planes según permisos"""
|
| 79 |
+
try:
|
| 80 |
+
conn = sqlite3.connect(DB_FILE)
|
| 81 |
+
cursor = conn.cursor()
|
| 82 |
+
|
| 83 |
+
if role == 'admin':
|
| 84 |
+
cursor.execute('SELECT id, plan_data, created_at, created_by FROM planes ORDER BY created_at DESC')
|
| 85 |
+
else:
|
| 86 |
+
cursor.execute('SELECT id, plan_data, created_at, created_by FROM planes WHERE created_by = ? ORDER BY created_at DESC', (username,))
|
| 87 |
+
|
| 88 |
+
plans = []
|
| 89 |
+
for row in cursor.fetchall():
|
| 90 |
+
plan_data = json.loads(row[1])
|
| 91 |
+
plan_data['id'] = row[0]
|
| 92 |
+
plan_data['createdAt'] = row[2]
|
| 93 |
+
plan_data['createdBy'] = row[3]
|
| 94 |
+
plans.append(plan_data)
|
| 95 |
+
|
| 96 |
+
conn.close()
|
| 97 |
+
print(f"✅ Cargados {len(plans)} planes para {username} ({role})")
|
| 98 |
+
return plans
|
| 99 |
+
except Exception as e:
|
| 100 |
+
print(f"❌ Error al cargar planes: {e}")
|
| 101 |
+
return []
|
| 102 |
+
|
| 103 |
+
def delete_plan_from_db(plan_id):
|
| 104 |
+
"""Eliminar plan de la base de datos"""
|
| 105 |
+
try:
|
| 106 |
+
conn = sqlite3.connect(DB_FILE)
|
| 107 |
+
cursor = conn.cursor()
|
| 108 |
+
cursor.execute('DELETE FROM planes WHERE id = ?', (plan_id,))
|
| 109 |
+
conn.commit()
|
| 110 |
+
conn.close()
|
| 111 |
+
print(f"✅ Plan {plan_id} eliminado")
|
| 112 |
+
return True
|
| 113 |
+
except Exception as e:
|
| 114 |
+
print(f"❌ Error al eliminar plan: {e}")
|
| 115 |
+
return False
|
| 116 |
+
|
| 117 |
+
def authenticate_user(username, password):
|
| 118 |
+
"""Autenticar usuario"""
|
| 119 |
+
try:
|
| 120 |
+
conn = sqlite3.connect(DB_FILE)
|
| 121 |
+
cursor = conn.cursor()
|
| 122 |
+
cursor.execute('SELECT role, name FROM users WHERE username = ? AND password = ?',
|
| 123 |
+
(username.upper(), password))
|
| 124 |
+
result = cursor.fetchone()
|
| 125 |
+
conn.close()
|
| 126 |
+
|
| 127 |
+
if result:
|
| 128 |
+
user_data = {
|
| 129 |
+
'username': username.upper(),
|
| 130 |
+
'role': result[0],
|
| 131 |
+
'name': result[1]
|
| 132 |
+
}
|
| 133 |
+
print(f"✅ Login exitoso: {username} ({result[0]})")
|
| 134 |
+
return user_data
|
| 135 |
+
else:
|
| 136 |
+
print(f"❌ Login fallido: {username}")
|
| 137 |
+
return None
|
| 138 |
+
except Exception as e:
|
| 139 |
+
print(f"❌ Error en autenticación: {e}")
|
| 140 |
+
return None
|
| 141 |
+
|
| 142 |
+
# APIs para el frontend
|
| 143 |
+
def api_login(request: gr.Request):
|
| 144 |
+
"""API de login"""
|
| 145 |
+
try:
|
| 146 |
+
data = json.loads(request.query_params.get('data', '{}'))
|
| 147 |
+
username = data.get('username', '')
|
| 148 |
+
password = data.get('password', '')
|
| 149 |
+
|
| 150 |
+
user = authenticate_user(username, password)
|
| 151 |
+
if user:
|
| 152 |
+
return json.dumps({'success': True, 'user': user})
|
| 153 |
+
return json.dumps({'success': False, 'error': 'Credenciales inválidas'})
|
| 154 |
+
except Exception as e:
|
| 155 |
+
return json.dumps({'success': False, 'error': str(e)})
|
| 156 |
+
|
| 157 |
+
def api_save_plan(request: gr.Request):
|
| 158 |
+
"""API para guardar plan"""
|
| 159 |
+
try:
|
| 160 |
+
data = json.loads(request.query_params.get('data', '{}'))
|
| 161 |
+
plan_json = data.get('plan', '{}')
|
| 162 |
+
username = data.get('username', '')
|
| 163 |
+
|
| 164 |
+
plan_data = json.loads(plan_json)
|
| 165 |
+
plan_id = save_plan_to_db(plan_data, username)
|
| 166 |
+
|
| 167 |
+
if plan_id:
|
| 168 |
+
return json.dumps({'success': True, 'id': plan_id})
|
| 169 |
+
return json.dumps({'success': False, 'error': 'Error al guardar'})
|
| 170 |
+
except Exception as e:
|
| 171 |
+
return json.dumps({'success': False, 'error': str(e)})
|
| 172 |
+
|
| 173 |
+
def api_get_plans(request: gr.Request):
|
| 174 |
+
"""API para obtener planes"""
|
| 175 |
+
try:
|
| 176 |
+
data = json.loads(request.query_params.get('data', '{}'))
|
| 177 |
+
username = data.get('username', '')
|
| 178 |
+
role = data.get('role', 'user')
|
| 179 |
+
|
| 180 |
+
plans = get_all_plans(username, role)
|
| 181 |
+
return json.dumps({'success': True, 'plans': plans})
|
| 182 |
+
except Exception as e:
|
| 183 |
+
return json.dumps({'success': False, 'error': str(e)})
|
| 184 |
+
|
| 185 |
+
def api_delete_plan(request: gr.Request):
|
| 186 |
+
"""API para eliminar plan"""
|
| 187 |
+
try:
|
| 188 |
+
data = json.loads(request.query_params.get('data', '{}'))
|
| 189 |
+
plan_id = data.get('plan_id', 0)
|
| 190 |
+
|
| 191 |
+
success = delete_plan_from_db(plan_id)
|
| 192 |
+
if success:
|
| 193 |
+
return json.dumps({'success': True})
|
| 194 |
+
return json.dumps({'success': False, 'error': 'Error al eliminar'})
|
| 195 |
+
except Exception as e:
|
| 196 |
+
return json.dumps({'success': False, 'error': str(e)})
|
| 197 |
+
|
| 198 |
+
# Inicializar BD al arrancar
|
| 199 |
+
print("🚀 Iniciando Osorno Runners - Sistema de Entrenamiento")
|
| 200 |
+
init_db()
|
| 201 |
+
|
| 202 |
+
# Leer HTML
|
| 203 |
+
html_path = Path("index.html")
|
| 204 |
+
if html_path.exists():
|
| 205 |
+
html_content = html_path.read_text(encoding='utf-8')
|
| 206 |
+
print("✅ HTML cargado correctamente")
|
| 207 |
+
else:
|
| 208 |
+
html_content = "<h1>Error: index.html no encontrado</h1>"
|
| 209 |
+
print("❌ Error: index.html no encontrado")
|
| 210 |
+
|
| 211 |
+
# Crear interfaz Gradio
|
| 212 |
+
with gr.Blocks(
|
| 213 |
+
title="Osorno Runners",
|
| 214 |
+
theme=gr.themes.Soft(),
|
| 215 |
+
css="""
|
| 216 |
+
.gradio-container {padding: 0 !important;}
|
| 217 |
+
.contain {max-width: 100% !important;}
|
| 218 |
+
"""
|
| 219 |
+
) as app:
|
| 220 |
+
gr.HTML(html_content)
|
| 221 |
+
|
| 222 |
+
# Configuración del servidor
|
| 223 |
+
if __name__ == "__main__":
|
| 224 |
+
print("🌐 Iniciando servidor en puerto 7860")
|
| 225 |
+
app.launch(
|
| 226 |
+
server_name="0.0.0.0",
|
| 227 |
+
server_port=7860,
|
| 228 |
+
share=False,
|
| 229 |
+
show_error=True
|
| 230 |
+
)
|
| 231 |
+
|
index.html
CHANGED
|
@@ -1,17 +1,16 @@
|
|
| 1 |
<!DOCTYPE html>
|
| 2 |
<html lang="es">
|
| 3 |
<head>
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
</head>
|
| 10 |
-
<body>
|
| 11 |
<style>
|
| 12 |
-
*{margin:0;padding:0;box-sizing:border-box}:root{--primary-color:#dc143c;--primary-dark:#8b0000;--secondary-color:#00a65a;--danger-color:#dd4b39;--warning-color:#f39c12;--info-color:#00c0ef;--dark-color:#222d32;--sidebar-bg:#222d32;--sidebar-hover:#1a2226;--content-bg:#ecf0f5;--white:#fff;--text-dark:#333;--text-light:#666;--border-color:#ddd}body{font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;background-color:var(--content-bg);color:var(--text-dark)}.login-container{display:flex;justify-content:center;align-items:center;min-height:100vh;background:linear-gradient(135deg,var(--primary-color) 0%,var(--primary-dark) 100%)}.login-box{background:var(--white);padding:40px;border-radius:10px;box-shadow:0 10px 40px rgba(0,0,0,.3);width:100%;max-width:400px}.login-header{text-align:center;margin-bottom:30px}.login-header i{font-size:60px;color:var(--primary-color);margin-bottom:15px}.login-header h2{color:var(--text-dark);margin-bottom:10px}.login-header p{color:var(--text-light);font-size:14px}.header{background-color:var(--primary-color);color:var(--white);padding:15px 20px;display:flex;justify-content:space-between;align-items:center;box-shadow:0 2px 4px rgba(0,0,0,.1);position:fixed;top:0;left:0;right:0;z-index:1000}.header-left{display:flex;align-items:center;gap:15px}.menu-toggle{background:0 0;border:none;color:var(--white);font-size:24px;cursor:pointer;padding:5px 10px}.logo{font-size:24px;font-weight:700;display:flex;align-items:center;gap:10px}.header-right{display:flex;align-items:center;gap:20px}.user-info{display:flex;align-items:center;gap:10px}.user-badge{padding:5px 12px;background-color:rgba(255,255,255,.2);border-radius:15px;font-size:12px;font-weight:600}.user-avatar{width:35px;height:35px;border-radius:50%;background-color:var(--white);display:flex;align-items:center;justify-content:center;color:var(--primary-color);font-weight:700}.btn-logout{background-color:var(--danger-color);color:var(--white);border:none;padding:8px 15px;border-radius:5px;cursor:pointer;font-size:14px;transition:background-color .3s}.btn-logout:hover{background-color:#c23321}.sidebar{position:fixed;top:60px;left:0;width:250px;height:calc(100vh - 60px);background-color:var(--sidebar-bg);color:var(--white);overflow-y:auto;transition:transform .3s ease;z-index:999}.sidebar.hidden{transform:translateX(-100%)}.sidebar-menu{list-style:none;padding:20px 0}.sidebar-menu li{margin:5px 0}.sidebar-menu a{display:flex;align-items:center;gap:15px;padding:12px 20px;color:var(--white);text-decoration:none;transition:background-color .3s;cursor:pointer}.sidebar-menu a.active,.sidebar-menu a:hover{background-color:var(--sidebar-hover);border-left:3px solid var(--primary-color)}.sidebar-menu i{width:20px;text-align:center}.main-content{margin-left:250px;margin-top:60px;padding:30px;transition:margin-left .3s ease}.main-content.expanded{margin-left:0}.stats-container{display:grid;grid-template-columns:repeat(auto-fit,minmax(250px,1fr));gap:20px;margin-bottom:30px}.stat-card{background:var(--white);border-radius:8px;padding:20px;box-shadow:0 2px 10px rgba(0,0,0,.1);display:flex;justify-content:space-between;align-items:center;transition:transform .3s,box-shadow .3s}.stat-card:hover{transform:translateY(-5px);box-shadow:0 5px 20px rgba(0,0,0,.15)}.stat-info h3{font-size:14px;color:var(--text-light);margin-bottom:10px;text-transform:uppercase}.stat-info p{font-size:28px;font-weight:700;color:var(--text-dark)}.stat-icon{width:70px;height:70px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:30px;color:var(--white)}.stat-card.primary .stat-icon{background-color:var(--primary-color)}.stat-card.success .stat-icon{background-color:var(--secondary-color)}.stat-card.warning .stat-icon{background-color:var(--warning-color)}.stat-card.info .stat-icon{background-color:var(--info-color)}.box{background:var(--white);border-radius:8px;box-shadow:0 2px 10px rgba(0,0,0,.1);margin-bottom:30px;overflow:hidden}.box-header{background-color:#f7f7f7;padding:15px 20px;border-bottom:1px solid var(--border-color);display:flex;justify-content:space-between;align-items:center}.box-title{font-size:18px;font-weight:700;color:var(--text-dark);display:flex;align-items:center;gap:10px}.box-body{padding:20px}.form-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(250px,1fr));gap:20px;margin-bottom:20px}.form-group{display:flex;flex-direction:column}.form-group label{font-weight:600;margin-bottom:8px;color:var(--text-dark);font-size:14px}.form-group input,.form-group select,.form-group textarea{padding:10px 15px;border:1px solid var(--border-color);border-radius:5px;font-size:14px;transition:border-color .3s}.form-group input:focus,.form-group select:focus,.form-group textarea:focus{outline:0;border-color:var(--primary-color);box-shadow:0 0 0 3px rgba(220,20,60,.1)}.form-group textarea{resize:vertical;min-height:80px}.form-group small{margin-top:5px;font-size:12px;color:var(--text-light)}.info-box{background:#e8f4f8;border-left:4px solid var(--info-color);padding:12px 15px;margin-top:8px;border-radius:4px;font-size:13px;color:#0c5460}.checkbox-group{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px}.checkbox-item{display:flex;align-items:center;padding:8px;background:#f8f9fa;border-radius:5px;cursor:pointer;transition:all .3s}.checkbox-item:hover{background:#ffe5e5}.checkbox-item input{margin-right:8px;width:auto!important}.section-divider{margin:30px 0 20px;padding-bottom:12px;border-bottom:3px solid var(--primary-color);color:var(--primary-color);font-size:20px;font-weight:700;display:flex;align-items:center;gap:10px}.prep-race-list{margin-top:15px}.prep-race-item{background:#f8f9fa;padding:15px;border-radius:8px;margin-bottom:15px;border-left:4px solid var(--primary-color)}.prep-race-item .form-grid{margin-bottom:10px}.btn{padding:12px 30px;border:none;border-radius:5px;font-size:16px;font-weight:600;cursor:pointer;transition:all .3s;display:inline-flex;align-items:center;gap:10px;text-decoration:none}.btn-primary{background-color:var(--primary-color);color:var(--white)}.btn-primary:hover{background-color:var(--primary-dark);transform:translateY(-2px);box-shadow:0 5px 15px rgba(220,20,60,.3)}.btn-success{background-color:var(--secondary-color);color:var(--white)}.btn-success:hover{background-color:#008d4c}.btn-warning{background-color:var(--warning-color);color:var(--white)}.btn-warning:hover{background-color:#db8b0b}.btn-danger{background-color:var(--danger-color);color:var(--white)}.btn-danger:hover{background-color:#c23321}.btn-sm{padding:6px 15px;font-size:14px}.btn-secondary{background-color:#6c757d;color:var(--white)}.btn-secondary:hover{background-color:#5a6268}.plan-list{display:grid;gap:20px}.plan-card{background:var(--white);border-radius:8px;box-shadow:0 2px 10px rgba(0,0,0,.1);padding:20px;display:flex;justify-content:space-between;align-items:center;transition:transform .3s,box-shadow .3s}.plan-card:hover{transform:translateY(-3px);box-shadow:0 5px 20px rgba(0,0,0,.15)}.plan-info h3{font-size:20px;margin-bottom:10px;color:var(--text-dark)}.plan-info p{color:var(--text-light);font-size:14px;margin-bottom:5px}.plan-actions{display:flex;gap:10px;flex-wrap:wrap}.alert{padding:15px 20px;border-radius:5px;margin-bottom:20px;display:flex;align-items:center;gap:10px}.alert-info{background-color:#d1ecf1;color:#0c5460;border-left:4px solid var(--info-color)}.alert-success{background-color:#d4edda;color:#155724;border-left:4px solid var(--secondary-color)}.modal{display:none;position:fixed;z-index:2000;left:0;top:0;width:100%;height:100%;background-color:rgba(0,0,0,.5);overflow-y:auto}.modal.show{display:flex;justify-content:center;align-items:flex-start;padding:50px 20px}.modal-content{background-color:var(--white);border-radius:8px;width:100%;max-width:1200px;max-height:90vh;overflow-y:auto;box-shadow:0 10px 40px rgba(0,0,0,.3)}.modal-header{background-color:var(--primary-color);color:var(--white);padding:20px;display:flex;justify-content:space-between;align-items:center;position:sticky;top:0;z-index:10}.modal-header h2{margin:0;display:flex;align-items:center;gap:10px}.modal-close{background:0 0;border:none;color:var(--white);font-size:24px;cursor:pointer;padding:5px 10px}.modal-body{padding:30px}.period-section{margin-bottom:40px}.period-header{background:linear-gradient(135deg,var(--primary-color) 0%,var(--primary-dark) 100%);color:#fff;padding:15px 20px;border-radius:8px;font-size:20px;font-weight:700;margin-bottom:20px}.week-section{background:#f8f9fa;border-radius:8px;padding:20px;margin-bottom:20px;border-left:4px solid var(--primary-color)}.week-section.race-week{border-left:4px solid gold;background:linear-gradient(to right,#fff9e6 0%,#f8f9fa 100%)}.week-header{font-size:18px;font-weight:700;color:var(--primary-color);margin-bottom:15px;display:flex;justify-content:space-between;align-items:center}.session-card{background:#fff;padding:20px;border-radius:8px;margin-bottom:20px;box-shadow:0 2px 5px rgba(0,0,0,.05)}.session-card.race-day{border:3px solid gold;background:linear-gradient(to bottom,#fffef9 0%,#fff 100%)}.session-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:15px;padding-bottom:15px;border-bottom:2px solid #f0f0f0}.session-title{font-weight:700;color:var(--primary-color);font-size:18px}.session-distance{font-weight:700;color:var(--text-dark);font-size:16px}.motivational-message{background:linear-gradient(135deg,gold 0%,orange 100%);color:#1a1a1a;padding:20px;border-radius:8px;margin-bottom:20px;font-weight:600;font-size:16px;line-height:1.6;box-shadow:0 4px 15px rgba(255,215,0,.3);text-align:center}.session-details{margin-top:15px}.detail-section{margin-bottom:20px}.detail-section-title{font-weight:700;color:var(--primary-color);font-size:15px;margin-bottom:10px;display:flex;align-items:center;gap:8px}.detail-item{margin-bottom:12px;padding:12px;background:#f8f9fa;border-radius:5px;font-size:14px;line-height:1.6}.detail-label{font-weight:600;color:var(--primary-color);display:block;margin-bottom:5px}.purpose-box{background:linear-gradient(135deg,#e8f4f8 0%,#d1ecf1 100%);padding:15px;border-radius:8px;border-left:4px solid var(--info-color);margin-top:15px}.purpose-title{font-weight:700;color:var(--info-color);margin-bottom:8px;font-size:14px}.purpose-content{font-size:14px;color:#0c5460;line-height:1.6}.volume-summary{background:var(--dark-color);color:#fff;padding:12px 15px;border-radius:5px;text-align:center;font-weight:700;margin-top:15px;font-size:15px}.hr-zones{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px;margin-top:10px}.hr-zone{background:#f0f0f0;padding:8px 12px;border-radius:5px;text-align:center;font-size:13px}.hr-zone-label{font-weight:600;color:var(--text-dark);display:block;margin-bottom:3px}@media (max-width:768px){.sidebar{transform:translateX(-100%)}.sidebar.show{transform:translateX(0)}.main-content{margin-left:0}.header-right .user-info span{display:none}.form-grid{grid-template-columns:1fr}.stats-container{grid-template-columns:1fr}.plan-card{flex-direction:column;align-items:flex-start;gap:15px}.plan-actions{width:100%}.plan-actions button{flex:1}}.hidden{display:none!important}
|
| 13 |
</style>
|
| 14 |
-
|
|
|
|
| 15 |
<div id="loginScreen" class="login-container">
|
| 16 |
<div class="login-box">
|
| 17 |
<div class="login-header">
|
|
@@ -21,37 +20,35 @@
|
|
| 21 |
</div>
|
| 22 |
<form id="loginForm">
|
| 23 |
<div class="form-group">
|
| 24 |
-
<label
|
| 25 |
<input type="text" id="loginUsername" required placeholder="USER o ADMIN">
|
| 26 |
</div>
|
| 27 |
<div class="form-group" style="margin-top:15px">
|
| 28 |
-
<label
|
| 29 |
-
<input type="password" id="loginPassword" required
|
| 30 |
</div>
|
| 31 |
<button type="submit" class="btn btn-primary" style="width:100%;margin-top:20px;justify-content:center">
|
| 32 |
<i class="fas fa-sign-in-alt"></i> Iniciar Sesión
|
| 33 |
</button>
|
| 34 |
</form>
|
| 35 |
-
<div style="margin-top:20px;text-align:center;color:
|
| 36 |
-
<p><strong>Usuario:</strong> USER / <strong>
|
| 37 |
-
<p><strong>
|
| 38 |
</div>
|
| 39 |
</div>
|
| 40 |
</div>
|
| 41 |
|
| 42 |
<div id="appScreen" class="hidden">
|
| 43 |
<header class="header">
|
| 44 |
-
<div
|
| 45 |
<button class="menu-toggle" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
|
| 46 |
<div class="logo"><i class="fas fa-running"></i><span>Osorno Runners</span></div>
|
| 47 |
</div>
|
| 48 |
-
<div
|
| 49 |
-
<div class="user-info">
|
| 50 |
-
<span class="user-badge" id="userRole">USUARIO</span>
|
| 51 |
<span id="currentUserName">Usuario</span>
|
| 52 |
-
<
|
| 53 |
-
</
|
| 54 |
-
<
|
| 55 |
</div>
|
| 56 |
</header>
|
| 57 |
|
|
@@ -65,55 +62,37 @@
|
|
| 65 |
|
| 66 |
<main class="main-content" id="mainContent">
|
| 67 |
<section id="dashboard-section">
|
| 68 |
-
<h1 style="margin-bottom:30px
|
| 69 |
<div class="stats-container">
|
| 70 |
<div class="stat-card primary">
|
| 71 |
-
<div
|
| 72 |
<div class="stat-icon"><i class="fas fa-list-alt"></i></div>
|
| 73 |
</div>
|
| 74 |
<div class="stat-card success">
|
| 75 |
-
<div
|
| 76 |
<div class="stat-icon"><i class="fas fa-users"></i></div>
|
| 77 |
</div>
|
| 78 |
-
<div class="stat-card warning">
|
| 79 |
-
<div class="stat-info"><h3>Semanas Totales</h3><p id="stat-weeks">0</p></div>
|
| 80 |
-
<div class="stat-icon"><i class="fas fa-calendar-week"></i></div>
|
| 81 |
-
</div>
|
| 82 |
-
<div class="stat-card info">
|
| 83 |
-
<div class="stat-info"><h3>Maratones</h3><p id="stat-marathons">0</p></div>
|
| 84 |
-
<div class="stat-icon"><i class="fas fa-medal"></i></div>
|
| 85 |
-
</div>
|
| 86 |
-
</div>
|
| 87 |
-
<div class="alert alert-info">
|
| 88 |
-
<i class="fas fa-info-circle"></i>
|
| 89 |
-
<span>Bienvenido al Sistema de Osorno Runners. <span id="dashboardMessage">Administra los planes de entrenamiento.</span></span>
|
| 90 |
-
</div>
|
| 91 |
-
<div class="box">
|
| 92 |
-
<div class="box-header"><h3 class="box-title"><i class="fas fa-rocket"></i> Inicio Rápido</h3></div>
|
| 93 |
-
<div class="box-body">
|
| 94 |
-
<p style="margin-bottom:20px;color:var(--text-light)"><span id="quickStartText">Crea planes personalizados de entrenamiento.</span></p>
|
| 95 |
-
<button class="btn btn-primary" id="quickStartBtn" onclick="showSection('new-plan')"><i class="fas fa-plus"></i> Crear Nuevo Plan</button>
|
| 96 |
-
</div>
|
| 97 |
</div>
|
|
|
|
| 98 |
</section>
|
| 99 |
|
| 100 |
<section id="new-plan-section" class="hidden">
|
| 101 |
<h1 style="margin-bottom:30px"><i class="fas fa-plus-circle"></i> Crear Nuevo Plan</h1>
|
| 102 |
<div class="box">
|
| 103 |
-
<div class="box-header"><h3
|
| 104 |
<div class="box-body">
|
| 105 |
<form id="trainingForm">
|
| 106 |
<div class="form-grid">
|
| 107 |
<div class="form-group">
|
| 108 |
-
<label
|
| 109 |
-
<input type="text" id="athleteName" required
|
| 110 |
</div>
|
| 111 |
<div class="form-group">
|
| 112 |
-
<label
|
| 113 |
-
<input type="number" id="athleteAge" required
|
| 114 |
</div>
|
| 115 |
<div class="form-group">
|
| 116 |
-
<label
|
| 117 |
<select id="experience" required>
|
| 118 |
<option value="">Selecciona...</option>
|
| 119 |
<option value="principiante">Principiante</option>
|
|
@@ -125,40 +104,37 @@
|
|
| 125 |
<div class="section-divider"><i class="fas fa-weight"></i> Antropometría</div>
|
| 126 |
<div class="form-grid">
|
| 127 |
<div class="form-group">
|
| 128 |
-
<label
|
| 129 |
-
<input type="number" id="weight" required
|
| 130 |
</div>
|
| 131 |
<div class="form-group">
|
| 132 |
-
<label
|
| 133 |
-
<input type="number" id="height" required
|
| 134 |
</div>
|
| 135 |
<div class="form-group">
|
| 136 |
-
<label>
|
| 137 |
-
<input type="text" id="imc" readonly
|
| 138 |
-
<small id="imcCategory"></small>
|
| 139 |
</div>
|
| 140 |
</div>
|
| 141 |
<div class="section-divider"><i class="fas fa-heartbeat"></i> Datos Fisiológicos</div>
|
| 142 |
<div class="form-grid">
|
| 143 |
<div class="form-group">
|
| 144 |
-
<label
|
| 145 |
-
<input type="number" id="hrMax" required
|
| 146 |
-
<small>Sugerida: 220 - edad = <span id="suggestedHrMax">--</span> bpm</small>
|
| 147 |
</div>
|
| 148 |
<div class="form-group">
|
| 149 |
-
<label
|
| 150 |
-
<input type="number" id="hrRest" required
|
| 151 |
</div>
|
| 152 |
<div class="form-group">
|
| 153 |
-
<label
|
| 154 |
-
<input type="number" id="vo2max"
|
| 155 |
-
<small>Opcional</small>
|
| 156 |
</div>
|
| 157 |
</div>
|
| 158 |
-
<div class="section-divider"><i class="fas fa-bullseye"></i> Objetivo
|
| 159 |
<div class="form-grid">
|
| 160 |
<div class="form-group">
|
| 161 |
-
<label
|
| 162 |
<select id="distance" required>
|
| 163 |
<option value="">Selecciona...</option>
|
| 164 |
<option value="5K">5K</option>
|
|
@@ -168,11 +144,11 @@
|
|
| 168 |
</select>
|
| 169 |
</div>
|
| 170 |
<div class="form-group">
|
| 171 |
-
<label
|
| 172 |
-
<input type="text" id="targetPace" required placeholder="
|
| 173 |
</div>
|
| 174 |
<div class="form-group">
|
| 175 |
-
<label
|
| 176 |
<input type="date" id="raceDate" required>
|
| 177 |
</div>
|
| 178 |
</div>
|
|
@@ -189,28 +165,8 @@
|
|
| 189 |
<label class="checkbox-item"><input type="checkbox" name="trainingDays" value="domingo">Domingo</label>
|
| 190 |
</div>
|
| 191 |
</div>
|
| 192 |
-
<div
|
| 193 |
-
<div class="form-group">
|
| 194 |
-
<label>Actividades Complementarias</label>
|
| 195 |
-
<div class="checkbox-group">
|
| 196 |
-
<label class="checkbox-item"><input type="checkbox" name="crossTraining" value="ciclismo">🚴 Ciclismo</label>
|
| 197 |
-
<label class="checkbox-item"><input type="checkbox" name="crossTraining" value="natacion">🏊 Natación</label>
|
| 198 |
-
<label class="checkbox-item"><input type="checkbox" name="crossTraining" value="gimnasio">💪 Gimnasio</label>
|
| 199 |
-
<label class="checkbox-item"><input type="checkbox" name="crossTraining" value="yoga">🧘 Yoga</label>
|
| 200 |
-
<label class="checkbox-item"><input type="checkbox" name="crossTraining" value="pilates">🤸 Pilates</label>
|
| 201 |
-
<label class="checkbox-item"><input type="checkbox" name="crossTraining" value="spinning">🚴 Spinning</label>
|
| 202 |
-
</div>
|
| 203 |
-
</div>
|
| 204 |
-
<div class="section-divider"><i class="fas fa-trophy"></i> Carreras Preparatorias</div>
|
| 205 |
-
<div id="prepRacesList" class="prep-race-list"></div>
|
| 206 |
-
<button type="button" class="btn btn-secondary btn-sm" onclick="addPrepRace()"><i class="fas fa-plus"></i> Agregar Carrera</button>
|
| 207 |
-
<div class="form-group" style="margin-top:30px">
|
| 208 |
-
<label for="notes"><i class="fas fa-sticky-note"></i> Notas</label>
|
| 209 |
-
<textarea id="notes" placeholder="Notas adicionales"></textarea>
|
| 210 |
-
</div>
|
| 211 |
-
<div style="margin-top:30px;display:flex;gap:15px;flex-wrap:wrap">
|
| 212 |
<button type="submit" class="btn btn-success"><i class="fas fa-check"></i> Generar Plan</button>
|
| 213 |
-
<button type="button" class="btn btn-primary" onclick="resetForm()"><i class="fas fa-redo"></i> Limpiar</button>
|
| 214 |
</div>
|
| 215 |
</form>
|
| 216 |
</div>
|
|
@@ -221,1176 +177,14 @@
|
|
| 221 |
<h1 style="margin-bottom:30px"><i class="fas fa-list-ul"></i> Planes de Entrenamiento</h1>
|
| 222 |
<div id="planListContent" class="plan-list"></div>
|
| 223 |
<div id="noPlanPlaceholder" class="hidden">
|
| 224 |
-
<div class="alert alert-info"><i class="fas fa-info-circle"></i><span>No hay planes disponibles
|
| 225 |
</div>
|
| 226 |
</section>
|
| 227 |
</main>
|
| 228 |
</div>
|
| 229 |
|
| 230 |
-
<div id="planDetailModal" class="modal">
|
| 231 |
-
<div class="modal-content">
|
| 232 |
-
<div class="modal-header">
|
| 233 |
-
<h2><i class="fas fa-calendar-alt"></i> <span id="modalTitle">Detalle del Plan</span></h2>
|
| 234 |
-
<button class="modal-close" onclick="closeModal()"><i class="fas fa-times"></i></button>
|
| 235 |
-
</div>
|
| 236 |
-
<div class="modal-body" id="modalPlanContent"></div>
|
| 237 |
-
</div>
|
| 238 |
-
</div>
|
| 239 |
-
|
| 240 |
<script>
|
| 241 |
-
let currentUser = null,
|
| 242 |
-
prepRaceCounter = 0;
|
| 243 |
-
|
| 244 |
-
// Objeto de usuarios con credenciales y roles
|
| 245 |
-
const users = {
|
| 246 |
-
USER: {
|
| 247 |
-
password: '123',
|
| 248 |
-
role: 'user',
|
| 249 |
-
name: 'Usuario'
|
| 250 |
-
},
|
| 251 |
-
ADMIN: {
|
| 252 |
-
password: '123',
|
| 253 |
-
role: 'admin',
|
| 254 |
-
name: 'Administrador'
|
| 255 |
-
}
|
| 256 |
-
};
|
| 257 |
-
|
| 258 |
-
/**
|
| 259 |
-
* Manejador del formulario de inicio de sesión
|
| 260 |
-
*/
|
| 261 |
-
document.getElementById('loginForm').addEventListener('submit', function (e) {
|
| 262 |
-
e.preventDefault();
|
| 263 |
-
|
| 264 |
-
const username = document.getElementById('loginUsername').value.toUpperCase();
|
| 265 |
-
const password = document.getElementById('loginPassword').value;
|
| 266 |
-
|
| 267 |
-
if (users[username] && users[username].password === password) {
|
| 268 |
-
currentUser = {
|
| 269 |
-
username: username,
|
| 270 |
-
role: users[username].role,
|
| 271 |
-
name: users[username].name
|
| 272 |
-
};
|
| 273 |
-
|
| 274 |
-
// Ocultar pantalla de login y mostrar la app
|
| 275 |
-
document.getElementById('loginScreen').classList.add('hidden');
|
| 276 |
-
document.getElementById('appScreen').classList.remove('hidden');
|
| 277 |
-
|
| 278 |
-
// Actualizar datos del usuario en el dashboard
|
| 279 |
-
document.getElementById('currentUserName').textContent = currentUser.name;
|
| 280 |
-
document.getElementById('userRole').textContent = currentUser.role === 'admin' ? 'ADMINISTRADOR' : 'USUARIO';
|
| 281 |
-
|
| 282 |
-
// Lógica de visualización y botones según el rol
|
| 283 |
-
if (currentUser.role === 'user') {
|
| 284 |
-
document.getElementById('menu-new-plan').style.display = 'none';
|
| 285 |
-
document.getElementById('dashboardMessage').textContent = 'Consulta los planes de entrenamiento.';
|
| 286 |
-
document.getElementById('quickStartText').textContent = 'Revisa los planes disponibles.';
|
| 287 |
-
document.getElementById('quickStartBtn').innerHTML = '<i class="fas fa-list"></i> Ver Planes';
|
| 288 |
-
document.getElementById('quickStartBtn').onclick = function () {
|
| 289 |
-
showSection('plan-list')
|
| 290 |
-
};
|
| 291 |
-
} else { // admin role
|
| 292 |
-
document.getElementById('menu-new-plan').style.display = 'block';
|
| 293 |
-
document.getElementById('quickStartBtn').onclick = function () {
|
| 294 |
-
showSection('new-plan')
|
| 295 |
-
};
|
| 296 |
-
}
|
| 297 |
-
|
| 298 |
-
updateDashboard();
|
| 299 |
-
loadPlanList();
|
| 300 |
-
} else {
|
| 301 |
-
alert('Usuario o contraseña incorrectos')
|
| 302 |
-
}
|
| 303 |
-
});
|
| 304 |
-
|
| 305 |
-
/**
|
| 306 |
-
* Función para cerrar sesión
|
| 307 |
-
*/
|
| 308 |
-
function logout() {
|
| 309 |
-
currentUser = null;
|
| 310 |
-
document.getElementById('appScreen').classList.add('hidden');
|
| 311 |
-
document.getElementById('loginScreen').classList.remove('hidden');
|
| 312 |
-
document.getElementById('loginForm').reset();
|
| 313 |
-
showSection('dashboard');
|
| 314 |
-
}
|
| 315 |
-
|
| 316 |
-
/**
|
| 317 |
-
* Función para mostrar/ocultar la barra lateral (sidebar)
|
| 318 |
-
*/
|
| 319 |
-
function toggleSidebar() {
|
| 320 |
-
const sidebar = document.getElementById('sidebar');
|
| 321 |
-
const mainContent = document.getElementById('mainContent');
|
| 322 |
-
if (window.innerWidth <= 768) {
|
| 323 |
-
sidebar.classList.toggle('show');
|
| 324 |
-
} else {
|
| 325 |
-
sidebar.classList.toggle('hidden');
|
| 326 |
-
mainContent.classList.toggle('expanded');
|
| 327 |
-
}
|
| 328 |
-
}
|
| 329 |
-
|
| 330 |
-
/**
|
| 331 |
-
* Muestra la sección de la aplicación solicitada
|
| 332 |
-
* @param {string} section - El ID de la sección a mostrar
|
| 333 |
-
*/
|
| 334 |
-
function showSection(section) {
|
| 335 |
-
// Ocultar todas las secciones
|
| 336 |
-
document.querySelectorAll('main > section').forEach(s => s.classList.add('hidden'));
|
| 337 |
-
// Quitar 'active' de todos los enlaces de menú
|
| 338 |
-
document.querySelectorAll('.sidebar-menu a').forEach(a => a.classList.remove('active'));
|
| 339 |
-
|
| 340 |
-
// Mostrar la sección específica
|
| 341 |
-
if (section === 'dashboard') {
|
| 342 |
-
document.getElementById('dashboard-section').classList.remove('hidden');
|
| 343 |
-
} else if (section === 'new-plan') {
|
| 344 |
-
if (currentUser && currentUser.role === 'admin') {
|
| 345 |
-
document.getElementById('new-plan-section').classList.remove('hidden');
|
| 346 |
-
} else {
|
| 347 |
-
alert('Solo los administradores pueden crear planes');
|
| 348 |
-
return;
|
| 349 |
-
}
|
| 350 |
-
} else if (section === 'plan-list') {
|
| 351 |
-
document.getElementById('plan-list-section').classList.remove('hidden');
|
| 352 |
-
loadPlanList();
|
| 353 |
-
}
|
| 354 |
-
|
| 355 |
-
// Activar el enlace del menú correspondiente
|
| 356 |
-
if (window.event && window.event.target) {
|
| 357 |
-
const link = window.event.target.closest('a');
|
| 358 |
-
if (link) {
|
| 359 |
-
link.classList.add('active');
|
| 360 |
-
}
|
| 361 |
-
}
|
| 362 |
-
}
|
| 363 |
-
|
| 364 |
-
// --- Funciones de almacenamiento y gestión de planes ---
|
| 365 |
-
|
| 366 |
-
/**
|
| 367 |
-
* Obtiene los planes almacenados en LocalStorage
|
| 368 |
-
* @returns {Array} Lista de planes
|
| 369 |
-
*/
|
| 370 |
-
function getPlans() {
|
| 371 |
-
const plans = localStorage.getItem('osornoRunnerPlans');
|
| 372 |
-
return plans ? JSON.parse(plans) : [];
|
| 373 |
-
}
|
| 374 |
-
|
| 375 |
-
/**
|
| 376 |
-
* Guarda un nuevo plan en LocalStorage
|
| 377 |
-
* @param {object} plan - El objeto plan a guardar
|
| 378 |
-
*/
|
| 379 |
-
function savePlan(plan) {
|
| 380 |
-
const plans = getPlans();
|
| 381 |
-
plans.push(plan);
|
| 382 |
-
localStorage.setItem('osornoRunnerPlans', JSON.stringify(plans));
|
| 383 |
-
}
|
| 384 |
-
|
| 385 |
-
/**
|
| 386 |
-
* Elimina un plan por su ID
|
| 387 |
-
* @param {string} planId - El ID del plan a eliminar
|
| 388 |
-
*/
|
| 389 |
-
function deletePlan(planId) {
|
| 390 |
-
const plans = getPlans();
|
| 391 |
-
const filtered = plans.filter(p => p.id !== planId);
|
| 392 |
-
localStorage.setItem('osornoRunnerPlans', JSON.stringify(filtered));
|
| 393 |
-
}
|
| 394 |
-
|
| 395 |
-
// --- Funciones del formulario 'Nuevo Plan' ---
|
| 396 |
-
|
| 397 |
-
/**
|
| 398 |
-
* Calcula y muestra la Frecuencia Cardíaca Máxima sugerida (220 - edad)
|
| 399 |
-
*/
|
| 400 |
-
document.getElementById('athleteAge').addEventListener('input', function () {
|
| 401 |
-
const age = parseInt(this.value);
|
| 402 |
-
if (age && age >= 10 && age <= 100) {
|
| 403 |
-
const suggestedHR = 220 - age;
|
| 404 |
-
document.getElementById('suggestedHrMax').textContent = suggestedHR;
|
| 405 |
-
} else {
|
| 406 |
-
document.getElementById('suggestedHrMax').textContent = '--';
|
| 407 |
-
}
|
| 408 |
-
});
|
| 409 |
-
|
| 410 |
-
/**
|
| 411 |
-
* Calcula el Índice de Masa Corporal (IMC)
|
| 412 |
-
*/
|
| 413 |
-
function calculateIMC() {
|
| 414 |
-
const weight = parseFloat(document.getElementById('weight').value);
|
| 415 |
-
const height = parseFloat(document.getElementById('height').value);
|
| 416 |
-
|
| 417 |
-
if (weight && height && height > 0) {
|
| 418 |
-
const heightM = height / 100;
|
| 419 |
-
const imc = weight / (heightM * heightM);
|
| 420 |
-
document.getElementById('imc').value = imc.toFixed(1);
|
| 421 |
-
|
| 422 |
-
let category = '',
|
| 423 |
-
color = '';
|
| 424 |
-
if (imc < 18.5) {
|
| 425 |
-
category = 'Bajo peso';
|
| 426 |
-
color = '#17a2b8';
|
| 427 |
-
} else if (imc < 25) {
|
| 428 |
-
category = 'Peso normal';
|
| 429 |
-
color = '#28a745';
|
| 430 |
-
} else if (imc < 30) {
|
| 431 |
-
category = 'Sobrepeso';
|
| 432 |
-
color = '#ffc107';
|
| 433 |
-
} else {
|
| 434 |
-
category = 'Obesidad';
|
| 435 |
-
color = '#dc3545';
|
| 436 |
-
}
|
| 437 |
-
document.getElementById('imcCategory').innerHTML = `<strong style="color: ${color};">${category}</strong>`;
|
| 438 |
-
} else {
|
| 439 |
-
document.getElementById('imc').value = '';
|
| 440 |
-
document.getElementById('imcCategory').textContent = '';
|
| 441 |
-
}
|
| 442 |
-
}
|
| 443 |
-
|
| 444 |
-
/**
|
| 445 |
-
* Añade un nuevo campo para Carrera Preparatoria en el formulario
|
| 446 |
-
*/
|
| 447 |
-
function addPrepRace() {
|
| 448 |
-
prepRaceCounter++;
|
| 449 |
-
const raceHtml = `
|
| 450 |
-
<div class="prep-race-item" id="prepRace${prepRaceCounter}">
|
| 451 |
-
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px">
|
| 452 |
-
<h4 style="margin:0;color:var(--primary-color)"><i class="fas fa-trophy"></i> Carrera #${prepRaceCounter}</h4>
|
| 453 |
-
<button type="button" class="btn btn-danger btn-sm" onclick="removePrepRace(${prepRaceCounter})"><i class="fas fa-trash"></i></button>
|
| 454 |
-
</div>
|
| 455 |
-
<div class="form-grid">
|
| 456 |
-
<div class="form-group">
|
| 457 |
-
<label>Nombre</label>
|
| 458 |
-
<input type="text" name="prepRaceName[]" placeholder="Ej: 10K Los Muermos" class="prep-race-name">
|
| 459 |
-
</div>
|
| 460 |
-
<div class="form-group">
|
| 461 |
-
<label>Distancia</label>
|
| 462 |
-
<select name="prepRaceDistance[]" class="prep-race-distance">
|
| 463 |
-
<option value="5K">5K</option>
|
| 464 |
-
<option value="10K">10K</option>
|
| 465 |
-
<option value="15K">15K</option>
|
| 466 |
-
<option value="21K">21K</option>
|
| 467 |
-
</select>
|
| 468 |
-
</div>
|
| 469 |
-
<div class="form-group">
|
| 470 |
-
<label>Fecha</label>
|
| 471 |
-
<input type="date" name="prepRaceDate[]" class="prep-race-date">
|
| 472 |
-
</div>
|
| 473 |
-
</div>
|
| 474 |
-
</div>`;
|
| 475 |
-
document.getElementById('prepRacesList').insertAdjacentHTML('beforeend', raceHtml);
|
| 476 |
-
}
|
| 477 |
-
|
| 478 |
-
/**
|
| 479 |
-
* Elimina un campo de Carrera Preparatoria
|
| 480 |
-
* @param {number} id - El ID del contador de la carrera a eliminar
|
| 481 |
-
*/
|
| 482 |
-
function removePrepRace(id) {
|
| 483 |
-
const element = document.getElementById(`prepRace${id}`);
|
| 484 |
-
if (element) {
|
| 485 |
-
element.remove();
|
| 486 |
-
}
|
| 487 |
-
}
|
| 488 |
-
|
| 489 |
-
// --- Generación del Plan de Entrenamiento ---
|
| 490 |
-
|
| 491 |
-
document.getElementById('trainingForm').addEventListener('submit', function (e) {
|
| 492 |
-
e.preventDefault();
|
| 493 |
-
generateTrainingPlan();
|
| 494 |
-
});
|
| 495 |
-
|
| 496 |
-
/**
|
| 497 |
-
* Recolecta datos del formulario y genera el plan de entrenamiento completo
|
| 498 |
-
*/
|
| 499 |
-
function generateTrainingPlan() {
|
| 500 |
-
const RAG_SERVER_URL = "https://servidorraw.onrender.com"; // <--- CAMBIAR POR LA URL REAL DEL SERVIDOR
|
| 501 |
-
|
| 502 |
-
// 1. Recolección de Datos (Se mantiene la lógica existente)
|
| 503 |
-
const athleteName = document.getElementById('athleteName').value;
|
| 504 |
-
const athleteAge = parseInt(document.getElementById('athleteAge').value);
|
| 505 |
-
const experience = document.getElementById('experience').value;
|
| 506 |
-
const distance = document.getElementById('distance').value;
|
| 507 |
-
const targetPace = document.getElementById('targetPace').value;
|
| 508 |
-
const raceDate = document.getElementById('raceDate').value;
|
| 509 |
-
const hrMax = parseInt(document.getElementById('hrMax').value);
|
| 510 |
-
const hrRest = parseInt(document.getElementById('hrRest').value);
|
| 511 |
-
const vo2Max = parseFloat(document.getElementById('vo2Max').value);
|
| 512 |
-
const imc = document.getElementById('imc').value;
|
| 513 |
-
const trainingDays = Array.from(document.querySelectorAll('input[name="trainingDays"]:checked')).map(cb => cb.value);
|
| 514 |
-
const crossTraining = Array.from(document.querySelectorAll('input[name="crossTraining"]:checked')).map(cb => cb.value);
|
| 515 |
-
|
| 516 |
-
// Recolección de Carreras Preparatorias
|
| 517 |
-
const prepRaces = [];
|
| 518 |
-
document.querySelectorAll('.prep-race-item').forEach(item => {
|
| 519 |
-
const raceName = item.querySelector('.prep-race-name').value;
|
| 520 |
-
const raceDistance = item.querySelector('.prep-race-distance').value;
|
| 521 |
-
const raceDate = item.querySelector('.prep-race-date').value;
|
| 522 |
-
if (raceName && raceDate && raceDistance) {
|
| 523 |
-
prepRaces.push({ name: raceName, distance: raceDistance, date: raceDate });
|
| 524 |
-
}
|
| 525 |
-
});
|
| 526 |
-
|
| 527 |
-
// 2. Construir el objeto de datos para el servidor RAG
|
| 528 |
-
const formData = {
|
| 529 |
-
athleteName: athleteName,
|
| 530 |
-
athleteAge: athleteAge,
|
| 531 |
-
experience: experience,
|
| 532 |
-
distance: distance,
|
| 533 |
-
targetPace: targetPace,
|
| 534 |
-
raceDate: raceDate,
|
| 535 |
-
hrMax: hrMax,
|
| 536 |
-
hrRest: hrRest,
|
| 537 |
-
vo2Max: vo2Max,
|
| 538 |
-
imc: imc,
|
| 539 |
-
trainingDays: trainingDays,
|
| 540 |
-
crossTraining: crossTraining,
|
| 541 |
-
prepRaces: prepRaces
|
| 542 |
-
};
|
| 543 |
-
|
| 544 |
-
const loadingMsg = document.createElement('div');
|
| 545 |
-
loadingMsg.id = 'loadingMessage';
|
| 546 |
-
loadingMsg.textContent = '🧠 Generando plan con IA de Running...';
|
| 547 |
-
document.body.appendChild(loadingMsg);
|
| 548 |
-
|
| 549 |
-
// 3. Llamada API al servidor RAG
|
| 550 |
-
fetch(RAG_SERVER_URL, {
|
| 551 |
-
method: 'POST',
|
| 552 |
-
headers: {
|
| 553 |
-
'Content-Type': 'application/json',
|
| 554 |
-
// Si tu servidor RAG requiere autenticación (ej. un API Key), agrégala aquí
|
| 555 |
-
},
|
| 556 |
-
body: JSON.stringify(formData)
|
| 557 |
-
})
|
| 558 |
-
.then(response => {
|
| 559 |
-
// Manejo de errores de la respuesta HTTP
|
| 560 |
-
if (!response.ok) {
|
| 561 |
-
return response.json().then(errorData => {
|
| 562 |
-
throw new Error(errorData.message || `Error ${response.status}: Fallo en el servidor RAG.`);
|
| 563 |
-
});
|
| 564 |
-
}
|
| 565 |
-
return response.json();
|
| 566 |
-
})
|
| 567 |
-
.then(planFromAI => {
|
| 568 |
-
// 4. Procesar la respuesta del servidor RAG
|
| 569 |
-
document.body.removeChild(loadingMsg);
|
| 570 |
-
|
| 571 |
-
// La respuesta de la IA debe tener la estructura 'plan' esperada por savePlan()
|
| 572 |
-
if (planFromAI && planFromAI.id) {
|
| 573 |
-
savePlan(planFromAI);
|
| 574 |
-
alert('¡Plan creado por la IA con éxito!');
|
| 575 |
-
resetForm();
|
| 576 |
-
updateDashboard();
|
| 577 |
-
showSection('plan-list');
|
| 578 |
-
} else {
|
| 579 |
-
throw new Error('La IA no devolvió un plan válido. Estructura JSON incorrecta.');
|
| 580 |
-
}
|
| 581 |
-
})
|
| 582 |
-
.catch(error => {
|
| 583 |
-
// Manejo de errores, incluyendo problemas de conexión o errores en la IA
|
| 584 |
-
document.body.removeChild(loadingMsg);
|
| 585 |
-
console.error('Error al generar el plan con RAG:', error);
|
| 586 |
-
alert(`Fallo al generar el plan con IA. Asegúrate de que el servidor RAG esté activo. Detalle: ${error.message}`);
|
| 587 |
-
});
|
| 588 |
-
}
|
| 589 |
-
|
| 590 |
-
/**
|
| 591 |
-
* Calcula el número total de semanas de entrenamiento según distancia y experiencia
|
| 592 |
-
*/
|
| 593 |
-
function calculateWeeks(distance, experience) {
|
| 594 |
-
const weeksMap = {
|
| 595 |
-
'5K': {
|
| 596 |
-
principiante: 8,
|
| 597 |
-
intermedio: 6,
|
| 598 |
-
avanzado: 6
|
| 599 |
-
},
|
| 600 |
-
'10K': {
|
| 601 |
-
principiante: 10,
|
| 602 |
-
intermedio: 8,
|
| 603 |
-
avanzado: 8
|
| 604 |
-
},
|
| 605 |
-
'21K': {
|
| 606 |
-
principiante: 16,
|
| 607 |
-
intermedio: 14,
|
| 608 |
-
avanzado: 12
|
| 609 |
-
},
|
| 610 |
-
'42K': {
|
| 611 |
-
principiante: 24,
|
| 612 |
-
intermedio: 20,
|
| 613 |
-
avanzado: 18
|
| 614 |
-
}
|
| 615 |
-
};
|
| 616 |
-
return weeksMap[distance][experience];
|
| 617 |
-
}
|
| 618 |
-
|
| 619 |
-
/**
|
| 620 |
-
* Genera el plan semanal (estructura por semanas y períodos)
|
| 621 |
-
*/
|
| 622 |
-
function generateWeeklyPlans(distance, experience, totalWeeks, trainingDays, targetPace, athleteName, hrMax, hrRest, crossTraining, prepRaces, mainRaceDate) {
|
| 623 |
-
const plans = [];
|
| 624 |
-
|
| 625 |
-
// Cálculo de períodos
|
| 626 |
-
const basePeriod = Math.ceil(.35 * totalWeeks);
|
| 627 |
-
const specificPeriod = Math.ceil(.4 * totalWeeks);
|
| 628 |
-
const competitionPeriod = Math.ceil(.15 * totalWeeks);
|
| 629 |
-
const transitionPeriod = totalWeeks - basePeriod - specificPeriod - competitionPeriod;
|
| 630 |
-
|
| 631 |
-
let currentPeriod = 'basico';
|
| 632 |
-
|
| 633 |
-
// Cálculo de la fecha de inicio
|
| 634 |
-
const mainRaceDateObj = new Date(mainRaceDate);
|
| 635 |
-
const startDate = new Date(mainRaceDateObj);
|
| 636 |
-
startDate.setDate(startDate.getDate() - 7 * totalWeeks);
|
| 637 |
-
|
| 638 |
-
for (let week = 1; week <= totalWeeks; week++) {
|
| 639 |
-
const weekStart = new Date(startDate);
|
| 640 |
-
weekStart.setDate(weekStart.getDate() + 7 * (week - 1));
|
| 641 |
-
|
| 642 |
-
// Determinar el período
|
| 643 |
-
if (week > basePeriod + specificPeriod + competitionPeriod) {
|
| 644 |
-
currentPeriod = 'transicion';
|
| 645 |
-
} else if (week > basePeriod + specificPeriod) {
|
| 646 |
-
currentPeriod = 'competencia';
|
| 647 |
-
} else if (week > basePeriod) {
|
| 648 |
-
currentPeriod = 'especifico';
|
| 649 |
-
}
|
| 650 |
-
|
| 651 |
-
const isRaceWeek = week === totalWeeks;
|
| 652 |
-
const isRecoveryWeek = week % 4 == 0 && !isRaceWeek;
|
| 653 |
-
|
| 654 |
-
// Verificar si hay carrera preparatoria esta semana
|
| 655 |
-
let prepRaceThisWeek = null;
|
| 656 |
-
prepRaces.forEach(race => {
|
| 657 |
-
const raceDateObj = new Date(race.date);
|
| 658 |
-
const weekEnd = new Date(weekStart);
|
| 659 |
-
weekEnd.setDate(weekEnd.getDate() + 7);
|
| 660 |
-
if (raceDateObj >= weekStart && raceDateObj < weekEnd) {
|
| 661 |
-
prepRaceThisWeek = race;
|
| 662 |
-
}
|
| 663 |
-
});
|
| 664 |
-
|
| 665 |
-
// Generar sesiones de entrenamiento
|
| 666 |
-
const sessions = generateWeekSessions(week, totalWeeks, trainingDays, currentPeriod, isRaceWeek, isRecoveryWeek, distance, targetPace, experience, athleteName, hrMax, hrRest, crossTraining, prepRaceThisWeek);
|
| 667 |
-
|
| 668 |
-
// Calcular kilómetros totales de la semana
|
| 669 |
-
const totalKm = sessions.reduce((sum, s) => {
|
| 670 |
-
const km = parseFloat(s.distance.replace(' km', '').replace('km', '') || 0);
|
| 671 |
-
return sum + km;
|
| 672 |
-
}, 0);
|
| 673 |
-
|
| 674 |
-
plans.push({
|
| 675 |
-
week: week,
|
| 676 |
-
period: currentPeriod,
|
| 677 |
-
isRaceWeek: isRaceWeek,
|
| 678 |
-
isRecoveryWeek: isRecoveryWeek,
|
| 679 |
-
prepRace: prepRaceThisWeek,
|
| 680 |
-
sessions: sessions,
|
| 681 |
-
totalKm: Math.round(totalKm)
|
| 682 |
-
});
|
| 683 |
-
}
|
| 684 |
-
return plans;
|
| 685 |
-
}
|
| 686 |
-
|
| 687 |
-
/**
|
| 688 |
-
* Genera las sesiones de entrenamiento para una semana específica
|
| 689 |
-
*/
|
| 690 |
-
function generateWeekSessions(week, totalWeeks, trainingDays, period, isRaceWeek, isRecoveryWeek, distance, targetPace, experience, athleteName, hrMax, hrRest, crossTraining, prepRace) {
|
| 691 |
-
const sessions = [];
|
| 692 |
-
|
| 693 |
-
if (isRaceWeek) {
|
| 694 |
-
// Semana de la carrera objetivo (Tapering final)
|
| 695 |
-
trainingDays.forEach((day, index) => {
|
| 696 |
-
if (index === trainingDays.length - 1) { // Último día es la carrera
|
| 697 |
-
sessions.push(createRaceDay(day, distance, targetPace, athleteName, hrMax, hrRest));
|
| 698 |
-
} else if (index === trainingDays.length - 2) { // Penúltimo día es activación
|
| 699 |
-
sessions.push(createPreRaceSession(day, hrMax, hrRest, athleteName));
|
| 700 |
-
} else { // Otros días son recuperación/taper
|
| 701 |
-
sessions.push(createTaperSession(day, hrMax, hrRest));
|
| 702 |
-
}
|
| 703 |
-
});
|
| 704 |
-
} else if (prepRace) {
|
| 705 |
-
// Semana con carrera preparatoria
|
| 706 |
-
trainingDays.forEach((day, index) => {
|
| 707 |
-
if (index === trainingDays.length - 1) { // Último día (simulación de carrera)
|
| 708 |
-
sessions.push(createPrepRaceDay(day, prepRace, targetPace, hrMax, hrRest));
|
| 709 |
-
} else if (index === trainingDays.length - 2) { // Penúltimo día es activación
|
| 710 |
-
sessions.push(createPreRaceSession(day, hrMax, hrRest, athleteName));
|
| 711 |
-
} else { // Otros días son sesiones regulares
|
| 712 |
-
const baseKm = getBaseKm(distance, experience, week, totalWeeks);
|
| 713 |
-
const session = createRegularSession(day, index, trainingDays.length, period, baseKm, targetPace, hrMax, hrRest, crossTraining, isRecoveryWeek);
|
| 714 |
-
sessions.push(session);
|
| 715 |
-
}
|
| 716 |
-
});
|
| 717 |
-
} else {
|
| 718 |
-
// Semana normal
|
| 719 |
-
const baseKm = getBaseKm(distance, experience, week, totalWeeks);
|
| 720 |
-
trainingDays.forEach((day, index) => {
|
| 721 |
-
const session = createRegularSession(day, index, trainingDays.length, period, baseKm, targetPace, hrMax, hrRest, crossTraining, isRecoveryWeek);
|
| 722 |
-
sessions.push(session);
|
| 723 |
-
});
|
| 724 |
-
}
|
| 725 |
-
return sessions;
|
| 726 |
-
}
|
| 727 |
-
|
| 728 |
-
// --- Funciones de creación de sesiones específicas ---
|
| 729 |
-
|
| 730 |
-
/**
|
| 731 |
-
* Crea la sesión del día de la carrera objetivo
|
| 732 |
-
*/
|
| 733 |
-
function createRaceDay(day, distance, targetPace, athleteName, hrMax, hrRest) {
|
| 734 |
-
const motivationalMessages = {
|
| 735 |
-
'5K': `¡${athleteName}, hoy es tu día! Los 5K son pura potencia. ¡Dalo TODO! 🏃♂️💪🔥`,
|
| 736 |
-
'10K': `¡${athleteName}, llegó el momento! Confía en tu entrenamiento. ¡Tu mejor versión está a punto de cruzar esa meta! 🏃♂️✨`,
|
| 737 |
-
'21K': `¡${athleteName}, hoy escribes tu historia! Los primeros 15K con la cabeza, los últimos 6K con el corazón. ¡El podio te espera! 🏃♂️💪🏅`,
|
| 738 |
-
'42K': `¡${athleteName}, hoy te conviertes en MARATONISTA! Los primeros 30K controla, los últimos 12K puro corazón. ¡TÚ PUEDES! 🏃♂️🔥🏆✨`
|
| 739 |
-
};
|
| 740 |
-
const hrZones = calculateHRZones(hrMax, hrRest);
|
| 741 |
-
|
| 742 |
-
return {
|
| 743 |
-
day: day.toUpperCase(),
|
| 744 |
-
type: `🏁 CARRERA OBJETIVO - ${distance}`,
|
| 745 |
-
distance: distance,
|
| 746 |
-
motivationalMessage: motivationalMessages[distance],
|
| 747 |
-
details: {
|
| 748 |
-
warmup: '20-30 min antes: Movilidad articular suave + 10 min trote suave + 4 progresivos de 80m',
|
| 749 |
-
main: `¡ES TU MOMENTO! Sal con confianza a ${targetPace}/km. Hidrátate cada 5K. Geles según plan. ¡Disfruta!`,
|
| 750 |
-
cooldown: 'Post-carrera: Camina 10-15 min, hidrátate, estira suavemente',
|
| 751 |
-
hrZones: hrZones,
|
| 752 |
-
nutrition: `Desayuno 3-4h antes. Gel 15 min antes. Durante: hidratación cada 5K + gel cada 45 min`,
|
| 753 |
-
gear: 'Zapatilla de competencia. Ropa técnica ligera.',
|
| 754 |
-
mentalPrep: 'Confía en tu entrenamiento. ¡TÚ PUEDES!'
|
| 755 |
-
},
|
| 756 |
-
isRaceDay: true,
|
| 757 |
-
purpose: {
|
| 758 |
-
title: '🎯 Tu Gran Día',
|
| 759 |
-
content: 'Este es el día para el que entrenaste. Confía en tu preparación y disfruta.'
|
| 760 |
-
}
|
| 761 |
-
}
|
| 762 |
-
}
|
| 763 |
-
|
| 764 |
-
/**
|
| 765 |
-
* Crea la sesión de activación del día anterior a la carrera
|
| 766 |
-
*/
|
| 767 |
-
function createPreRaceSession(day, hrMax, hrRest, athleteName) {
|
| 768 |
-
const hrZones = calculateHRZones(hrMax, hrRest);
|
| 769 |
-
return {
|
| 770 |
-
day: day.toUpperCase(),
|
| 771 |
-
type: '🎯 Activación Pre-Carrera',
|
| 772 |
-
distance: '4 km',
|
| 773 |
-
motivationalMessage: `${athleteName}, mañana es TU DÍA! Hoy solo activamos y relajamos. ¡Mañana vas a brillar! 💪✨`,
|
| 774 |
-
details: {
|
| 775 |
-
warmup: '5 min caminata con respiraciones profundas',
|
| 776 |
-
main: 'Trote MUY fácil 4km. 4 progresivos de 60m',
|
| 777 |
-
cooldown: '10 min estiramientos suaves',
|
| 778 |
-
hrZones: {
|
| 779 |
-
zone: 'Zona 1-2',
|
| 780 |
-
bpm: `${hrZones.zone1.min}-${hrZones.zone2.max} bpm`,
|
| 781 |
-
percentage: '50-70% FCMax'
|
| 782 |
-
},
|
| 783 |
-
stretching: 'Cuádriceps, isquiotibiales, gemelos, psoas. 20 seg cada grupo',
|
| 784 |
-
nutrition: 'Hidratación constante. Comida ligera. Cena temprano.',
|
| 785 |
-
mentalPrep: 'Visualización positiva. Repasa estrategia. Duerme 8+ horas'
|
| 786 |
-
},
|
| 787 |
-
purpose: {
|
| 788 |
-
title: '🧘 Activación y Mentalización',
|
| 789 |
-
content: 'Mantener piernas activas sin fatiga. Preparación mental para la carrera.'
|
| 790 |
-
}
|
| 791 |
-
}
|
| 792 |
-
}
|
| 793 |
-
|
| 794 |
-
/**
|
| 795 |
-
* Crea una sesión de Tapering (Reducción de volumen)
|
| 796 |
-
*/
|
| 797 |
-
function createTaperSession(day, hrMax, hrRest) {
|
| 798 |
-
const hrZones = calculateHRZones(hrMax, hrRest);
|
| 799 |
-
return {
|
| 800 |
-
day: day.toUpperCase(),
|
| 801 |
-
type: 'Recuperación - Taper',
|
| 802 |
-
distance: '6 km',
|
| 803 |
-
details: {
|
| 804 |
-
warmup: '5 min caminata suave',
|
| 805 |
-
main: 'Trote muy suave. Sin esfuerzo. Enfoque en recuperación',
|
| 806 |
-
cooldown: '15 min estiramientos profundos + rodillo',
|
| 807 |
-
hrZones: {
|
| 808 |
-
zone: 'Zona 1',
|
| 809 |
-
bpm: `${hrZones.zone1.min}-${hrZones.zone1.max} bpm`,
|
| 810 |
-
percentage: '50-60% FCMax'
|
| 811 |
-
},
|
| 812 |
-
stretching: 'Cuádriceps (30 seg), Isquiotibiales (30 seg), Gemelos (30 seg)',
|
| 813 |
-
hydration: 'Mantén hidratación constante',
|
| 814 |
-
recovery: 'Masaje suave, baño de contraste, elevación de piernas'
|
| 815 |
-
},
|
| 816 |
-
purpose: {
|
| 817 |
-
title: '💆 Recuperación y Preparación',
|
| 818 |
-
content: 'Reducir volumen para llegar fresco. Optimizar recuperación muscular.'
|
| 819 |
-
}
|
| 820 |
-
}
|
| 821 |
-
}
|
| 822 |
-
|
| 823 |
-
/**
|
| 824 |
-
* Crea la sesión del día de la carrera preparatoria
|
| 825 |
-
*/
|
| 826 |
-
function createPrepRaceDay(day, prepRace, targetPace, hrMax, hrRest) {
|
| 827 |
-
const hrZones = calculateHRZones(hrMax, hrRest);
|
| 828 |
-
return {
|
| 829 |
-
day: day.toUpperCase(),
|
| 830 |
-
type: `🏃 Carrera Preparatoria - ${prepRace.name}`,
|
| 831 |
-
distance: prepRace.distance,
|
| 832 |
-
isPrepRace: true,
|
| 833 |
-
details: {
|
| 834 |
-
warmup: '20 min antes: Movilidad + 10 min trote + 3 progresivos',
|
| 835 |
-
main: `Carrera a ritmo controlado (5-10 seg más lento). FC: ${hrZones.zone3.min}-${hrZones.zone4.max} bpm`,
|
| 836 |
-
cooldown: '10 min caminata, hidratación, estiramientos',
|
| 837 |
-
hrZones: hrZones,
|
| 838 |
-
strategy: 'Prueba tu estrategia de hidratación y nutrición',
|
| 839 |
-
learning: 'Anota qué funcionó para la carrera principal'
|
| 840 |
-
},
|
| 841 |
-
purpose: {
|
| 842 |
-
title: '🎯 Simulacro y Aprendizaje',
|
| 843 |
-
content: 'Probar estrategia de hidratación/nutrición, sentir el ritmo, ganar confianza.'
|
| 844 |
-
}
|
| 845 |
-
}
|
| 846 |
-
}
|
| 847 |
-
|
| 848 |
-
/**
|
| 849 |
-
* Decide qué tipo de sesión crear según el día y el período de entrenamiento
|
| 850 |
-
*/
|
| 851 |
-
function createRegularSession(day, dayIndex, totalDays, period, baseKm, targetPace, hrMax, hrRest, crossTraining, isRecovery) {
|
| 852 |
-
const hrZones = calculateHRZones(hrMax, hrRest);
|
| 853 |
-
const kmPerSession = baseKm / totalDays;
|
| 854 |
-
|
| 855 |
-
if (period === 'basico') {
|
| 856 |
-
return generateBaseSession(day, kmPerSession, isRecovery, hrZones, dayIndex, crossTraining);
|
| 857 |
-
} else if (period === 'especifico') {
|
| 858 |
-
return generateSpecificSession(day, dayIndex, totalDays, kmPerSession, targetPace, hrZones, crossTraining);
|
| 859 |
-
} else if (period === 'competencia') {
|
| 860 |
-
return generateCompetitionSession(day, dayIndex, totalDays, kmPerSession, targetPace, hrZones, crossTraining);
|
| 861 |
-
} else { // transicion
|
| 862 |
-
return generateTransitionSession(day, kmPerSession, hrZones, crossTraining);
|
| 863 |
-
}
|
| 864 |
-
}
|
| 865 |
-
|
| 866 |
-
/**
|
| 867 |
-
* Calcula las zonas de Frecuencia Cardíaca
|
| 868 |
-
*/
|
| 869 |
-
function calculateHRZones(hrMax, hrRest) {
|
| 870 |
-
const hrReserve = hrMax - hrRest;
|
| 871 |
-
return {
|
| 872 |
-
zone1: {
|
| 873 |
-
min: Math.round(hrRest + .5 * hrReserve),
|
| 874 |
-
max: Math.round(hrRest + .6 * hrReserve),
|
| 875 |
-
name: 'Recuperación'
|
| 876 |
-
},
|
| 877 |
-
zone2: {
|
| 878 |
-
min: Math.round(hrRest + .6 * hrReserve),
|
| 879 |
-
max: Math.round(hrRest + .7 * hrReserve),
|
| 880 |
-
name: 'Aeróbica'
|
| 881 |
-
},
|
| 882 |
-
zone3: {
|
| 883 |
-
min: Math.round(hrRest + .7 * hrReserve),
|
| 884 |
-
max: Math.round(hrRest + .8 * hrReserve),
|
| 885 |
-
name: 'Tempo'
|
| 886 |
-
},
|
| 887 |
-
zone4: {
|
| 888 |
-
min: Math.round(hrRest + .8 * hrReserve),
|
| 889 |
-
max: Math.round(hrRest + .9 * hrReserve),
|
| 890 |
-
name: 'Umbral'
|
| 891 |
-
},
|
| 892 |
-
zone5: {
|
| 893 |
-
min: Math.round(hrRest + .9 * hrReserve),
|
| 894 |
-
max: hrMax,
|
| 895 |
-
name: 'Máxima'
|
| 896 |
-
}
|
| 897 |
-
}
|
| 898 |
-
}
|
| 899 |
-
|
| 900 |
-
/**
|
| 901 |
-
* Genera una sesión del Período Base
|
| 902 |
-
*/
|
| 903 |
-
function generateBaseSession(day, km, isRecovery, hrZones, dayIndex, crossTraining) {
|
| 904 |
-
const distance = isRecovery ? Math.round(.7 * km) : Math.round(km);
|
| 905 |
-
|
| 906 |
-
// Días de Cross Training
|
| 907 |
-
if (dayIndex % 3 == 1 && crossTraining.length > 0) {
|
| 908 |
-
const activities = crossTraining.join(', ');
|
| 909 |
-
return {
|
| 910 |
-
day: day.toUpperCase(),
|
| 911 |
-
type: 'Entrenamiento Cruzado',
|
| 912 |
-
distance: '30-45 min',
|
| 913 |
-
details: {
|
| 914 |
-
warmup: '10 min movilidad',
|
| 915 |
-
main: `${activities} a intensidad moderada. FC: ${hrZones.zone1.min}-${hrZones.zone2.max} bpm`,
|
| 916 |
-
cooldown: '10 min estiramiento + rodillo',
|
| 917 |
-
crossTraining: activities,
|
| 918 |
-
benefits: 'Reduce impacto, mejora fuerza, previene lesiones'
|
| 919 |
-
},
|
| 920 |
-
purpose: {
|
| 921 |
-
title: '🔄 Recuperación Activa',
|
| 922 |
-
content: `El cross training permite recuperación mientras mantienes fitness. ${activities} fortalece grupos musculares complementarios.`
|
| 923 |
-
}
|
| 924 |
-
}
|
| 925 |
-
}
|
| 926 |
-
|
| 927 |
-
// Trote Base (Long Run y otros trotes suaves)
|
| 928 |
-
return {
|
| 929 |
-
day: day.toUpperCase(),
|
| 930 |
-
type: 'Trote Continuo Base',
|
| 931 |
-
distance: `${distance} km`,
|
| 932 |
-
details: {
|
| 933 |
-
warmup: '10 min caminata + activación glúteos + 5 min trote suave',
|
| 934 |
-
main: `Trote continuo conversacional. FC: ${hrZones.zone2.min}-${hrZones.zone2.max} bpm (Zona 2). Postura: cabeza erguida, hombros relajados`,
|
| 935 |
-
cooldown: '5 min trote suave + 5 min caminata + 15 min estiramientos',
|
| 936 |
-
hrZones: hrZones,
|
| 937 |
-
technique: 'Cadencia 170-180 pasos/min, contacto suave, respiración rítmica',
|
| 938 |
-
stretching: 'Cuádriceps (30 seg), Isquiotibiales (30 seg), Gemelos (30 seg), Psoas (30 seg)',
|
| 939 |
-
gear: 'Zapatilla con buena amortiguación',
|
| 940 |
-
hydration: 'Hidrátate antes y después. Si >60 min, lleva agua'
|
| 941 |
-
},
|
| 942 |
-
purpose: {
|
| 943 |
-
title: '🎯 Construcción de Base Aeróbica',
|
| 944 |
-
content: 'Desarrollar resistencia aeróbica fundamental. Adaptación cardiovascular. Este es el pilar de tu entrenamiento.'
|
| 945 |
-
}
|
| 946 |
-
}
|
| 947 |
-
}
|
| 948 |
-
|
| 949 |
-
/**
|
| 950 |
-
* Genera una sesión del Período Específico (Incluye intervalos, Tempo y Carrera Larga)
|
| 951 |
-
*/
|
| 952 |
-
function generateSpecificSession(day, index, totalDays, km, targetPace, hrZones, crossTraining) {
|
| 953 |
-
const distance = Math.round(km);
|
| 954 |
-
|
| 955 |
-
// Días de Recuperación y Cross Training
|
| 956 |
-
if (index === 0 || index === 1) {
|
| 957 |
-
if (index === 1 && crossTraining.length > 0) {
|
| 958 |
-
const activities = crossTraining.join(', ');
|
| 959 |
-
return {
|
| 960 |
-
day: day.toUpperCase(),
|
| 961 |
-
type: 'Recuperación + Cross Training',
|
| 962 |
-
distance: `${Math.round(.6 * distance)} km + 30 min`,
|
| 963 |
-
details: {
|
| 964 |
-
warmup: '5 min movilidad',
|
| 965 |
-
main: `Trote suave ${Math.round(.6 * distance)}km + ${activities} 30 min. FC: ${hrZones.zone1.min}-${hrZones.zone2.max} bpm`,
|
| 966 |
-
cooldown: '15 min estiramientos + rodillo',
|
| 967 |
-
recovery: 'Enfoque en recuperación. Baño de contraste si es posible'
|
| 968 |
-
},
|
| 969 |
-
purpose: {
|
| 970 |
-
title: '💆 Recuperación Activa Multimodal',
|
| 971 |
-
content: 'Combina recuperación cardiovascular con fortalecimiento sin impacto.'
|
| 972 |
-
}
|
| 973 |
-
}
|
| 974 |
-
}
|
| 975 |
-
// Trote Regenerativo
|
| 976 |
-
return {
|
| 977 |
-
day: day.toUpperCase(),
|
| 978 |
-
type: 'Trote Regenerativo',
|
| 979 |
-
distance: `${distance} km`,
|
| 980 |
-
details: {
|
| 981 |
-
warmup: '10 min trote muy suave + movilidad',
|
| 982 |
-
main: `Trote muy cómodo. FC: ${hrZones.zone1.min}-${hrZones.zone2.max} bpm. Recuperación activa`,
|
| 983 |
-
cooldown: '10 min estiramientos profundos',
|
| 984 |
-
recovery: 'Rodillo de espuma: Gemelos, cuádriceps, isquiotibiales, glúteos (5 min cada grupo)'
|
| 985 |
-
},
|
| 986 |
-
purpose: {
|
| 987 |
-
title: '💆 Recuperación Muscular',
|
| 988 |
-
content: 'Facilitar recuperación activa, mejorar flujo sanguíneo. Prepara para sesiones intensas.'
|
| 989 |
-
}
|
| 990 |
-
}
|
| 991 |
-
}
|
| 992 |
-
// Sesión de Intervalos (Mitad de la semana)
|
| 993 |
-
else if (index === Math.floor(totalDays / 2)) {
|
| 994 |
-
return {
|
| 995 |
-
day: day.toUpperCase(),
|
| 996 |
-
type: 'Intervalos en Pista/Ruta',
|
| 997 |
-
distance: `${distance+3} km`, // +3km de calentamiento/enfriamiento
|
| 998 |
-
details: {
|
| 999 |
-
warmup: '15 min trote + Ejercicios dinámicos + 4 progresivos 100m',
|
| 1000 |
-
main: `SESIÓN CLAVE: 8-10 x 400m a ${targetPace}/km con 90 seg recuperación. FC: ${hrZones.zone4.min}-${hrZones.zone5.min} bpm`,
|
| 1001 |
-
cooldown: '10 min trote suave + 15 min estiramientos + core (plancha 3x30seg)',
|
| 1002 |
-
technique: 'Brazos activos, cadencia alta, respira profundo, mantén forma técnica',
|
| 1003 |
-
mentalFocus: 'Cada intervalo con concentración. Último intervalo da tu mejor esfuerzo.',
|
| 1004 |
-
recovery: 'Recuperación activa entre intervalos es CLAVE',
|
| 1005 |
-
nutrition: 'Gel 30 min antes si entrenas en ayunas'
|
| 1006 |
-
},
|
| 1007 |
-
purpose: {
|
| 1008 |
-
title: '⚡ Desarrollo de Velocidad y VO2Max',
|
| 1009 |
-
content: 'Mejorar capacidad anaeróbica, velocidad, economía de carrera. Entrenas al cuerpo a mantener ritmo objetivo con menor esfuerzo.'
|
| 1010 |
-
}
|
| 1011 |
-
}
|
| 1012 |
-
}
|
| 1013 |
-
// Sesión Tempo (Penúltimo día de entrenamiento)
|
| 1014 |
-
else if (index === totalDays - 2) {
|
| 1015 |
-
return {
|
| 1016 |
-
day: day.toUpperCase(),
|
| 1017 |
-
type: 'Tempo Run (Ritmo Sostenido)',
|
| 1018 |
-
distance: `${distance+3} km`, // +3km de calentamiento/enfriamiento
|
| 1019 |
-
details: {
|
| 1020 |
-
warmup: '15 min trote + 4 progresivos 100m',
|
| 1021 |
-
main: `SESIÓN CLAVE: 25-35 min a ritmo TEMPO (10-15 seg más rápido que objetivo). FC: ${hrZones.zone3.min}-${hrZones.zone4.max} bpm. Puedes decir frases cortas pero no conversación fluida.`,
|
| 1022 |
-
cooldown: '10 min trote fácil + 15 min estiramientos profundos',
|
| 1023 |
-
technique: 'Postura erguida, respiración controlada profunda, relaja hombros',
|
| 1024 |
-
mentalFocus: 'Divide en bloques de 5 min. Cada bloque es un mini-desafío.',
|
| 1025 |
-
gear: 'Zapatilla mixta o tempo (más ligera)',
|
| 1026 |
-
nutrition: 'Hidratación durante si >45 min totales'
|
| 1027 |
-
},
|
| 1028 |
-
purpose: {
|
| 1029 |
-
title: '🎯 Umbral Anaeróbico',
|
| 1030 |
-
content: 'Elevar tu umbral de lactato. Mejora capacidad de sostener ritmos rápidos. Fundamental para resistencia.'
|
| 1031 |
-
}
|
| 1032 |
-
}
|
| 1033 |
-
}
|
| 1034 |
-
// Carrera Larga (Último día de entrenamiento)
|
| 1035 |
-
else {
|
| 1036 |
-
return {
|
| 1037 |
-
day: day.toUpperCase(),
|
| 1038 |
-
type: 'Carrera Larga - Long Run',
|
| 1039 |
-
distance: `${Math.round(1.6 * distance)} km`,
|
| 1040 |
-
details: {
|
| 1041 |
-
warmup: '15 min trote MUY fácil + movilidad completa + activación glúteos',
|
| 1042 |
-
main: `SESIÓN FUNDAMENTAL: Carrera continua aeróbica. FC: ${hrZones.zone2.min}-${hrZones.zone2.max} bpm. Últimos 3-5 km puedes acelerar ligeramente. Hidratación cada 20 min (200ml). Si >90 min: gel cada 45 min.`,
|
| 1043 |
-
cooldown: '10 min caminata + 20 min estiramientos COMPLETOS + rodillo 10 min + hidratación con electrolitos + plátano',
|
| 1044 |
-
nutrition: 'Pre: Desayuno ligero 2-3h antes. Durante: Hidratación + geles. Post: Proteína + carbohidratos en 30 min',
|
| 1045 |
-
mentalFocus: 'Disfruta el proceso. Meditación en movimiento. Los últimos 5km son mentales - aquí creces',
|
| 1046 |
-
gear: 'Zapatilla maximalista con máxima amortiguación',
|
| 1047 |
-
recovery: 'Post: Baño de contraste (3 min cada), elevación piernas 15 min, masaje suave',
|
| 1048 |
-
progression: 'Empieza conservador. Siéntete bien en primeros 2/3. Acelera último tercio si te sientes fuerte'
|
| 1049 |
-
},
|
| 1050 |
-
purpose: {
|
| 1051 |
-
title: '🏃 Resistencia Muscular y Mental',
|
| 1052 |
-
content: 'Adaptación muscular y tendinosa. Entrenamiento mental crucial. Enseña al cuerpo a usar grasas como combustible. El long run es donde se construyen los maratonistas.'
|
| 1053 |
-
}
|
| 1054 |
-
}
|
| 1055 |
-
}
|
| 1056 |
-
}
|
| 1057 |
-
|
| 1058 |
-
/**
|
| 1059 |
-
* Genera una sesión del Período de Competición (Similar a Específico, pero con menor volumen)
|
| 1060 |
-
*/
|
| 1061 |
-
function generateCompetitionSession(day, index, totalDays, km, targetPace, hrZones, crossTraining) {
|
| 1062 |
-
// Reduce el volumen total en ~15% para el período de competición
|
| 1063 |
-
return generateSpecificSession(day, index, totalDays, Math.round(.85 * km), targetPace, hrZones, crossTraining);
|
| 1064 |
-
}
|
| 1065 |
-
|
| 1066 |
-
/**
|
| 1067 |
-
* Genera una sesión del Período de Transición (Recuperación post-carrera)
|
| 1068 |
-
*/
|
| 1069 |
-
function generateTransitionSession(day, km, hrZones, crossTraining) {
|
| 1070 |
-
// Sesión de Cross Training aleatoria (50% de probabilidad)
|
| 1071 |
-
if (crossTraining.length > 0 && Math.random() > .5) {
|
| 1072 |
-
const activities = crossTraining.join(' o ');
|
| 1073 |
-
return {
|
| 1074 |
-
day: day.toUpperCase(),
|
| 1075 |
-
type: 'Recuperación Activa - Cross Training',
|
| 1076 |
-
distance: '30-40 min',
|
| 1077 |
-
details: {
|
| 1078 |
-
warmup: '10 min movilidad articular completa',
|
| 1079 |
-
main: `Sesión suave de ${activities}. Intensidad baja-moderada. FC: ${hrZones.zone1.min}-${hrZones.zone2.max} bpm`,
|
| 1080 |
-
cooldown: '15 min estiramientos profundos + trabajo de movilidad',
|
| 1081 |
-
focus: 'Recuperación total, prevención de lesiones, mantener movilidad'
|
| 1082 |
-
},
|
| 1083 |
-
purpose: {
|
| 1084 |
-
title: '🔄 Recuperación y Mantenimiento',
|
| 1085 |
-
content: 'Semana de transición para recuperación profunda. Mantener actividad sin impacto.'
|
| 1086 |
-
}
|
| 1087 |
-
}
|
| 1088 |
-
}
|
| 1089 |
-
// Trote Regenerativo ligero
|
| 1090 |
-
return {
|
| 1091 |
-
day: day.toUpperCase(),
|
| 1092 |
-
type: 'Trote Regenerativo Ligero',
|
| 1093 |
-
distance: `${Math.round(.6 * km)} km`,
|
| 1094 |
-
details: {
|
| 1095 |
-
warmup: '5 min caminata con respiraciones profundas',
|
| 1096 |
-
main: `Trote MUY suave y relajado. FC: ${hrZones.zone1.min}-${hrZones.zone1.max} bpm. Sin reloj, sin presión`,
|
| 1097 |
-
cooldown: '15 min estiramientos + rodillo completo + yoga/pilates 15 min',
|
| 1098 |
-
recovery: 'Enfoque total en recuperación. Escucha tu cuerpo',
|
| 1099 |
-
mentalHealth: 'Disfruta correr sin presión. Reconecta con por qué amas correr'
|
| 1100 |
-
},
|
| 1101 |
-
purpose: {
|
| 1102 |
-
title: '💆 Recuperación Total',
|
| 1103 |
-
content: 'Permitir regeneración profunda después del ciclo. Preparación para próximo ciclo o disfrute post-carrera.'
|
| 1104 |
-
}
|
| 1105 |
-
}
|
| 1106 |
-
}
|
| 1107 |
-
|
| 1108 |
-
/**
|
| 1109 |
-
* Calcula el kilometraje base semanal progresivo (incluyendo el Tapering)
|
| 1110 |
-
*/
|
| 1111 |
-
function getBaseKm(distance, experience, week, totalWeeks) {
|
| 1112 |
-
const baseKmMap = {
|
| 1113 |
-
'5K': {
|
| 1114 |
-
principiante: 20,
|
| 1115 |
-
intermedio: 25,
|
| 1116 |
-
avanzado: 30
|
| 1117 |
-
},
|
| 1118 |
-
'10K': {
|
| 1119 |
-
principiante: 30,
|
| 1120 |
-
intermedio: 35,
|
| 1121 |
-
avanzado: 40
|
| 1122 |
-
},
|
| 1123 |
-
'21K': {
|
| 1124 |
-
principiante: 40,
|
| 1125 |
-
intermedio: 55,
|
| 1126 |
-
avanzado: 70
|
| 1127 |
-
},
|
| 1128 |
-
'42K': {
|
| 1129 |
-
principiante: 50,
|
| 1130 |
-
intermedio: 70,
|
| 1131 |
-
avanzado: 90
|
| 1132 |
-
}
|
| 1133 |
-
};
|
| 1134 |
-
|
| 1135 |
-
const base = baseKmMap[distance][experience];
|
| 1136 |
-
const progress = week / totalWeeks;
|
| 1137 |
-
const peak = .75; // El volumen máximo se alcanza al 75% del plan
|
| 1138 |
-
|
| 1139 |
-
if (progress < peak) {
|
| 1140 |
-
// Fase de acumulación (progresión lineal hasta el 75%)
|
| 1141 |
-
return Math.round(base + .6 * base * (progress / peak));
|
| 1142 |
-
} else {
|
| 1143 |
-
// Fase de Tapering (Reducción de volumen)
|
| 1144 |
-
const taperProgress = (progress - peak) / (1 - peak); // 0 a 1 en el 25% final
|
| 1145 |
-
const peakKm = base + .6 * base;
|
| 1146 |
-
return Math.round(peakKm * (1 - .3 * taperProgress)); // Reducción gradual del 30%
|
| 1147 |
-
}
|
| 1148 |
-
}
|
| 1149 |
-
|
| 1150 |
-
// --- Funciones de la lista de planes ---
|
| 1151 |
-
|
| 1152 |
-
/**
|
| 1153 |
-
* Carga y muestra la lista de planes en la sección 'plan-list'
|
| 1154 |
-
*/
|
| 1155 |
-
function loadPlanList() {
|
| 1156 |
-
const plans = getPlans();
|
| 1157 |
-
const listContent = document.getElementById('planListContent');
|
| 1158 |
-
const placeholder = document.getElementById('noPlanPlaceholder');
|
| 1159 |
-
|
| 1160 |
-
let filteredPlans = plans;
|
| 1161 |
-
// Filtrar por planes creados por el usuario si no es admin
|
| 1162 |
-
if (currentUser && currentUser.role === 'user') {
|
| 1163 |
-
filteredPlans = plans.filter(p => p.createdBy === currentUser.username);
|
| 1164 |
-
}
|
| 1165 |
-
|
| 1166 |
-
if (filteredPlans.length === 0) {
|
| 1167 |
-
placeholder.classList.remove('hidden');
|
| 1168 |
-
listContent.innerHTML = '';
|
| 1169 |
-
return;
|
| 1170 |
-
}
|
| 1171 |
-
|
| 1172 |
-
placeholder.classList.add('hidden');
|
| 1173 |
-
const experienceText = {
|
| 1174 |
-
principiante: 'Principiante',
|
| 1175 |
-
intermedio: 'Intermedio',
|
| 1176 |
-
avanzado: 'Avanzado'
|
| 1177 |
-
};
|
| 1178 |
-
let html = '';
|
| 1179 |
-
|
| 1180 |
-
filteredPlans.forEach(plan => {
|
| 1181 |
-
const crossTrainingText = plan.userData.crossTraining && plan.userData.crossTraining.length > 0 ? plan.userData.crossTraining.join(', ') : 'No';
|
| 1182 |
-
html += `
|
| 1183 |
-
<div class="plan-card">
|
| 1184 |
-
<div class="plan-info">
|
| 1185 |
-
<h3><i class="fas fa-user"></i> ${plan.userData.name}</h3>
|
| 1186 |
-
<p><i class="fas fa-birthday-cake"></i> <strong>Edad:</strong> ${plan.userData.age} años | <strong>IMC:</strong> ${plan.userData.imc}</p>
|
| 1187 |
-
<p><i class="fas fa-layer-group"></i> <strong>Experiencia:</strong> ${experienceText[plan.userData.experience]}</p>
|
| 1188 |
-
<p><i class="fas fa-heartbeat"></i> <strong>FC Max:</strong> ${plan.userData.hrMax} bpm | <strong>FC Reposo:</strong> ${plan.userData.hrRest} bpm</p>
|
| 1189 |
-
<p><i class="fas fa-flag-checkered"></i> <strong>Objetivo:</strong> ${plan.userData.distance} - Ritmo ${plan.userData.targetPace}/km</p>
|
| 1190 |
-
<p><i class="fas fa-calendar-check"></i> <strong>Fecha:</strong> ${new Date(plan.userData.raceDate).toLocaleDateString('es-CL')}</p>
|
| 1191 |
-
<p><i class="fas fa-calendar-week"></i> <strong>Duración:</strong> ${plan.totalWeeks} sem | <strong>Días:</strong> ${plan.userData.trainingDays.length}</p>
|
| 1192 |
-
<p><i class="fas fa-dumbbell"></i> <strong>Cross Training:</strong> ${crossTrainingText}</p>
|
| 1193 |
-
${plan.userData.prepRaces && plan.userData.prepRaces.length > 0 ? `<p><i class="fas fa-trophy"></i> <strong>Carreras prep:</strong> ${plan.userData.prepRaces.length}</p>` : ''}
|
| 1194 |
-
<p style="font-size:12px;color:#999"><i class="fas fa-clock"></i> ${new Date(plan.createdAt).toLocaleString()}</p>
|
| 1195 |
-
</div>
|
| 1196 |
-
<div class="plan-actions">
|
| 1197 |
-
<button class="btn btn-primary btn-sm" onclick="viewPlanDetail('${plan.id}')"><i class="fas fa-eye"></i> Ver</button>
|
| 1198 |
-
<button class="btn btn-success btn-sm" onclick="generatePDF('${plan.id}')"><i class="fas fa-file-pdf"></i> PDF</button>
|
| 1199 |
-
${currentUser && currentUser.role === 'admin' ? `<button class="btn btn-danger btn-sm" onclick="confirmDeletePlan('${plan.id}')"><i class="fas fa-trash"></i> Eliminar</button>` : ''}
|
| 1200 |
-
</div>
|
| 1201 |
-
</div>`;
|
| 1202 |
-
});
|
| 1203 |
-
listContent.innerHTML = html;
|
| 1204 |
-
}
|
| 1205 |
-
|
| 1206 |
-
/**
|
| 1207 |
-
* Muestra el detalle de un plan de entrenamiento en un modal
|
| 1208 |
-
*/
|
| 1209 |
-
function viewPlanDetail(planId) {
|
| 1210 |
-
const plans = getPlans();
|
| 1211 |
-
const plan = plans.find(p => p.id === planId);
|
| 1212 |
-
if (!plan) return;
|
| 1213 |
-
|
| 1214 |
-
currentViewPlan = plan; // Almacena el plan actual para el PDF
|
| 1215 |
-
|
| 1216 |
-
const experienceText = {
|
| 1217 |
-
principiante: 'Principiante',
|
| 1218 |
-
intermedio: 'Intermedio',
|
| 1219 |
-
avanzado: 'Avanzado'
|
| 1220 |
-
};
|
| 1221 |
-
|
| 1222 |
-
document.getElementById('modalTitle').textContent = `Plan - ${plan.userData.name}`;
|
| 1223 |
-
|
| 1224 |
-
// HTML del Perfil del Atleta
|
| 1225 |
-
let html = `
|
| 1226 |
-
<div style="background:linear-gradient(135deg,#f8f9fa 0%,#e9ecef 100%);padding:25px;border-radius:8px;margin-bottom:30px;border-left:5px solid var(--primary-color)">
|
| 1227 |
-
<h3 style="color:var(--primary-color);margin-bottom:20px;font-size:22px"><i class="fas fa-user-circle"></i> Perfil del Atleta</h3>
|
| 1228 |
-
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(250px,1fr));gap:15px">
|
| 1229 |
-
<p><strong>👤 Nombre:</strong> ${plan.userData.name}</p>
|
| 1230 |
-
<p><strong>🎂 Edad:</strong> ${plan.userData.age} años</p>
|
| 1231 |
-
<p><strong>📊 Experiencia:</strong> ${experienceText[plan.userData.experience]}</p>
|
| 1232 |
-
<p><strong>⚖️ Peso:</strong> ${plan.userData.weight} kg</p>
|
| 1233 |
-
<p><strong>📏 Talla:</strong> ${plan.userData.height} cm</p>
|
| 1234 |
-
<p><strong>💪 IMC:</strong> ${plan.userData.imc}</p>
|
| 1235 |
-
<p><strong>❤️ FC Máxima:</strong> ${plan.userData.hrMax} bpm</p>
|
| 1236 |
-
<p><strong>🛌 FC Reposo:</strong> ${plan.userData.hrRest} bpm</p>
|
| 1237 |
-
${plan.userData.vo2max ? `<p><strong>🫁 VO2Max:</strong> ${plan.userData.vo2max}</p>` : ''}
|
| 1238 |
-
<p><strong>🎯 Objetivo:</strong> ${plan.userData.distance}</p>
|
| 1239 |
-
<p><strong>⏱️ Ritmo:</strong> ${plan.userData.targetPace}/km</p>
|
| 1240 |
-
<p><strong>📅 Fecha:</strong> <strong style="color:var(--primary-color);font-size:16px">${new Date(plan.userData.raceDate).toLocaleDateString('es-CL', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}</strong></p>
|
| 1241 |
-
<p><strong>📆 Duración:</strong> ${plan.totalWeeks} sem</p>
|
| 1242 |
-
<p><strong>🏃 Días:</strong> ${plan.userData.trainingDays.join(', ')}</p>
|
| 1243 |
-
</div>
|
| 1244 |
-
${plan.userData.crossTraining && plan.userData.crossTraining.length > 0 ? `<p style="margin-top:15px"><strong>🏋️ Cross Training:</strong> ${plan.userData.crossTraining.join(', ')}</p>` : ''}
|
| 1245 |
-
${plan.userData.prepRaces && plan.userData.prepRaces.length > 0 ? `
|
| 1246 |
-
<div style="margin-top:15px">
|
| 1247 |
-
<p><strong>🏆 Carreras Preparatorias:</strong></p>
|
| 1248 |
-
<ul style="margin-left:20px;margin-top:8px">
|
| 1249 |
-
${plan.userData.prepRaces.map(r => `<li>${r.name} - ${r.distance} - ${new Date(r.date).toLocaleDateString('es-CL')}</li>`).join('')}
|
| 1250 |
-
</ul>
|
| 1251 |
-
</div>` : ''}
|
| 1252 |
-
${plan.userData.notes ? `<p style="margin-top:15px"><strong>📝 Notas:</strong> ${plan.userData.notes}</p>` : ''}
|
| 1253 |
-
</div>`;
|
| 1254 |
-
|
| 1255 |
-
// Agrupar semanas por período
|
| 1256 |
-
const periodGroups = {
|
| 1257 |
-
basico: [],
|
| 1258 |
-
especifico: [],
|
| 1259 |
-
competencia: [],
|
| 1260 |
-
transicion: []
|
| 1261 |
-
};
|
| 1262 |
-
plan.weeklyPlans.forEach(week => {
|
| 1263 |
-
periodGroups[week.period].push(week);
|
| 1264 |
-
});
|
| 1265 |
-
|
| 1266 |
-
const periodNames = {
|
| 1267 |
-
basico: 'PERÍODO BASE',
|
| 1268 |
-
especifico: 'PERÍODO ESPECÍFICO',
|
| 1269 |
-
competencia: 'PERÍODO DE COMPETENCIA',
|
| 1270 |
-
transicion: 'PERÍODO DE TRANSICIÓN'
|
| 1271 |
-
};
|
| 1272 |
-
|
| 1273 |
-
// Iterar por períodos y semanas
|
| 1274 |
-
Object.keys(periodGroups).forEach(periodKey => {
|
| 1275 |
-
if (periodGroups[periodKey].length === 0) return;
|
| 1276 |
-
|
| 1277 |
-
html += `<div class="period-section"><div class="period-header"><i class="fas fa-calendar-alt"></i> ${periodNames[periodKey]}</div>`;
|
| 1278 |
-
|
| 1279 |
-
periodGroups[periodKey].forEach(week => {
|
| 1280 |
-
// Sección de la semana
|
| 1281 |
-
html += `
|
| 1282 |
-
<div class="week-section ${week.isRaceWeek ? 'race-week' : ''}">
|
| 1283 |
-
<div class="week-header">
|
| 1284 |
-
<span>${week.isRaceWeek ? '🏆' : '📅'} SEMANA ${week.week}${week.isRaceWeek ? ' - 🎯 COMPETENCIA' : ''}${week.prepRace ? ' - 🏃 ' + week.prepRace.name : ''}${week.isRecoveryWeek && !week.isRaceWeek ? ' (💆 Recuperación)' : ''}</span>
|
| 1285 |
-
<span style="color:var(--secondary-color);font-weight:bold">${week.totalKm} km</span>
|
| 1286 |
-
</div>`;
|
| 1287 |
-
|
| 1288 |
-
// Sesiones de la semana
|
| 1289 |
-
week.sessions.forEach(session => {
|
| 1290 |
-
html += `
|
| 1291 |
-
<div class="session-card ${session.isRaceDay ? 'race-day' : ''}">
|
| 1292 |
-
<div class="session-header">
|
| 1293 |
-
<div class="session-title">${session.isRaceDay ? '🏁' : session.isPrepRace ? '🏃' : '💪'} ${session.day} - ${session.type}</div>
|
| 1294 |
-
<div class="session-distance">${session.distance}</div>
|
| 1295 |
-
</div>
|
| 1296 |
-
${session.motivationalMessage ? `<div class="motivational-message">${session.motivationalMessage}</div>` : ''}
|
| 1297 |
-
<div class="session-details">
|
| 1298 |
-
<div class="detail-section"><div class="detail-section-title">🔥 Calentamiento</div><div class="detail-item">${session.details.warmup}</div></div>
|
| 1299 |
-
<div class="detail-section"><div class="detail-section-title">🏃 Desarrollo Principal</div><div class="detail-item">${session.details.main}</div></div>
|
| 1300 |
-
<div class="detail-section"><div class="detail-section-title">🧘 Enfriamiento</div><div class="detail-item">${session.details.cooldown}</div></div>
|
| 1301 |
-
${session.details.hrZones ? `<div class="detail-section"><div class="detail-section-title">❤️ Zonas FC</div>
|
| 1302 |
-
<div class="hr-zones">
|
| 1303 |
-
${session.details.hrZones.zone ? // Si es zona individual (ej. Zona 1)
|
| 1304 |
-
`<div class="hr-zone"><span class="hr-zone-label">${session.details.hrZones.zone}</span>${session.details.hrZones.bpm}<br>${session.details.hrZones.percentage || ''}</div>` :
|
| 1305 |
-
// Si son todas las zonas
|
| 1306 |
-
`<div class="hr-zone"><span class="hr-zone-label">Zona 1 - Recuperación</span>${session.details.hrZones.zone1.min}-${session.details.hrZones.zone1.max} bpm</div>
|
| 1307 |
-
<div class="hr-zone"><span class="hr-zone-label">Zona 2 - Aeróbica</span>${session.details.hrZones.zone2.min}-${session.details.hrZones.zone2.max} bpm</div>
|
| 1308 |
-
<div class="hr-zone"><span class="hr-zone-label">Zona 3 - Tempo</span>${session.details.hrZones.zone3.min}-${session.details.hrZones.zone3.max} bpm</div>
|
| 1309 |
-
<div class="hr-zone"><span class="hr-zone-label">Zona 4 - Umbral</span>${session.details.hrZones.zone4.min}-${session.details.hrZones.zone4.max} bpm</div>`
|
| 1310 |
-
}
|
| 1311 |
-
</div>
|
| 1312 |
-
</div>` : ''}
|
| 1313 |
-
${session.details.stretching ? `<div class="detail-section"><div class="detail-section-title">🤸 Estiramientos</div><div class="detail-item">${session.details.stretching}</div></div>` : ''}
|
| 1314 |
-
${session.details.technique ? `<div class="detail-section"><div class="detail-section-title">🎯 Técnica</div><div class="detail-item">${session.details.technique}</div></div>` : ''}
|
| 1315 |
-
${session.details.mentalFocus ? `<div class="detail-section"><div class="detail-section-title">🧠 Enfoque Mental</div><div class="detail-item">${session.details.mentalFocus}</div></div>` : ''}
|
| 1316 |
-
${session.details.nutrition ? `<div class="detail-section"><div class="detail-section-title">🍎 Nutrición</div><div class="detail-item">${session.details.nutrition}</div></div>` : ''}
|
| 1317 |
-
${session.details.gear ? `<div class="detail-section"><div class="detail-section-title">⚙️ Equipamiento</div><div class="detail-item">${session.details.gear}</div></div>` : ''}
|
| 1318 |
-
${session.details.recovery ? `<div class="detail-section"><div class="detail-section-title">🩹 Recuperación</div><div class="detail-item">${session.details.recovery}</div></div>` : ''}
|
| 1319 |
-
${session.details.progression ? `<div class="detail-section"><div class="detail-section-title">📈 Progresión</div><div class="detail-item">${session.details.progression}</div></div>` : ''}
|
| 1320 |
-
<div class="detail-purpose">
|
| 1321 |
-
<span class="purpose-title">${session.purpose.title}</span>: ${session.purpose.content}
|
| 1322 |
-
</div>
|
| 1323 |
-
</div>
|
| 1324 |
-
</div>`;
|
| 1325 |
-
});
|
| 1326 |
-
html += `</div>`; // Cierre de week-section
|
| 1327 |
-
});
|
| 1328 |
-
html += `</div>`; // Cierre de period-section
|
| 1329 |
-
});
|
| 1330 |
-
|
| 1331 |
-
document.getElementById('modalBody').innerHTML = html;
|
| 1332 |
-
$('#planDetailModal').modal('show');
|
| 1333 |
-
}
|
| 1334 |
-
|
| 1335 |
-
/**
|
| 1336 |
-
* Función para confirmar la eliminación de un plan
|
| 1337 |
-
*/
|
| 1338 |
-
function confirmDeletePlan(planId) {
|
| 1339 |
-
if (confirm('¿Estás seguro de que quieres eliminar este plan de entrenamiento? Esta acción es irreversible.')) {
|
| 1340 |
-
deletePlan(planId);
|
| 1341 |
-
loadPlanList();
|
| 1342 |
-
updateDashboard();
|
| 1343 |
-
}
|
| 1344 |
-
}
|
| 1345 |
-
|
| 1346 |
-
/**
|
| 1347 |
-
* Función (vacía en el original) que se debe implementar para restablecer el formulario
|
| 1348 |
-
*/
|
| 1349 |
-
function resetForm() {
|
| 1350 |
-
document.getElementById('trainingForm').reset();
|
| 1351 |
-
document.getElementById('suggestedHrMax').textContent = '--';
|
| 1352 |
-
document.getElementById('imc').value = '';
|
| 1353 |
-
document.getElementById('imcCategory').textContent = '';
|
| 1354 |
-
document.getElementById('prepRacesList').innerHTML = '';
|
| 1355 |
-
prepRaceCounter = 0;
|
| 1356 |
-
}
|
| 1357 |
-
|
| 1358 |
-
/**
|
| 1359 |
-
* Función (vacía en el original) que se debe implementar para actualizar el Dashboard
|
| 1360 |
-
*/
|
| 1361 |
-
function updateDashboard() {
|
| 1362 |
-
// Lógica para actualizar las estadísticas o resúmenes en el dashboard
|
| 1363 |
-
const plans = getPlans();
|
| 1364 |
-
const totalPlans = plans.length;
|
| 1365 |
-
|
| 1366 |
-
// Estadísticas según el rol
|
| 1367 |
-
if (currentUser && currentUser.role === 'admin') {
|
| 1368 |
-
const adminPlans = plans.length;
|
| 1369 |
-
document.getElementById('dashboardStat1').textContent = adminPlans;
|
| 1370 |
-
document.getElementById('dashboardStat1Title').textContent = 'Planes Creados';
|
| 1371 |
-
document.getElementById('dashboardStat2Title').textContent = 'Planes 21K';
|
| 1372 |
-
document.getElementById('dashboardStat2').textContent = plans.filter(p => p.userData.distance === '21K').length;
|
| 1373 |
-
} else {
|
| 1374 |
-
const userPlans = plans.filter(p => p.createdBy === (currentUser ? currentUser.username : null)).length;
|
| 1375 |
-
document.getElementById('dashboardStat1').textContent = userPlans;
|
| 1376 |
-
document.getElementById('dashboardStat1Title').textContent = 'Mis Planes';
|
| 1377 |
-
document.getElementById('dashboardStat2Title').textContent = 'Planes 10K';
|
| 1378 |
-
document.getElementById('dashboardStat2').textContent = plans.filter(p => p.createdBy === (currentUser ? currentUser.username : null) && p.userData.distance === '10K').length;
|
| 1379 |
-
}
|
| 1380 |
-
|
| 1381 |
-
// Puedes añadir más lógica aquí para mostrar promedios, etc.
|
| 1382 |
-
}
|
| 1383 |
-
|
| 1384 |
-
// Inicializar el dashboard al cargar
|
| 1385 |
-
document.addEventListener('DOMContentLoaded', () => {
|
| 1386 |
-
// Si el usuario ya estaba logeado (en un caso real con persistencia)
|
| 1387 |
-
// o simplemente para asegurarse de que el dashboard tenga contenido inicial.
|
| 1388 |
-
// En este caso simple, solo se actualiza al logearse.
|
| 1389 |
-
});
|
| 1390 |
-
|
| 1391 |
-
// Nota: La función generatePDF('${plan.id}') no está definida en el código original,
|
| 1392 |
-
// por lo que generará un error al hacer clic en ese botón. Debería implementarse
|
| 1393 |
-
// utilizando alguna librería como jsPDF o html2canvas.
|
| 1394 |
</script>
|
| 1395 |
</body>
|
| 1396 |
</html>
|
|
|
|
| 1 |
<!DOCTYPE html>
|
| 2 |
<html lang="es">
|
| 3 |
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>Osorno Runners</title>
|
| 7 |
+
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
|
| 8 |
+
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
|
|
|
|
|
|
|
| 9 |
<style>
|
| 10 |
+
*{margin:0;padding:0;box-sizing:border-box}:root{--primary:#dc143c;--primary-dark:#8b0000;--secondary:#00a65a;--danger:#dd4b39;--warning:#f39c12;--info:#00c0ef;--dark:#222d32;--sidebar:#222d32;--content:#ecf0f5;--white:#fff;--text-dark:#333;--text-light:#666;--border:#ddd}body{font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;background:var(--content);color:var(--text-dark)}.login-container{display:flex;justify-content:center;align-items:center;min-height:100vh;background:linear-gradient(135deg,var(--primary),var(--primary-dark))}.login-box{background:var(--white);padding:40px;border-radius:10px;box-shadow:0 10px 40px rgba(0,0,0,.3);max-width:400px;width:100%}.login-header{text-align:center;margin-bottom:30px}.login-header i{font-size:60px;color:var(--primary);margin-bottom:15px}.header{background:var(--primary);color:var(--white);padding:15px 20px;display:flex;justify-content:space-between;align-items:center;position:fixed;top:0;left:0;right:0;z-index:1000}.menu-toggle{background:0 0;border:none;color:var(--white);font-size:24px;cursor:pointer}.logo{font-size:24px;font-weight:700;display:flex;align-items:center;gap:10px}.sidebar{position:fixed;top:60px;left:0;width:250px;height:calc(100vh - 60px);background:var(--sidebar);color:var(--white);overflow-y:auto;transition:transform .3s;z-index:999}.sidebar.hidden{transform:translateX(-100%)}.sidebar-menu{list-style:none;padding:20px 0}.sidebar-menu a{display:flex;align-items:center;gap:15px;padding:12px 20px;color:var(--white);text-decoration:none;cursor:pointer}.sidebar-menu a:hover,.sidebar-menu a.active{background:rgba(255,255,255,.1);border-left:3px solid var(--primary)}.main-content{margin-left:250px;margin-top:60px;padding:30px;transition:margin-left .3s}.main-content.expanded{margin-left:0}.stats-container{display:grid;grid-template-columns:repeat(auto-fit,minmax(250px,1fr));gap:20px;margin-bottom:30px}.stat-card{background:var(--white);border-radius:8px;padding:20px;box-shadow:0 2px 10px rgba(0,0,0,.1);display:flex;justify-content:space-between;align-items:center}.stat-icon{width:70px;height:70px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:30px;color:var(--white)}.stat-card.primary .stat-icon{background:var(--primary)}.stat-card.success .stat-icon{background:var(--secondary)}.stat-card.warning .stat-icon{background:var(--warning)}.stat-card.info .stat-icon{background:var(--info)}.box{background:var(--white);border-radius:8px;box-shadow:0 2px 10px rgba(0,0,0,.1);margin-bottom:30px}.box-header{background:#f7f7f7;padding:15px 20px;border-bottom:1px solid var(--border)}.box-body{padding:20px}.form-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(250px,1fr));gap:20px;margin-bottom:20px}.form-group{display:flex;flex-direction:column}.form-group label{font-weight:600;margin-bottom:8px;font-size:14px}.form-group input,.form-group select,.form-group textarea{padding:10px 15px;border:1px solid var(--border);border-radius:5px;font-size:14px}.form-group input:focus,.form-group select:focus{outline:0;border-color:var(--primary)}.checkbox-group{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px}.checkbox-item{display:flex;align-items:center;padding:8px;background:#f8f9fa;border-radius:5px}.section-divider{margin:30px 0 20px;padding-bottom:12px;border-bottom:3px solid var(--primary);color:var(--primary);font-size:20px;font-weight:700}.btn{padding:12px 30px;border:none;border-radius:5px;font-size:16px;font-weight:600;cursor:pointer;display:inline-flex;align-items:center;gap:10px}.btn-primary{background:var(--primary);color:var(--white)}.btn-success{background:var(--secondary);color:var(--white)}.btn-danger{background:var(--danger);color:var(--white)}.btn-sm{padding:6px 15px;font-size:14px}.btn-secondary{background:#6c757d;color:var(--white)}.plan-list{display:grid;gap:20px}.plan-card{background:var(--white);border-radius:8px;box-shadow:0 2px 10px rgba(0,0,0,.1);padding:20px}.alert{padding:15px 20px;border-radius:5px;margin-bottom:20px;display:flex;align-items:center;gap:10px}.alert-info{background:#d1ecf1;color:#0c5460;border-left:4px solid var(--info)}.hidden{display:none!important}.prep-race-item{background:#f8f9fa;padding:15px;border-radius:8px;margin-bottom:15px;border-left:4px solid var(--primary)}@media(max-width:768px){.sidebar{transform:translateX(-100%)}.main-content{margin-left:0}}
|
| 11 |
</style>
|
| 12 |
+
</head>
|
| 13 |
+
<body>
|
| 14 |
<div id="loginScreen" class="login-container">
|
| 15 |
<div class="login-box">
|
| 16 |
<div class="login-header">
|
|
|
|
| 20 |
</div>
|
| 21 |
<form id="loginForm">
|
| 22 |
<div class="form-group">
|
| 23 |
+
<label><i class="fas fa-user"></i> Usuario</label>
|
| 24 |
<input type="text" id="loginUsername" required placeholder="USER o ADMIN">
|
| 25 |
</div>
|
| 26 |
<div class="form-group" style="margin-top:15px">
|
| 27 |
+
<label><i class="fas fa-lock"></i> Contraseña</label>
|
| 28 |
+
<input type="password" id="loginPassword" required>
|
| 29 |
</div>
|
| 30 |
<button type="submit" class="btn btn-primary" style="width:100%;margin-top:20px;justify-content:center">
|
| 31 |
<i class="fas fa-sign-in-alt"></i> Iniciar Sesión
|
| 32 |
</button>
|
| 33 |
</form>
|
| 34 |
+
<div style="margin-top:20px;text-align:center;color:#666;font-size:13px">
|
| 35 |
+
<p><strong>Usuario:</strong> USER / <strong>Pass:</strong> 123</p>
|
| 36 |
+
<p><strong>Admin:</strong> ADMIN / <strong>Pass:</strong> 123</p>
|
| 37 |
</div>
|
| 38 |
</div>
|
| 39 |
</div>
|
| 40 |
|
| 41 |
<div id="appScreen" class="hidden">
|
| 42 |
<header class="header">
|
| 43 |
+
<div style="display:flex;align-items:center;gap:15px">
|
| 44 |
<button class="menu-toggle" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
|
| 45 |
<div class="logo"><i class="fas fa-running"></i><span>Osorno Runners</span></div>
|
| 46 |
</div>
|
| 47 |
+
<div style="display:flex;align-items:center;gap:20px">
|
|
|
|
|
|
|
| 48 |
<span id="currentUserName">Usuario</span>
|
| 49 |
+
<button class="btn-danger" style="padding:8px 15px;border:none;border-radius:5px;cursor:pointer" onclick="logout()">
|
| 50 |
+
<i class="fas fa-sign-out-alt"></i> Salir
|
| 51 |
+
</button>
|
| 52 |
</div>
|
| 53 |
</header>
|
| 54 |
|
|
|
|
| 62 |
|
| 63 |
<main class="main-content" id="mainContent">
|
| 64 |
<section id="dashboard-section">
|
| 65 |
+
<h1 style="margin-bottom:30px"><i class="fas fa-tachometer-alt"></i> Dashboard</h1>
|
| 66 |
<div class="stats-container">
|
| 67 |
<div class="stat-card primary">
|
| 68 |
+
<div><h3 style="font-size:14px;color:#666;margin-bottom:10px">PLANES CREADOS</h3><p id="stat-plans" style="font-size:28px;font-weight:700">0</p></div>
|
| 69 |
<div class="stat-icon"><i class="fas fa-list-alt"></i></div>
|
| 70 |
</div>
|
| 71 |
<div class="stat-card success">
|
| 72 |
+
<div><h3 style="font-size:14px;color:#666;margin-bottom:10px">TOTAL ATLETAS</h3><p id="stat-users" style="font-size:28px;font-weight:700">0</p></div>
|
| 73 |
<div class="stat-icon"><i class="fas fa-users"></i></div>
|
| 74 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
</div>
|
| 76 |
+
<div class="alert alert-info"><i class="fas fa-info-circle"></i><span>Sistema conectado a base de datos SQLite en HuggingFace Space</span></div>
|
| 77 |
</section>
|
| 78 |
|
| 79 |
<section id="new-plan-section" class="hidden">
|
| 80 |
<h1 style="margin-bottom:30px"><i class="fas fa-plus-circle"></i> Crear Nuevo Plan</h1>
|
| 81 |
<div class="box">
|
| 82 |
+
<div class="box-header"><h3 style="font-size:18px;font-weight:700"><i class="fas fa-user-circle"></i> Información del Atleta</h3></div>
|
| 83 |
<div class="box-body">
|
| 84 |
<form id="trainingForm">
|
| 85 |
<div class="form-grid">
|
| 86 |
<div class="form-group">
|
| 87 |
+
<label><i class="fas fa-user"></i> Nombre *</label>
|
| 88 |
+
<input type="text" id="athleteName" required>
|
| 89 |
</div>
|
| 90 |
<div class="form-group">
|
| 91 |
+
<label><i class="fas fa-birthday-cake"></i> Edad *</label>
|
| 92 |
+
<input type="number" id="athleteAge" required min="10" max="100">
|
| 93 |
</div>
|
| 94 |
<div class="form-group">
|
| 95 |
+
<label><i class="fas fa-layer-group"></i> Experiencia *</label>
|
| 96 |
<select id="experience" required>
|
| 97 |
<option value="">Selecciona...</option>
|
| 98 |
<option value="principiante">Principiante</option>
|
|
|
|
| 104 |
<div class="section-divider"><i class="fas fa-weight"></i> Antropometría</div>
|
| 105 |
<div class="form-grid">
|
| 106 |
<div class="form-group">
|
| 107 |
+
<label>Peso (kg) *</label>
|
| 108 |
+
<input type="number" id="weight" required min="30" max="200" step="0.1">
|
| 109 |
</div>
|
| 110 |
<div class="form-group">
|
| 111 |
+
<label>Talla (cm) *</label>
|
| 112 |
+
<input type="number" id="height" required min="100" max="250">
|
| 113 |
</div>
|
| 114 |
<div class="form-group">
|
| 115 |
+
<label>IMC</label>
|
| 116 |
+
<input type="text" id="imc" readonly style="background:#e9ecef">
|
|
|
|
| 117 |
</div>
|
| 118 |
</div>
|
| 119 |
<div class="section-divider"><i class="fas fa-heartbeat"></i> Datos Fisiológicos</div>
|
| 120 |
<div class="form-grid">
|
| 121 |
<div class="form-group">
|
| 122 |
+
<label>FC Máxima (bpm) *</label>
|
| 123 |
+
<input type="number" id="hrMax" required min="100" max="220">
|
|
|
|
| 124 |
</div>
|
| 125 |
<div class="form-group">
|
| 126 |
+
<label>FC Reposo (bpm) *</label>
|
| 127 |
+
<input type="number" id="hrRest" required min="30" max="100">
|
| 128 |
</div>
|
| 129 |
<div class="form-group">
|
| 130 |
+
<label>VO2Max (opcional)</label>
|
| 131 |
+
<input type="number" id="vo2max" min="20" max="90" step="0.1">
|
|
|
|
| 132 |
</div>
|
| 133 |
</div>
|
| 134 |
+
<div class="section-divider"><i class="fas fa-bullseye"></i> Objetivo</div>
|
| 135 |
<div class="form-grid">
|
| 136 |
<div class="form-group">
|
| 137 |
+
<label>Distancia *</label>
|
| 138 |
<select id="distance" required>
|
| 139 |
<option value="">Selecciona...</option>
|
| 140 |
<option value="5K">5K</option>
|
|
|
|
| 144 |
</select>
|
| 145 |
</div>
|
| 146 |
<div class="form-group">
|
| 147 |
+
<label>Ritmo (min/km) *</label>
|
| 148 |
+
<input type="text" id="targetPace" required placeholder="4:30">
|
| 149 |
</div>
|
| 150 |
<div class="form-group">
|
| 151 |
+
<label>Fecha Carrera *</label>
|
| 152 |
<input type="date" id="raceDate" required>
|
| 153 |
</div>
|
| 154 |
</div>
|
|
|
|
| 165 |
<label class="checkbox-item"><input type="checkbox" name="trainingDays" value="domingo">Domingo</label>
|
| 166 |
</div>
|
| 167 |
</div>
|
| 168 |
+
<div style="margin-top:30px">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
<button type="submit" class="btn btn-success"><i class="fas fa-check"></i> Generar Plan</button>
|
|
|
|
| 170 |
</div>
|
| 171 |
</form>
|
| 172 |
</div>
|
|
|
|
| 177 |
<h1 style="margin-bottom:30px"><i class="fas fa-list-ul"></i> Planes de Entrenamiento</h1>
|
| 178 |
<div id="planListContent" class="plan-list"></div>
|
| 179 |
<div id="noPlanPlaceholder" class="hidden">
|
| 180 |
+
<div class="alert alert-info"><i class="fas fa-info-circle"></i><span>No hay planes disponibles</span></div>
|
| 181 |
</div>
|
| 182 |
</section>
|
| 183 |
</main>
|
| 184 |
</div>
|
| 185 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
<script>
|
| 187 |
+
let currentUser=null;const API_URL='/api';async function apiCall(endpoint,data){try{const response=await fetch(API_URL+endpoint,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)});return await response.json()}catch(e){console.error('API Error:',e);return{success:false,error:e.message}}}document.getElementById('loginForm').addEventListener('submit',async function(e){e.preventDefault();const username=document.getElementById('loginUsername').value.toUpperCase(),password=document.getElementById('loginPassword').value,result=await apiCall('/login',{username:username,password:password});if(result.success){currentUser=result.user;document.getElementById('loginScreen').classList.add('hidden');document.getElementById('appScreen').classList.remove('hidden');document.getElementById('currentUserName').textContent=currentUser.name;currentUser.role==='user'&&(document.getElementById('menu-new-plan').style.display='none');loadPlans()}else alert('Usuario o contraseña incorrectos')});function logout(){currentUser=null;document.getElementById('appScreen').classList.add('hidden');document.getElementById('loginScreen').classList.remove('hidden');document.getElementById('loginForm').reset()}function toggleSidebar(){document.getElementById('sidebar').classList.toggle('hidden');document.getElementById('mainContent').classList.toggle('expanded')}function showSection(section){document.querySelectorAll('main > section').forEach(s=>s.classList.add('hidden'));document.querySelectorAll('.sidebar-menu a').forEach(a=>a.classList.remove('active'));if('dashboard'===section)document.getElementById('dashboard-section').classList.remove('hidden');else if('new-plan'===section){if(currentUser&&'admin'===currentUser.role)document.getElementById('new-plan-section').classList.remove('hidden');else{alert('Solo administradores pueden crear planes');return}}else'plan-list'===section&&(document.getElementById('plan-list-section').classList.remove('hidden'),loadPlans());window.event&&window.event.target&&window.event.target.closest('a').classList.add('active')}async function loadPlans(){const result=await apiCall('/get_plans',{username:currentUser.username,role:currentUser.role});if(result.success){const plans=result.plans,listContent=document.getElementById('planListContent'),placeholder=document.getElementById('noPlanPlaceholder');if(0===plans.length){placeholder.classList.remove('hidden');listContent.innerHTML='';return}placeholder.classList.add('hidden');let html='';plans.forEach(plan=>{html+=`<div class="plan-card"><div><h3><i class="fas fa-user"></i> ${plan.userData.name}</h3><p><strong>Objetivo:</strong> ${plan.userData.distance} - ${plan.totalWeeks} sem</p></div><div style="display:flex;gap:10px"><button class="btn btn-success btn-sm" onclick="generatePDF(${plan.id})"><i class="fas fa-file-pdf"></i> PDF</button>${currentUser&&'admin'===currentUser.role?`<button class="btn btn-danger btn-sm" onclick="deletePlan(${plan.id})"><i class="fas fa-trash"></i></button>`:''}</div></div>`});listContent.innerHTML=html;document.getElementById('stat-plans').textContent=plans.length}}document.getElementById('trainingForm').addEventListener('submit',async function(e){e.preventDefault();const trainingDays=Array.from(document.querySelectorAll('input[name="trainingDays"]:checked')).map(cb=>cb.value);if(trainingDays.length<3)return void alert('Selecciona al menos 3 días');const plan={userData:{name:document.getElementById('athleteName').value,age:parseInt(document.getElementById('athleteAge').value),experience:document.getElementById('experience').value,weight:parseFloat(document.getElementById('weight').value),height:parseFloat(document.getElementById('height').value),imc:document.getElementById('imc').value,hrMax:parseInt(document.getElementById('hrMax').value),hrRest:parseInt(document.getElementById('hrRest').value),vo2max:document.getElementById('vo2max').value||null,distance:document.getElementById('distance').value,targetPace:document.getElementById('targetPace').value,raceDate:document.getElementById('raceDate').value,trainingDays:trainingDays},totalWeeks:12,weeklyPlans:[]};const result=await apiCall('/save_plan',{plan:JSON.stringify(plan),username:currentUser.username});result.success?(alert('Plan creado exitosamente'),document.getElementById('trainingForm').reset(),showSection('plan-list')):alert('Error al crear plan: '+result.error)});async function deletePlan(planId){if(confirm('¿Eliminar este plan?')){const result=await apiCall('/delete_plan',{plan_id:planId});result.success?(alert('Plan eliminado'),loadPlans()):alert('Error al eliminar')}}function generatePDF(planId){alert('Generación de PDF disponible en versión completa')}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
</script>
|
| 189 |
</body>
|
| 190 |
</html>
|
requirements.txt
CHANGED
|
@@ -1,10 +1 @@
|
|
| 1 |
-
|
| 2 |
-
flask-cors
|
| 3 |
-
python-dotenv
|
| 4 |
-
datasets
|
| 5 |
-
transformers
|
| 6 |
-
torch
|
| 7 |
-
faiss-cpu
|
| 8 |
-
langchain
|
| 9 |
-
langchain-community
|
| 10 |
-
google-genai
|
|
|
|
| 1 |
+
gradio==4.44.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|