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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
from flask import Flask, request, jsonify
|
| 4 |
+
from flask_cors import CORS
|
| 5 |
+
from dotenv import load_dotenv
|
| 6 |
+
|
| 7 |
+
# --- RAG/LLM Imports ---
|
| 8 |
+
from datasets import load_dataset
|
| 9 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 10 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 11 |
+
from langchain_community.vectorstores import FAISS
|
| 12 |
+
from langchain_core.prompts import ChatPromptTemplate
|
| 13 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 14 |
+
from langchain.chains.combine_documents import create_stuff_documents_chain
|
| 15 |
+
from langchain.chains import create_retrieval_chain
|
| 16 |
+
|
| 17 |
+
# Cargar variables de entorno
|
| 18 |
+
load_dotenv()
|
| 19 |
+
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
| 20 |
+
|
| 21 |
+
if not GEMINI_API_KEY:
|
| 22 |
+
raise ValueError("La variable de entorno GEMINI_API_KEY no está configurada.")
|
| 23 |
+
|
| 24 |
+
# --- Configuración de Flask ---
|
| 25 |
+
app = Flask(__name__)
|
| 26 |
+
# Importante: Permite que tu frontend (localhost:XXXX) se conecte al backend
|
| 27 |
+
CORS(app)
|
| 28 |
+
|
| 29 |
+
# --- Configuración del RAG Pipeline ---
|
| 30 |
+
|
| 31 |
+
# Paso 1: Cargar el dataset y crear embeddings (Esto solo ocurre una vez al iniciar el servidor)
|
| 32 |
+
DATASET_NAME = "florentgbelidji/running-science"
|
| 33 |
+
VECTOR_STORE_PATH = "faiss_running_index"
|
| 34 |
+
|
| 35 |
+
# Función para inicializar el almacén vectorial FAISS
|
| 36 |
+
def initialize_vector_store():
|
| 37 |
+
print(f"Cargando dataset: {DATASET_NAME}...")
|
| 38 |
+
|
| 39 |
+
# Cargar el dataset de Hugging Face
|
| 40 |
+
dataset = load_dataset(DATASET_NAME)
|
| 41 |
+
|
| 42 |
+
# Combinar todas las columnas relevantes en un solo texto por fila
|
| 43 |
+
documents = []
|
| 44 |
+
for item in dataset['train']:
|
| 45 |
+
# Asumiendo que las columnas son 'text', 'title', etc.
|
| 46 |
+
# Ajusta esto si el dataset tiene nombres de columna diferentes
|
| 47 |
+
content = f"Título: {item.get('title', 'Sin título')}. Texto: {item.get('text', 'Sin contenido')}"
|
| 48 |
+
documents.append(content)
|
| 49 |
+
|
| 50 |
+
# Dividir el texto en chunks (trozos) para el RAG
|
| 51 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)
|
| 52 |
+
docs = text_splitter.create_documents(documents)
|
| 53 |
+
|
| 54 |
+
print(f"Creando embeddings y almacén FAISS con {len(docs)} chunks...")
|
| 55 |
+
|
| 56 |
+
# Crear embeddings (Representación vectorial del texto)
|
| 57 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 58 |
+
|
| 59 |
+
# Crear la base de datos vectorial FAISS
|
| 60 |
+
vector_store = FAISS.from_documents(docs, embeddings)
|
| 61 |
+
vector_store.save_local(VECTOR_STORE_PATH)
|
| 62 |
+
print("Almacén FAISS creado y guardado.")
|
| 63 |
+
return vector_store
|
| 64 |
+
|
| 65 |
+
# Verificar si el índice FAISS existe, si no, crearlo.
|
| 66 |
+
if not os.path.exists(VECTOR_STORE_PATH):
|
| 67 |
+
vector_store = initialize_vector_store()
|
| 68 |
+
else:
|
| 69 |
+
print("Cargando almacén FAISS existente...")
|
| 70 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 71 |
+
vector_store = FAISS.load_local(VECTOR_STORE_PATH, embeddings, allow_dangerous_deserialization=True)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
# Inicializar el LLM (Gemini)
|
| 75 |
+
llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash", temperature=0.7)
|
| 76 |
+
|
| 77 |
+
# Definir el prompt del sistema y usuario para el RAG
|
| 78 |
+
SYSTEM_PROMPT = (
|
| 79 |
+
"Eres un entrenador de running de élite basado en la ciencia, especializado en el conocimiento "
|
| 80 |
+
"proporcionado en el CONTEXTO. Tu tarea es generar un plan de entrenamiento semanal detallado "
|
| 81 |
+
"para el atleta. El plan DEBE estar en formato JSON. Si el CONTEXTO no cubre un punto, usa el "
|
| 82 |
+
"sentido común del running. El JSON debe incluir solo el objeto del plan, sin explicaciones ni texto adicional."
|
| 83 |
+
"\n\nCONTEXTO de Running Science: {context}"
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
# Template del plan JSON (adaptado a la estructura de tu frontend)
|
| 87 |
+
JSON_TEMPLATE = """
|
| 88 |
+
{{
|
| 89 |
+
"id": "AI-{athleteName}-{distance}-{date}",
|
| 90 |
+
"createdBy": "Sistema IA RAG",
|
| 91 |
+
"createdAt": "{current_date}",
|
| 92 |
+
"userData": {{"athleteName": "{athleteName}", "distance": "{distance}", "targetPace": "{targetPace}", "raceDate": "{raceDate}"}},
|
| 93 |
+
"totalWeeks": {totalWeeks},
|
| 94 |
+
"weeklyPlans": [
|
| 95 |
+
// La IA debe generar la lista de objetos semanales aquí
|
| 96 |
+
{{
|
| 97 |
+
"week": 1,
|
| 98 |
+
"theme": "Base y Adaptación",
|
| 99 |
+
"totalVolumeKm": 30,
|
| 100 |
+
"weeklySessions": [
|
| 101 |
+
{{"day": "Lunes", "type": "Descanso", "description": "Día libre", "distanceKm": 0, "paceMinKm": 0, "intensity": "N/A", "notes": ""}},
|
| 102 |
+
{{"day": "Martes", "type": "Rodaje Suave", "description": "Rodaje regenerativo", "distanceKm": 8, "paceMinKm": 6.00, "intensity": "Zona 2", "notes": "Concentrarse en la forma."}}
|
| 103 |
+
// ... Llenar el resto de la semana y semanas
|
| 104 |
+
]
|
| 105 |
+
}}
|
| 106 |
+
]
|
| 107 |
+
}}
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
HUMAN_PROMPT = (
|
| 111 |
+
"Genera un plan de entrenamiento completo y detallado para el siguiente atleta y meta, "
|
| 112 |
+
"basándote en el CONTEXTO de Running Science. "
|
| 113 |
+
"El plan debe cubrir {totalWeeks} semanas e incluir las carreras preparatorias si las hay. "
|
| 114 |
+
"Los datos del atleta son: {formData}. "
|
| 115 |
+
"El plan de salida DEBE ser un objeto JSON que siga la estructura del siguiente TEMPLATE:\n"
|
| 116 |
+
f"{JSON_TEMPLATE}"
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
# Configurar la cadena RAG
|
| 120 |
+
prompt = ChatPromptTemplate.from_messages([
|
| 121 |
+
("system", SYSTEM_PROMPT),
|
| 122 |
+
("human", HUMAN_PROMPT),
|
| 123 |
+
])
|
| 124 |
+
|
| 125 |
+
# Cadena para combinar los documentos
|
| 126 |
+
document_chain = create_stuff_documents_chain(llm, prompt)
|
| 127 |
+
|
| 128 |
+
# Cadena de recuperación (Retriever)
|
| 129 |
+
retriever = vector_store.as_retriever(k=5)
|
| 130 |
+
retrieval_chain = create_retrieval_chain(retriever, document_chain)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
# --- API Endpoint ---
|
| 134 |
+
|
| 135 |
+
@app.route('/api/generate_plan', methods=['POST'])
|
| 136 |
+
def generate_plan():
|
| 137 |
+
"""Endpoint para generar el plan de entrenamiento usando RAG."""
|
| 138 |
+
try:
|
| 139 |
+
formData = request.json
|
| 140 |
+
|
| 141 |
+
# Calcular el número de semanas (una estimación simple para el prompt)
|
| 142 |
+
race_date = formData.get('raceDate')
|
| 143 |
+
|
| 144 |
+
# Una lógica simple para estimar las semanas entre hoy y la carrera (ajusta si necesitas más precisión)
|
| 145 |
+
from datetime import datetime
|
| 146 |
+
date_format = "%Y-%m-%d"
|
| 147 |
+
race_dt = datetime.strptime(race_date, date_format)
|
| 148 |
+
today_dt = datetime.now()
|
| 149 |
+
total_weeks = (race_dt - today_dt).days // 7
|
| 150 |
+
total_weeks = max(4, total_weeks) # Mínimo 4 semanas
|
| 151 |
+
|
| 152 |
+
# 1. Definir la pregunta para el retriever (lo que busca en el dataset)
|
| 153 |
+
retrieval_query = (
|
| 154 |
+
f"Plan de entrenamiento de running para {formData['distance']} en {total_weeks} semanas, "
|
| 155 |
+
f"con un ritmo objetivo de {formData['targetPace']} y experiencia {formData['experience']}. "
|
| 156 |
+
f"Datos biométricos clave: VO2Max {formData.get('vo2Max')} y FC Máx {formData.get('hrMax')}."
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
# 2. Configurar los valores para el Human Prompt
|
| 160 |
+
prompt_values = {
|
| 161 |
+
"totalWeeks": total_weeks,
|
| 162 |
+
"formData": json.dumps(formData), # Pasar los datos del formulario como JSON para el prompt
|
| 163 |
+
"athleteName": formData.get('athleteName', 'Corredor'),
|
| 164 |
+
"distance": formData.get('distance', '10K'),
|
| 165 |
+
"targetPace": formData.get('targetPace', '5:00'),
|
| 166 |
+
"raceDate": formData.get('raceDate', 'N/A'),
|
| 167 |
+
"current_date": datetime.now().isoformat()
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
# 3. Ejecutar la cadena RAG
|
| 171 |
+
response = retrieval_chain.invoke({"input": retrieval_query, **prompt_values})
|
| 172 |
+
|
| 173 |
+
# La respuesta es el plan en formato de cadena de texto JSON
|
| 174 |
+
plan_json_str = response['answer'].strip()
|
| 175 |
+
|
| 176 |
+
# 4. Intentar parsear y devolver el JSON
|
| 177 |
+
try:
|
| 178 |
+
plan_data = json.loads(plan_json_str)
|
| 179 |
+
# Asegurar un ID único para el frontend
|
| 180 |
+
plan_data['id'] = f"AI_{formData['distance']}_{datetime.now().strftime('%Y%m%d%H%M%S')}"
|
| 181 |
+
return jsonify(plan_data), 200
|
| 182 |
+
except json.JSONDecodeError:
|
| 183 |
+
print("ERROR: La IA no devolvió un JSON válido.")
|
| 184 |
+
print(f"Respuesta cruda de la IA: {plan_json_str}")
|
| 185 |
+
return jsonify({"message": "La IA no pudo generar un plan JSON válido. Inténtalo de nuevo."}), 500
|
| 186 |
+
|
| 187 |
+
except Exception as e:
|
| 188 |
+
print(f"Error interno del servidor: {e}")
|
| 189 |
+
return jsonify({"message": f"Error interno en el servidor RAG: {str(e)}", "details": str(e)}), 500
|
| 190 |
+
|
| 191 |
+
if __name__ == '__main__':
|
| 192 |
+
# Ejecutar el servidor. Asegúrate de que el puerto coincida con RAG_SERVER_URL en tu frontend (5000)
|
| 193 |
+
print("\n--- Servidor RAG de Running Science ---")
|
| 194 |
+
print(f"FAISS Index: {VECTOR_STORE_PATH}")
|
| 195 |
+
print("Iniciando servidor en http://127.0.0.1:5000")
|
| 196 |
+
app.run(debug=True, port=5000)
|
index.html
CHANGED
|
@@ -1,19 +1,1396 @@
|
|
| 1 |
-
<!
|
| 2 |
-
<html>
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
<p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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>Running Training Dashboard - 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 |
+
</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">
|
| 18 |
+
<i class="fas fa-running"></i>
|
| 19 |
+
<h2>Osorno Runners</h2>
|
| 20 |
+
<p>Sistema de Planes de Entrenamiento</p>
|
| 21 |
+
</div>
|
| 22 |
+
<form id="loginForm">
|
| 23 |
+
<div class="form-group">
|
| 24 |
+
<label for="loginUsername"><i class="fas fa-user"></i> Usuario</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 for="loginPassword"><i class="fas fa-lock"></i> Contraseña</label>
|
| 29 |
+
<input type="password" id="loginPassword" required placeholder="Contraseña">
|
| 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:var(--text-light);font-size:13px">
|
| 36 |
+
<p><strong>Usuario:</strong> USER / <strong>Contraseña:</strong> 123</p>
|
| 37 |
+
<p><strong>Administrador:</strong> ADMIN / <strong>Contraseña:</strong> 123</p>
|
| 38 |
+
</div>
|
| 39 |
+
</div>
|
| 40 |
+
</div>
|
| 41 |
+
|
| 42 |
+
<div id="appScreen" class="hidden">
|
| 43 |
+
<header class="header">
|
| 44 |
+
<div class="header-left">
|
| 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 class="header-right">
|
| 49 |
+
<div class="user-info">
|
| 50 |
+
<span class="user-badge" id="userRole">USUARIO</span>
|
| 51 |
+
<span id="currentUserName">Usuario</span>
|
| 52 |
+
<div class="user-avatar"><i class="fas fa-user"></i></div>
|
| 53 |
+
</div>
|
| 54 |
+
<button class="btn-logout" onclick="logout()"><i class="fas fa-sign-out-alt"></i> Salir</button>
|
| 55 |
+
</div>
|
| 56 |
+
</header>
|
| 57 |
+
|
| 58 |
+
<nav class="sidebar" id="sidebar">
|
| 59 |
+
<ul class="sidebar-menu">
|
| 60 |
+
<li><a href="#" class="active" onclick="showSection('dashboard')"><i class="fas fa-tachometer-alt"></i><span>Dashboard</span></a></li>
|
| 61 |
+
<li id="menu-new-plan"><a href="#" onclick="showSection('new-plan')"><i class="fas fa-plus-circle"></i><span>Nuevo Plan</span></a></li>
|
| 62 |
+
<li><a href="#" onclick="showSection('plan-list')"><i class="fas fa-list-ul"></i><span>Ver Planes</span></a></li>
|
| 63 |
+
</ul>
|
| 64 |
+
</nav>
|
| 65 |
+
|
| 66 |
+
<main class="main-content" id="mainContent">
|
| 67 |
+
<section id="dashboard-section">
|
| 68 |
+
<h1 style="margin-bottom:30px;color:var(--text-dark)"><i class="fas fa-tachometer-alt"></i> Dashboard</h1>
|
| 69 |
+
<div class="stats-container">
|
| 70 |
+
<div class="stat-card primary">
|
| 71 |
+
<div class="stat-info"><h3>Planes Creados</h3><p id="stat-plans">0</p></div>
|
| 72 |
+
<div class="stat-icon"><i class="fas fa-list-alt"></i></div>
|
| 73 |
+
</div>
|
| 74 |
+
<div class="stat-card success">
|
| 75 |
+
<div class="stat-info"><h3>Total Atletas</h3><p id="stat-users">0</p></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 class="box-title"><i class="fas fa-user-circle"></i> Información del Atleta</h3></div>
|
| 104 |
+
<div class="box-body">
|
| 105 |
+
<form id="trainingForm">
|
| 106 |
+
<div class="form-grid">
|
| 107 |
+
<div class="form-group">
|
| 108 |
+
<label for="athleteName"><i class="fas fa-user"></i> Nombre Completo *</label>
|
| 109 |
+
<input type="text" id="athleteName" required placeholder="Ej: Rodrigo Garcés">
|
| 110 |
+
</div>
|
| 111 |
+
<div class="form-group">
|
| 112 |
+
<label for="athleteAge"><i class="fas fa-birthday-cake"></i> Edad *</label>
|
| 113 |
+
<input type="number" id="athleteAge" required placeholder="Ej: 40" min="10" max="100">
|
| 114 |
+
</div>
|
| 115 |
+
<div class="form-group">
|
| 116 |
+
<label for="experience"><i class="fas fa-layer-group"></i> Experiencia *</label>
|
| 117 |
+
<select id="experience" required>
|
| 118 |
+
<option value="">Selecciona...</option>
|
| 119 |
+
<option value="principiante">Principiante</option>
|
| 120 |
+
<option value="intermedio">Intermedio</option>
|
| 121 |
+
<option value="avanzado">Avanzado</option>
|
| 122 |
+
</select>
|
| 123 |
+
</div>
|
| 124 |
+
</div>
|
| 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 for="weight"><i class="fas fa-weight-hanging"></i> Peso (kg) *</label>
|
| 129 |
+
<input type="number" id="weight" required placeholder="Ej: 75" min="30" max="200" step="0.1" oninput="calculateIMC()">
|
| 130 |
+
</div>
|
| 131 |
+
<div class="form-group">
|
| 132 |
+
<label for="height"><i class="fas fa-ruler-vertical"></i> Talla (cm) *</label>
|
| 133 |
+
<input type="number" id="height" required placeholder="Ej: 175" min="100" max="250" oninput="calculateIMC()">
|
| 134 |
+
</div>
|
| 135 |
+
<div class="form-group">
|
| 136 |
+
<label><i class="fas fa-calculator"></i> IMC</label>
|
| 137 |
+
<input type="text" id="imc" readonly placeholder="Se calculará automáticamente" style="background:#e9ecef">
|
| 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 for="hrMax"><i class="fas fa-heart"></i> FC Máxima (bpm) *</label>
|
| 145 |
+
<input type="number" id="hrMax" required placeholder="Ej: 180" min="100" max="220">
|
| 146 |
+
<small>Sugerida: 220 - edad = <span id="suggestedHrMax">--</span> bpm</small>
|
| 147 |
+
</div>
|
| 148 |
+
<div class="form-group">
|
| 149 |
+
<label for="hrRest"><i class="fas fa-bed"></i> FC en Reposo (bpm) *</label>
|
| 150 |
+
<input type="number" id="hrRest" required placeholder="Ej: 60" min="30" max="100">
|
| 151 |
+
</div>
|
| 152 |
+
<div class="form-group">
|
| 153 |
+
<label for="vo2max"><i class="fas fa-lungs"></i> VO2Max</label>
|
| 154 |
+
<input type="number" id="vo2max" placeholder="Ej: 45" min="20" max="90" step="0.1">
|
| 155 |
+
<small>Opcional</small>
|
| 156 |
+
</div>
|
| 157 |
+
</div>
|
| 158 |
+
<div class="section-divider"><i class="fas fa-bullseye"></i> Objetivo de Carrera</div>
|
| 159 |
+
<div class="form-grid">
|
| 160 |
+
<div class="form-group">
|
| 161 |
+
<label for="distance"><i class="fas fa-flag-checkered"></i> Distancia *</label>
|
| 162 |
+
<select id="distance" required>
|
| 163 |
+
<option value="">Selecciona...</option>
|
| 164 |
+
<option value="5K">5K</option>
|
| 165 |
+
<option value="10K">10K</option>
|
| 166 |
+
<option value="21K">21K</option>
|
| 167 |
+
<option value="42K">42K</option>
|
| 168 |
+
</select>
|
| 169 |
+
</div>
|
| 170 |
+
<div class="form-group">
|
| 171 |
+
<label for="targetPace"><i class="fas fa-tachometer-alt"></i> Ritmo (min/km) *</label>
|
| 172 |
+
<input type="text" id="targetPace" required placeholder="Ej: 4:30" pattern="[0-9]:[0-5][0-9]">
|
| 173 |
+
</div>
|
| 174 |
+
<div class="form-group">
|
| 175 |
+
<label for="raceDate"><i class="fas fa-calendar-check"></i> Fecha Carrera *</label>
|
| 176 |
+
<input type="date" id="raceDate" required>
|
| 177 |
+
</div>
|
| 178 |
+
</div>
|
| 179 |
+
<div class="section-divider"><i class="fas fa-calendar-day"></i> Disponibilidad</div>
|
| 180 |
+
<div class="form-group">
|
| 181 |
+
<label>Días de Entrenamiento *</label>
|
| 182 |
+
<div class="checkbox-group">
|
| 183 |
+
<label class="checkbox-item"><input type="checkbox" name="trainingDays" value="lunes">Lunes</label>
|
| 184 |
+
<label class="checkbox-item"><input type="checkbox" name="trainingDays" value="martes">Martes</label>
|
| 185 |
+
<label class="checkbox-item"><input type="checkbox" name="trainingDays" value="miércoles">Miércoles</label>
|
| 186 |
+
<label class="checkbox-item"><input type="checkbox" name="trainingDays" value="jueves">Jueves</label>
|
| 187 |
+
<label class="checkbox-item"><input type="checkbox" name="trainingDays" value="viernes">Viernes</label>
|
| 188 |
+
<label class="checkbox-item"><input type="checkbox" name="trainingDays" value="sábado">Sábado</label>
|
| 189 |
+
<label class="checkbox-item"><input type="checkbox" name="trainingDays" value="domingo">Domingo</label>
|
| 190 |
+
</div>
|
| 191 |
+
</div>
|
| 192 |
+
<div class="section-divider"><i class="fas fa-dumbbell"></i> Cross Training</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>
|
| 217 |
+
</div>
|
| 218 |
+
</section>
|
| 219 |
+
|
| 220 |
+
<section id="plan-list-section" class="hidden">
|
| 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.</span></div>
|
| 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>
|
procfile
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
web: python app.py
|
requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Flask
|
| 2 |
+
flask-cors
|
| 3 |
+
python-dotenv
|
| 4 |
+
datasets
|
| 5 |
+
transformers
|
| 6 |
+
torch
|
| 7 |
+
faiss-cpu
|
| 8 |
+
langchain
|
| 9 |
+
langchain-community
|
| 10 |
+
google-genai
|