From 9a987baa5cc5f93d97699fffb305d3a4f73c4975 Mon Sep 17 00:00:00 2001 From: "Wayne H. Shephard" Date: Fri, 20 Nov 2026 01:03:35 +0300 Subject: [PATCH] lots of work done, dashboards added --- backend/auth.py | 12 +- backend/main.py | 8 +- backend/models.py | 22 +- backend/requirements.txt | 16 +- backend/routers/bootstrap.py | 157 +++++ backend/routers/sync.py | 178 ++--- backend/schemas.py | 1 - docker-compose.yml | 23 +- frontend/js/api.js | 79 ++- frontend/js/app.js | 270 ++++++-- frontend/js/auth.js | 57 +- frontend/js/logic/metrics.js | 89 ++- frontend/js/logic/settings.js | 905 ++++++++++++++++--------- frontend/js/modals/metrics-modal.js | 165 ++++- frontend/js/render/dashboard-screen.js | 96 +++ frontend/js/render/dashboard.js | 381 +++++++++++ frontend/js/state.js | 193 ++++-- frontend/js/sync.js | 826 +++++++++++++++++++--- frontend/nginx.conf | 19 +- 19 files changed, 2712 insertions(+), 785 deletions(-) create mode 100644 backend/routers/bootstrap.py create mode 100644 frontend/js/render/dashboard-screen.js create mode 100644 frontend/js/render/dashboard.js diff --git a/backend/auth.py b/backend/auth.py index fa6a202..be92786 100644 --- a/backend/auth.py +++ b/backend/auth.py @@ -1,3 +1,7 @@ +import os +from datetime import datetime, timedelta, timezone +from typing import Optional + import bcrypt import jwt from jwt.exceptions import PyJWTError @@ -18,12 +22,16 @@ bearer_scheme = HTTPBearer(auto_error=False) def hash_password(password: str) -> str: - return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") + # bcrypt.hashpw ожидает байты, возвращает байты. Декодируем в string для хранения. + salt = bcrypt.gensalt() + hashed = bcrypt.hashpw(password.encode('utf-8'), salt) + return hashed.decode('utf-8') def verify_password(password: str, hashed: str) -> bool: try: - return bcrypt.checkpw(password.encode("utf-8"), hashed.encode("utf-8")) + # bcrypt.checkpw ожидает байты + return bcrypt.checkpw(password.encode('utf-8'), hashed.encode('utf-8')) except ValueError: return False diff --git a/backend/main.py b/backend/main.py index 6316a86..bb8f783 100644 --- a/backend/main.py +++ b/backend/main.py @@ -3,9 +3,10 @@ import os from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware - from database import engine, Base +from pathlib import Path +import routers.bootstrap import routers.auth import routers.clients import routers.workout_types @@ -14,6 +15,10 @@ import routers.exercises import routers.metrics import routers.sync +# Создаем директорию для БД, если её нет +db_path = os.getenv("GYM_DB_PATH", "./gym.db") +Path(db_path).parent.mkdir(parents=True, exist_ok=True) + # Гарантируем, что директория существует os.makedirs(os.path.dirname(os.getenv("GYM_DB_PATH", "./gym.db")), exist_ok=True) @@ -41,6 +46,7 @@ app.include_router(routers.workouts.router) app.include_router(routers.exercises.router) app.include_router(routers.metrics.router) app.include_router(routers.sync.router) +app.include_router(routers.bootstrap.router) @app.get("/") diff --git a/backend/models.py b/backend/models.py index bedf989..d98f368 100644 --- a/backend/models.py +++ b/backend/models.py @@ -11,7 +11,6 @@ from sqlalchemy.orm import relationship from database import Base - class User(Base): __tablename__ = "users" @@ -19,7 +18,7 @@ class User(Base): username = Column(String, unique=True, nullable=False, index=True) password_hash = Column(String, nullable=False) display_name = Column(String, default="") - role = Column(String, default="personal") # personal | trainer + role = Column(String, default="personal") created_at = Column(String) @@ -32,7 +31,10 @@ class WorkoutType(Base): sort_order = Column(Integer, default=0) created_at = Column(String) + # ВАЖНО: Эта строка должна быть здесь! exercises = relationship("Exercise", back_populates="workout_type") + + # Если есть другие отношения, они тоже должны быть прописаны workouts = relationship("Workout", back_populates="workout_type") @@ -42,20 +44,16 @@ class Exercise(Base): id = Column(Integer, primary_key=True, index=True) sync_id = Column(String, unique=True, nullable=False, index=True) - # NULL = глобальный справочник, иначе — личное упражнение пользователя owner_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), index=True) - - workout_type_id = Column( - Integer, - ForeignKey("workout_types.id", ondelete="SET NULL"), - index=True, - ) + workout_type_id = Column(Integer, ForeignKey("workout_types.id", ondelete="SET NULL"), index=True) name = Column(String, nullable=False, index=True) created_at = Column(String) updated_at = Column(String) + # ВАЖНО: И эта строка тоже! workout_type = relationship("WorkoutType", back_populates="exercises") + workout_exercises = relationship("WorkoutExercise", back_populates="exercise") @@ -73,7 +71,7 @@ class Client(Base): color = Column(String) is_active = Column(Integer, default=1) - created_at = Column(String) + created_at = Column(String, default=lambda: datetime.utcnow().isoformat()) updated_at = Column(String) workouts = relationship("Workout", back_populates="client") @@ -232,7 +230,7 @@ class MetricType(Base): unit = Column(String, default="см") category = Column(String, default="body") sort_order = Column(Integer, default=0) - created_at = Column(String) + created_at = Column(String, default=lambda: datetime.utcnow().isoformat()) metric_values = relationship("BodyMetricValue", back_populates="metric_type") @@ -248,7 +246,7 @@ class BodyMetric(Base): metric_date = Column(String, nullable=False) notes = Column(String, default="") - created_at = Column(String) + created_at = Column(String, default=lambda: datetime.utcnow().isoformat()) client = relationship("Client", back_populates="body_metrics") values = relationship( diff --git a/backend/requirements.txt b/backend/requirements.txt index 5ddf5e3..d6944fb 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -1,9 +1,7 @@ --i https://mirror.yandex.ru/pypi/simple/ ---trusted-host mirror.yandex.ru -fastapi==0.104.1 -uvicorn[standard]==0.24.0 -sqlalchemy==2.0.23 -pydantic==2.5.0 -python-multipart==0.0.6 -PyJWT==2.8.0 -bcrypt==4.1.2 +fastapi==0.115.6 +uvicorn[standard]==0.32.1 +sqlalchemy==2.0.36 +pydantic==2.10.4 +python-multipart==0.0.20 +PyJWT==2.10.1 +bcrypt==4.2.1 diff --git a/backend/routers/bootstrap.py b/backend/routers/bootstrap.py new file mode 100644 index 0000000..0dc7778 --- /dev/null +++ b/backend/routers/bootstrap.py @@ -0,0 +1,157 @@ +# backend/routers/bootstrap.py + +from fastapi import APIRouter, Depends, HTTPException +from sqlalchemy.orm import Session, joinedload +from sqlalchemy import or_ +import auth +import database +import models +import schemas + +router = APIRouter( + prefix="/bootstrap", + tags=["bootstrap"], + dependencies=[Depends(auth.get_current_user)], +) + +@router.get("/") +def get_bootstrap_data( + current_user: models.User = Depends(auth.get_current_user), + db: Session = Depends(database.get_db), +): + """ + Возвращает ВСЕ данные пользователя для инициализации фронтенда. + Безопасная версия с проверкой NULL-связей. + """ + + try: + # 1. Типы тренировок (глобальные) + workout_types = db.query(models.WorkoutType).order_by(models.WorkoutType.sort_order).all() + + # 2. Типы замеров (глобальные) + metric_types = db.query(models.MetricType).order_by(models.MetricType.sort_order).all() + + # 3. Клиенты пользователя + clients = db.query(models.Client).filter(models.Client.owner_id == current_user.id).all() + + # 4. Упражнения пользователя + глобальные + exercises = db.query(models.Exercise).filter( + or_( + models.Exercise.owner_id == current_user.id, + models.Exercise.owner_id.is_(None) + ) + ).all() + + # 5. Тренировки пользователя (полные, с подходами и кардио) + workouts = db.query(models.Workout).options( + joinedload(models.Workout.workout_exercises).joinedload(models.WorkoutExercise.sets).joinedload(models.Set.dropset_items), + joinedload(models.Workout.cardio_sessions), + joinedload(models.Workout.client), # Загружаем клиента, если есть + joinedload(models.Workout.workout_type) # Загружаем тип тренировки + ).filter( + models.Workout.owner_id == current_user.id + ).order_by(models.Workout.start_time.desc()).all() + + # 6. Замеры пользователя + body_metrics = db.query(models.BodyMetric).options( + joinedload(models.BodyMetric.values), + joinedload(models.BodyMetric.client) # Если нужно имя клиента в замерах + ).filter( + models.BodyMetric.owner_id == current_user.id + ).order_by(models.BodyMetric.metric_date.desc()).all() + + # --- Ручная конвертация в словари, чтобы избежать ошибок Pydantic/SQLAlchemy lazy-loading --- + + def serialize_workout(w): + wt_name = w.workout_type.name if w.workout_type else "" + client_name = w.client.full_name if w.client else None + + return { + "id": w.id, + "sync_id": w.sync_id, + "owner_id": w.owner_id, + "client_id": w.client_id, + "workout_type_id": w.workout_type_id, + "start_time": w.start_time, + "end_time": w.end_time, + "notes": w.notes, + "synced": w.synced, + "created_at": w.created_at, + "updated_at": w.updated_at, + # Дополнительные поля для фронта + "workout_type_name": wt_name, + "client_full_name": client_name, + + "workout_exercises": [ + { + "id": ex.id, + "sync_id": ex.sync_id, + "exercise_name": ex.exercise_name, + "sort_order": ex.sort_order, + "sets": [ + { + "id": s.id, + "sync_id": s.sync_id, + "is_dropset": s.is_dropset, + "weight": s.weight, + "reps": s.reps, + "rating": s.rating, + "notes": s.notes, + "timestamp": s.timestamp, + "dropset_items": [ + { + "id": di.id, + "weight": di.weight, + "reps": di.reps, + "sort_order": di.sort_order + } for di in (s.dropset_items or []) + ] + } for s in (ex.sets or []) + ] + } for ex in (w.workout_exercises or []) + ], + "cardio_sessions": [ + { + "id": c.id, + "sync_id": c.sync_id, + "cardio_type": c.cardio_type, + "purpose": c.purpose, + "duration": c.duration, + "distance": c.distance, + "speed": c.speed, + "incline": c.incline, + "resistance": c.resistance, + "notes": c.notes, + "sort_order": c.sort_order + } for c in (w.cardio_sessions or []) + ] + } + + def serialize_metric(m): + return { + "id": m.id, + "sync_id": m.sync_id, + "client_id": m.client_id, + "metric_date": m.metric_date, + "notes": m.notes, + "values": [ + { + "id": v.id, + "metric_type_id": v.metric_type_id, + "value": v.value + } for v in (m.values or []) + ] + } + + return { + "workout_types": [{"id": t.id, "sync_id": t.sync_id, "name": t.name, "sort_order": t.sort_order} for t in workout_types], + "metric_types": [{"id": t.id, "sync_id": t.sync_id, "name": t.name, "unit": t.unit, "category": t.category, "sort_order": t.sort_order} for t in metric_types], + "clients": [{"id": c.id, "sync_id": c.sync_id, "full_name": c.full_name, "birth_date": c.birth_date, "goal": c.goal, "color": c.color} for c in clients], + "exercises": [{"id": e.id, "sync_id": e.sync_id, "name": e.name, "workout_type_id": e.workout_type_id} for e in exercises], + "workouts": [serialize_workout(w) for w in workouts], + "body_metrics": [serialize_metric(m) for m in body_metrics], + } + + except Exception as e: + print(f"❌ CRITICAL ERROR IN BOOTSTRAP: {e}") + raise HTTPException(status_code=500, detail=str(e)) diff --git a/backend/routers/sync.py b/backend/routers/sync.py index 19d35fd..4b67e44 100644 --- a/backend/routers/sync.py +++ b/backend/routers/sync.py @@ -168,26 +168,21 @@ def upsert_exercise( return obj, "created" -def resolve_client_id_from_sync_id( - db: Session, - user: models.User, - client_sync_id: Optional[str], - client_map: Dict[str, int], -) -> Optional[int]: +def resolve_client_id_from_sync_id(db, user, client_sync_id, client_map): + """Ищет client_id по sync_id.""" if not client_sync_id: return None + # 1. Проверяем кэш карты клиентов (клиенты, созданные в этом же запросе sync) if client_sync_id in client_map: return client_map[client_sync_id] - client = ( - db.query(models.Client) - .filter( - models.Client.sync_id == client_sync_id, - models.Client.owner_id == user.id, - ) - .first() - ) + # 2. Ищем в БД среди клиентов пользователя + client = db.query(models.Client).filter( + models.Client.sync_id == client_sync_id, + models.Client.owner_id == user.id + ).first() + return client.id if client else None @@ -289,19 +284,15 @@ def create_cardio_from_payload( return db_cardio -def resolve_metric_type_for_sync( - db: Session, - value: schemas.BodyMetricValueCreate, -) -> Optional[models.MetricType]: - if value.metric_type_id: - return db.get(models.MetricType, value.metric_type_id) +def resolve_metric_type_for_sync(db, value_data): + """Находит объект MetricType по ID или sync_id.""" + if value_data.metric_type_id: + return db.get(models.MetricType, value_data.metric_type_id) - if value.metric_type_sync_id: - return ( - db.query(models.MetricType) - .filter(models.MetricType.sync_id == value.metric_type_sync_id) - .first() - ) + if value_data.metric_type_sync_id: + return db.query(models.MetricType).filter( + models.MetricType.sync_id == value_data.metric_type_sync_id + ).first() return None @@ -449,21 +440,25 @@ def sync_data( for metric_data in payload.body_metrics or []: sync_id = metric_data.sync_id or new_sync_id() + # Попытка найти существующую запись existing = db.query(models.BodyMetric).filter(models.BodyMetric.sync_id == sync_id).first() + if existing: + # --- ОБНОВЛЕНИЕ СУЩЕСТВУЮЩЕГО ЗАМЕРА --- if existing.owner_id != current_user.id: raise HTTPException(status_code=409, detail="BodyMetric sync_id belongs to another user") + # Обновляем основные поля existing.metric_date = metric_data.metric_date existing.notes = metric_data.notes or "" + # Резолвим client_id (приоритет у sync_id, затем числовой id) client_id = resolve_client_id_from_sync_id( - db, - current_user, - metric_data.client_sync_id, - client_map, + db, current_user, metric_data.client_sync_id, client_map ) - if metric_data.client_id and not client_id: + + # Если client_id не найден по sync_id, пробуем по числовому ID из payload + if not client_id and metric_data.client_id: client = ( db.query(models.Client) .filter( @@ -472,75 +467,90 @@ def sync_data( ) .first() ) - client_id = client.id if client else None + if client: + client_id = client.id existing.client_id = client_id + # Удаляем старые значения перед добавлением новых db.query(models.BodyMetricValue).filter( models.BodyMetricValue.body_metric_id == existing.id - ).delete() + ).delete(synchronize_session=False) + # Добавляем новые значения for value_data in metric_data.values or []: - mt = resolve_metric_type_for_sync(db, value_data) - if not mt: - warnings.append("Body metric value skipped: metric type not found") - continue + try: + mt = resolve_metric_type_for_sync(db, value_data) + if not mt: + warnings.append(f"BodyMetric {sync_id}: Metric type not found for value {value_data.value}") + continue - db.add( - models.BodyMetricValue( - body_metric_id=existing.id, - metric_type_id=mt.id, - value=float(value_data.value), + db.add( + models.BodyMetricValue( + body_metric_id=existing.id, + metric_type_id=mt.id, + value=float(value_data.value), + ) ) - ) + except Exception as e: + warnings.append(f"BodyMetric {sync_id}: Error adding value - {str(e)}") updated["body_metrics"] += 1 continue - client_id = resolve_client_id_from_sync_id( - db, - current_user, - metric_data.client_sync_id, - client_map, - ) - if metric_data.client_id and not client_id: - client = ( - db.query(models.Client) - .filter( - models.Client.id == metric_data.client_id, - models.Client.owner_id == current_user.id, - ) - .first() - ) - client_id = client.id if client else None + else: + # --- СОЗДАНИЕ НОВОГО ЗАМЕРА --- - db_metric = models.BodyMetric( - sync_id=sync_id, - owner_id=current_user.id, - client_id=client_id, - metric_date=metric_data.metric_date, - notes=metric_data.notes or "", - created_at=timestamp, - ) - - db.add(db_metric) - db.flush() - created["body_metrics"] += 1 - - for value_data in metric_data.values or []: - mt = resolve_metric_type_for_sync(db, value_data) - if not mt: - warnings.append("Body metric value skipped: metric type not found") - continue - - db.add( - models.BodyMetricValue( - body_metric_id=db_metric.id, - metric_type_id=mt.id, - value=float(value_data.value), - ) + # Резолвим client_id + client_id = resolve_client_id_from_sync_id( + db, current_user, metric_data.client_sync_id, client_map ) + # Fallback на числовой ID, если sync_id не сработал + if not client_id and metric_data.client_id: + client = ( + db.query(models.Client) + .filter( + models.Client.id == metric_data.client_id, + models.Client.owner_id == current_user.id, + ) + .first() + ) + if client: + client_id = client.id + + # Создаем запись метрики + db_metric = models.BodyMetric( + sync_id=sync_id, + owner_id=current_user.id, + client_id=client_id, + metric_date=metric_data.metric_date, + notes=metric_data.notes or "", + created_at=timestamp, + ) + + db.add(db_metric) + db.flush() # Получаем ID для связи со значениями + + created["body_metrics"] += 1 + + # Добавляем значения + for value_data in metric_data.values or []: + try: + mt = resolve_metric_type_for_sync(db, value_data) + if not mt: + warnings.append(f"New BodyMetric {sync_id}: Metric type not found for value {value_data.value}") + continue + + db.add( + models.BodyMetricValue( + body_metric_id=db_metric.id, + metric_type_id=mt.id, + value=float(value_data.value), + ) + ) + except Exception as e: + warnings.append(f"New BodyMetric {sync_id}: Error adding value - {str(e)}") db.commit() return schemas.SyncResponse( diff --git a/backend/schemas.py b/backend/schemas.py index ee45d3e..fb708c7 100644 --- a/backend/schemas.py +++ b/backend/schemas.py @@ -1,7 +1,6 @@ from pydantic import BaseModel, Field from typing import Optional, List, Dict, Any - # ============================================================ # AUTH / USERS # ============================================================ diff --git a/docker-compose.yml b/docker-compose.yml index c443d22..8e23f66 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,28 +1,33 @@ -version: '3.8' - services: backend: - build: ./backend + build: + context: ./backend + network: host container_name: gym-bro-backend - dns: - - 8.8.8.8 - - 1.1.1.1 environment: - GYM_JWT_SECRET=${JWT_SECRET:-super-secret-key-change-in-prod} - GYM_DB_PATH=/data/gym.db volumes: - - ./data:/data # Монтируем локальную папку ./data в /data контейнера + - ./data:/data restart: unless-stopped networks: - gym-net + healthcheck: + # Используем python вместо curl + test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 5s + timeout: 3s + retries: 5 + start_period: 10s # Даём время серверу подняться перед первой проверкой frontend: build: ./frontend container_name: gym-bro-frontend ports: - - "80:80" # Или другой порт, если 80 занят + - "80:80" depends_on: - - backend + backend: + condition: service_healthy restart: unless-stopped networks: - gym-net diff --git a/frontend/js/api.js b/frontend/js/api.js index 2376aaa..08aaffa 100644 --- a/frontend/js/api.js +++ b/frontend/js/api.js @@ -1,48 +1,69 @@ // frontend/js/api.js -import { apiFetch } from "./auth.js"; -import { API_BASE } from "./config.js"; // <-- Добавили импорт -// УДАЛИТЬ эти строки из начала api.js: -// export const API_BASE = ... +import { apiFetch } from "./auth.js"; + +async function jsonOrThrow(res, fallbackMessage) { + if (!res.ok) { + let detail = fallbackMessage; + + try { + const err = await res.json(); + + if (typeof err.detail === "string") { + detail = err.detail; + } else if (Array.isArray(err.detail)) { + detail = err.detail + .map((d) => `${d.loc?.join(".") || ""}: ${d.msg || ""}`.trim()) + .join("; "); + } else { + detail = JSON.stringify(err.detail || err); + } + } catch { + // ignore parse error + } + + throw new Error(detail); + } + + return await res.json(); +} + +export async function fetchBootstrapData() { + const res = await apiFetch("/bootstrap/"); + return jsonOrThrow(res, "Failed to fetch bootstrap data"); +} export async function fetchWorkoutTypes() { - const res = await apiFetch("/workout-types/"); - if (!res.ok) throw new Error('Failed to fetch workout types'); - return await res.json(); + const res = await apiFetch("/workout-types/"); + return jsonOrThrow(res, "Failed to fetch workout types"); } export async function fetchMetricTypes() { - const res = await fetch(`${API_BASE}/metric-types/`); - if (!res.ok) throw new Error('Failed to fetch metric types'); - return await res.json(); + const res = await apiFetch("/metric-types/"); + return jsonOrThrow(res, "Failed to fetch metric types"); } export async function fetchClients() { - const res = await fetch(`${API_BASE}/clients/`); - if (!res.ok) throw new Error('Failed to fetch clients'); - return await res.json(); + const res = await apiFetch("/clients/"); + return jsonOrThrow(res, "Failed to fetch clients"); } export async function fetchExerciseHistory(exerciseName, clientId = null) { - let url = `${API_BASE}/exercises/history/${encodeURIComponent(exerciseName)}?limit=10`; - if (clientId) url += `&client_id=${clientId}`; + let path = `/exercises/history/${encodeURIComponent(exerciseName)}?limit=10`; - const res = await fetch(url); - if (!res.ok) throw new Error('Failed to fetch history'); - return await res.json(); + if (clientId) { + path += `&client_id=${clientId}`; + } + + const res = await apiFetch(path); + return jsonOrThrow(res, "Failed to fetch history"); } export async function syncData(payload) { - const res = await fetch(`${API_BASE}/sync/`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(payload) - }); + const res = await apiFetch("/sync/", { + method: "POST", + body: JSON.stringify(payload), + }); - if (!res.ok) { - const err = await res.json(); - console.error('❌ Sync API Error Detail:', err); // <-- Покажет, какое именно поле не прошло валидацию - throw new Error(err.detail ? JSON.stringify(err.detail) : 'Sync failed'); - } - return await res.json(); + return jsonOrThrow(res, "Sync failed"); } diff --git a/frontend/js/app.js b/frontend/js/app.js index 1cc0241..b016787 100644 --- a/frontend/js/app.js +++ b/frontend/js/app.js @@ -1,65 +1,239 @@ -import { loadState, saveState, state, updateSyncStatus } from './state.js'; -import { renderMainScreen } from './render/main-screen.js'; -import { sync, initAppData } from './sync.js'; +import { + loadState, + saveState, + state, + setActiveUser, + getActiveUser, + resetState, + updateSyncStatus, +} from "./state.js"; + +import { renderMainScreen } from "./render/main-screen.js"; +import { sync, initAppData } from "./sync.js"; + +import { + getToken, + getStoredUser, + clearSession, + login, + register, + me, +} from "./auth.js"; // Подключаем logic-модули -import './logic/workout.js'; -import './logic/exercise.js'; -import './logic/set.js'; -import './logic/cardio.js'; -import './logic/metrics.js'; -import './logic/settings.js'; +import "./logic/workout.js"; +import "./logic/exercise.js"; +import "./logic/set.js"; +import "./logic/cardio.js"; +import "./logic/metrics.js"; +import "./logic/settings.js"; // Подключаем модалки -import './modals/modal-base.js'; -import './modals/exercise-modal.js'; -import './modals/set-modal.js'; -import './modals/cardio-modal.js'; -import './modals/metrics-modal.js'; -import './modals/client-select-modal.js'; -import './modals/edit-exercise-modal.js'; -import './modals/edit-workout-date-modal.js'; +import "./modals/modal-base.js"; +import "./modals/exercise-modal.js"; +import "./modals/set-modal.js"; +import "./modals/cardio-modal.js"; +import "./modals/metrics-modal.js"; +import "./modals/edit-exercise-modal.js"; +import "./modals/edit-workout-date-modal.js"; +import "./modals/client-select-modal.js"; function renderHeader() { - const modeLabel = state.mode === 'trainer' ? '👨‍🏫 Тренер' : '👤 Личный'; - document.getElementById('app-header').innerHTML = ` -
-

Gym Bro 😈 (${modeLabel})

-
● Локально
-
-
- - - - -
- `; + const user = getActiveUser(); + const modeLabel = state.mode === "trainer" ? "👨‍🏫 Тренер" : "👤 Личный"; + + document.getElementById("app-header").innerHTML = ` +
+

+ Gym Bro 😈 + + (${modeLabel}) + +

+
● Локально
+ ${user ? `
${user.display_name || user.username}
` : ""} +
+
+ + + + + +
+ `; } -async function init() { - loadState(); - renderHeader(); - renderMainScreen(); - updateSyncStatus(); +function renderAuthScreen(message = "") { + const header = document.getElementById("app-header"); + const app = document.getElementById("app"); - // Загружаем справочники с бэкенда в фоне - await initAppData(); + header.innerHTML = ` +
+

Gym Bro 😈

+
Требуется вход
+
+ `; + + app.innerHTML = ` +
+

Вход / Регистрация

+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
${message}
+
+ `; } +function showAuthError(text) { + const el = document.getElementById("auth-error"); + if (el) el.textContent = text || ""; +} + +async function enterApp(user) { + setActiveUser(user); + loadState(); + + // Если пользователь тренер и это его первое состояние — включаем тренерский режим + if ( + user.role === "trainer" && + state.workouts.length === 0 && + state.clients.length === 0 && + state.exerciseRef.length === 0 + ) { + state.mode = "trainer"; + saveState(); + } + + renderHeader(); + renderMainScreen(); + updateSyncStatus(); + + // ВАЖНО: Загружаем справочники ТОЛЬКО после успешного входа + await initAppData(); +} + +async function bootstrap() { + const token = getToken(); + + // 1. Если токена нет — сразу на экран входа + if (!token) { + renderAuthScreen(); + return; + } + + let user = getStoredUser(); + + // 2. Проверяем валидность токена на сервере + try { + const freshUser = await me(); + if (freshUser) { + user = freshUser; + } else { + throw new Error("Invalid user response"); + } + } catch (e) { + console.warn("Token invalid or expired", e); + clearSession(); + renderAuthScreen("Сессия истекла. Войдите заново."); + return; + } + + // 3. Если всё ок — входим в приложение + await enterApp(user); +} + +window.AuthUI = { + async doLogin() { + const username = document.getElementById("auth-username")?.value.trim(); + const password = document.getElementById("auth-password")?.value; + + if (!username || !password) { + showAuthError("Введите логин и пароль"); + return; + } + + try { + showAuthError(""); + const user = await login(username, password); + await enterApp(user); + } catch (e) { + showAuthError(e.message); + } + }, + + async doRegister() { + const username = document.getElementById("auth-username")?.value.trim(); + const password = document.getElementById("auth-password")?.value; + const role = document.getElementById("auth-role")?.value || "personal"; + + if (!username || !password) { + showAuthError("Введите логин и пароль"); + return; + } + + try { + showAuthError(""); + const user = await register(username, password, role); + await enterApp(user); + } catch (e) { + showAuthError(e.message); + } + }, + + logout() { + clearSession(); + resetState(); + renderAuthScreen("Вы вышли из системы"); + }, +}; + +window.addEventListener("auth:unauthorized", () => { + clearSession(); + resetState(); + renderAuthScreen("Сессия истекла. Войдите заново."); +}); + window.App = { - getWorkout: (id) => state.workouts.find(w => w.id === id), - saveAndRender: () => { saveState(); }, - toggleMode: () => { - state.mode = state.mode === 'personal' ? 'trainer' : 'personal'; - saveState(); - renderHeader(); - renderMainScreen(); + getWorkout: (id) => state.workouts.find((w) => w.id === id), + saveAndRender: () => { + saveState(); + }, + toggleMode: () => { + state.mode = state.mode === "personal" ? "trainer" : "personal"; + saveState(); + renderHeader(); + renderMainScreen(); + }, + showDashboard: () => { + import('./render/dashboard-screen.js').then(mod => mod.renderDashboard()); }, - backToMain: () => renderMainScreen(), + backToMain: () => renderMainScreen(), }; + window.AppSync = { sync }; - -// Делаем renderMainScreen доступным глобально window.renderMainScreen = renderMainScreen; +window.state = state; -document.addEventListener('DOMContentLoaded', init); +document.addEventListener("DOMContentLoaded", bootstrap); diff --git a/frontend/js/auth.js b/frontend/js/auth.js index 58b6e7d..91385f4 100644 --- a/frontend/js/auth.js +++ b/frontend/js/auth.js @@ -5,16 +5,10 @@ import { API_BASE } from "./config.js"; const TOKEN_KEY = "gym_auth_token"; const USER_KEY = "gym_auth_user"; -/** - * Получить сохранённый токен - */ export function getToken() { return localStorage.getItem(TOKEN_KEY); } -/** - * Получить сохранённого пользователя - */ export function getStoredUser() { try { const raw = localStorage.getItem(USER_KEY); @@ -24,17 +18,19 @@ export function getStoredUser() { } } -/** - * Сохранить сессию (токен + данные пользователя) - */ export function setSession(token, user) { + // Гарантируем, что данные записаны синхронно localStorage.setItem(TOKEN_KEY, token); localStorage.setItem(USER_KEY, JSON.stringify(user)); + + // Принудительно обновляем UI статус, если элемент существует + const statusEl = document.getElementById('sync-status'); + if (statusEl) { + statusEl.textContent = '● Авторизовано'; + statusEl.className = 'sync-status synced'; + } } -/** - * Очистить сессию (Logout) - */ export function clearSession() { localStorage.removeItem(TOKEN_KEY); localStorage.removeItem(USER_KEY); @@ -42,19 +38,21 @@ export function clearSession() { /** * Защищённый Fetch wrapper. - * Автоматически добавляет Authorization header. - * При получении 401 очищает сессию и вызывает событие 'auth:unauthorized'. */ export async function apiFetch(path, options = {}) { const token = getToken(); - const headers = new Headers(options.headers || {}); - - if (token) { - headers.set("Authorization", `Bearer ${token}`); + // Критическая проверка: если токена нет, не идем на сервер + if (!token) { + console.warn(`⚠️ [AUTH] No token found for request: ${path}. Skipping.`); + throw new Error("Not authenticated"); } - // Если есть тело запроса и Content-Type не задан явно — ставим JSON + const headers = new Headers(options.headers || {}); + + // Всегда добавляем Authorization, перезаписывая любые существующие + headers.set("Authorization", `Bearer ${token}`); + if (options.body && !headers.has("Content-Type")) { headers.set("Content-Type", "application/json"); } @@ -66,23 +64,22 @@ export async function apiFetch(path, options = {}) { headers, }); } catch (e) { - // Сеть недоступна или другая ошибка транспорта - // Не логаутим автоматически, просто пробрасываем ошибку + console.error(`❌ [NETWORK] Failed to reach ${path}:`, e); throw e; } - // Если сервер ответил 401 Unauthorized — токен протух или неверный + // Если 401 — очищаем сессию и кидаем событие if (res.status === 401) { + console.error(`❌ [AUTH] Received 401 Unauthorized for ${path}. Clearing session.`); clearSession(); window.dispatchEvent(new Event("auth:unauthorized")); + // Пробрасываем ошибку, чтобы вызывающий код знал, что произошло + throw new Error("Unauthorized"); } return res; } -/** - * Логин пользователя - */ export async function login(username, password) { const res = await fetch(`${API_BASE}/auth/login`, { method: "POST", @@ -100,9 +97,6 @@ export async function login(username, password) { return data.user; } -/** - * Регистрация нового пользователя - */ export async function register(username, password, role = "personal") { const res = await fetch(`${API_BASE}/auth/register`, { method: "POST", @@ -120,18 +114,13 @@ export async function register(username, password, role = "personal") { return data.user; } -/** - * Проверка токена / получение текущего пользователя - */ export async function me() { + // Используем apiFetch, чтобы автоматически добавить токен const res = await apiFetch("/auth/me"); if (!res.ok) return null; return await res.json(); } -/** - * Хелпер для парсинга ошибок FastAPI/Pydantic - */ async function parseError(res, fallbackMessage) { try { const err = await res.json(); diff --git a/frontend/js/logic/metrics.js b/frontend/js/logic/metrics.js index 2edaf47..5f476c2 100644 --- a/frontend/js/logic/metrics.js +++ b/frontend/js/logic/metrics.js @@ -1,51 +1,90 @@ -import { state, saveState, genId } from '../state.js'; +// frontend/js/logic/metrics.js + +import { state, saveState, genId, generateUUID } from '../state.js'; import { renderMainScreen } from '../render/main-screen.js'; import { showBodyMetricsDialog } from '../modals/metrics-modal.js'; +/** + * Показывает модалку добавления/редактирования личных замеров + */ export function showBodyMetrics() { - // В личном режиме — замеры без клиента + // Фильтруем только личные замеры (без client_id) const personalMetrics = state.bodyMetrics.filter(m => !m.client_id); - showBodyMetricsDialog(personalMetrics, (newMetric) => { - if (!newMetric) return; - newMetric.id = genId(); - newMetric.client_id = null; // личный замер - state.bodyMetrics.unshift(newMetric); + showBodyMetricsDialog(personalMetrics, (newMetricData, isEdit) => { + if (!newMetricData) return; + + if (isEdit && newMetricData.id) { + // Редактирование существующего + const existing = state.bodyMetrics.find(m => m.id === newMetricData.id); + if (existing) { + Object.assign(existing, newMetricData); + existing.synced = false; // Помечаем как измененный + } + } else { + // Создание нового + const metric = { + id: generateUUID(), // Используем UUID сразу для стабильности + sync_id: generateUUID(), + date: newMetricData.date, + notes: newMetricData.notes || "", + values: newMetricData.values || [], + client_id: null, // Личный замер + synced: false, // Не синхронизирован + }; + + state.bodyMetrics.unshift(metric); + } + + // Сортировка по дате (новые сверху) state.bodyMetrics.sort((a, b) => new Date(b.date) - new Date(a.date)); + saveState(); renderMainScreen(); - alert('Замеры сохранены!'); + alert('Замер сохранен локально. Нажмите 🔄 для синхронизации.'); }); } +/** + * Редактирование конкретного замера + */ export function editBodyMetric(metricId) { const metric = state.bodyMetrics.find(m => m.id === metricId); if (!metric) return; - showBodyMetricsDialog(state.bodyMetrics, (updatedData) => { + + // Передаем данные в диалог. Диалог должен вернуть объект с теми же ID/sync_id, но новыми значениями + showBodyMetricsDialog([metric], (updatedData, isEdit) => { if (!updatedData) return; - Object.assign(metric, updatedData); + + // Обновляем поля + metric.date = updatedData.date; + metric.notes = updatedData.notes; + metric.values = updatedData.values; + metric.synced = false; // Помечаем как измененный + state.bodyMetrics.sort((a, b) => new Date(b.date) - new Date(a.date)); saveState(); - // Обновляем список в настройках, если он открыт - const list = document.getElementById('body-metrics-list'); - if (list && typeof window.SettingsLogic !== 'undefined') { - window.SettingsLogic._renderPersonalMetricsList(); - } else { - renderMainScreen(); - } + renderMainScreen(); + alert('Изменения сохранены. Нажмите 🔄 для синхронизации.'); }, metric); } +/** + * Удаление замера + */ export function deleteMetric(id) { - if (!confirm('Удалить замер?')) return; + if (!confirm('Удалить этот замер?')) return; + + // Для простоты MVP удаляем локально. + // На сервере удаление через API /body-metrics/{id} можно добавить позже. + // Сейчас просто убираем из стейта. state.bodyMetrics = state.bodyMetrics.filter(m => m.id !== id); saveState(); - const list = document.getElementById('body-metrics-list'); - if (list && typeof window.SettingsLogic !== 'undefined') { - window.SettingsLogic._renderPersonalMetricsList(); - } else { - renderMainScreen(); - } + renderMainScreen(); } -window.ML = { showBodyMetrics, editBodyMetric, deleteMetric }; +window.ML = { + showBodyMetrics, + editBodyMetric, + deleteMetric +}; diff --git a/frontend/js/logic/settings.js b/frontend/js/logic/settings.js index 96efaa3..0b9d409 100644 --- a/frontend/js/logic/settings.js +++ b/frontend/js/logic/settings.js @@ -1,36 +1,76 @@ +// frontend/js/logic/settings.js + import { state, saveState, CLIENT_COLORS, DEFAULT_COLOR, genId, generateUUID } from '../state.js'; import { showEditExerciseDialog } from '../modals/edit-exercise-modal.js'; import { showBodyMetricsDialog } from '../modals/metrics-modal.js'; -import { showModal } from '../modals/modal-base.js'; +import { apiFetch } from '../auth.js'; // Используем защищенный fetch +import { getToken } from '../auth.js'; +import { fetchMetricTypes, fetchWorkoutTypes } from '../api.js'; + +// ============================================================ +// ГЛАВНЫЙ ЭКРАН НАСТРОЕК +// ============================================================ export function showSettings() { const app = document.getElementById('app'); + if (!app) return; + app.innerHTML = ''; const screen = document.createElement('div'); screen.className = 'settings-screen'; + + // Генерируем опции типов тренировок из state.workoutTypes + const workoutTypeOptions = state.workoutTypes.length > 0 + ? state.workoutTypes.map(wt => ``).join('') + : ''; + screen.innerHTML = `

⚙️ Настройки

+ +
+
+ Справочники загружены из базы данных. + +
+
+ +
-

👥 Клиенты

-

Управление клиентами и их замерами. Цвет клиента используется для подсветки тренировок.

+

📏 Типы замеров (${state.metricTypes.length})

+

+ Какие метрики вы хотите отслеживать? Они появятся в форме добавления замера. +

+ +
+
+ + +
+

👥 Клиенты (${state.clients.length})

+

+ Список подопечных. Цвет используется для подсветки их тренировок на главном экране. +

+
-

📋 Справочник упражнений

-

Управляйте списком упражнений и привязывайте их к типам тренировок.

+

📋 Справочник упражнений (${state.exerciseRef.length})

+

+ Ваши любимые упражнения. Привязка к типу тренировки помогает фильтровать список при выборе. +

@@ -38,85 +78,484 @@ export function showSettings() {
+
-

📏 Личные замеры

-

Замеры без привязки к клиенту (для личного режима).

- +

📊 Личные замеры (${state.bodyMetrics.filter(m => !m.client_id).length})

+

+ История ваших собственных измерений тела. +

+
+

🗑 Данные

- +
`; + app.appendChild(screen); + // Вызываем рендеры всех списков + _renderMetricTypesList(); _renderClientsList(); _renderRefExercises(); _renderPersonalMetricsList(); } -export function _renderPersonalMetricsList() { - const list = document.getElementById('body-metrics-list'); - if (!list) return; +export async function refreshDicts() { + const btn = document.querySelector('.btn-secondary[onclick*="refreshDicts"]'); // Ищем кнопку по onclick, если она есть + if (btn) btn.textContent = '⏳ Загрузка...'; - const personalMetrics = state.bodyMetrics.filter(m => !m.client_id); + try { + console.log("Проверка токена...", getToken()); - if (personalMetrics.length === 0) { - list.innerHTML = '

Нет личных замеров

'; + // Если токена нет — сразу выходим и просим логин + if (!getToken()) { + alert("❌ Нет активной сессии. Пожалуйста, войдите снова."); + window.AuthUI.logout(); // Принудительно сбрасываем состояние + return; + } + + // Загружаем типы замеров + const mtRes = await fetchMetricTypes(); + state.metricTypes = Array.isArray(mtRes) ? mtRes : []; + + // Загружаем типы тренировок + const wtRes = await fetchWorkoutTypes(); + state.workoutTypes = Array.isArray(wtRes) ? wtRes : []; + + saveState(); + + // Перерисовываем текущий экран настроек + showSettings(); + + alert(`✅ Справочники обновлены.\nТипов замеров: ${state.metricTypes.length}\nТипов тренировок: ${state.workoutTypes.length}`); + } catch (e) { + console.error(e); + + // Специальная обработка 401 + if (e.message.includes('401') || e.message.includes('Unauthorized')) { + alert("❌ Сессия истекла или неверна. Войдите заново."); + window.AuthUI.logout(); + } else { + alert("❌ Ошибка обновления справочников: " + e.message); + } + } finally { + if (btn) btn.textContent = '🔄 Обновить'; + } +} + +// ============================================================ +// ЛОГИКА: ТИПЫ ЗАМЕРОВ +// ============================================================ + +export function addClientMetric(clientId) { + const clientMetrics = state.bodyMetrics.filter(m => m.client_id == clientId); + + showBodyMetricsDialog(clientMetrics, (newMetricData, isEdit) => { + if (!newMetricData) return; + + if (isEdit && newMetricData.id) { + const existing = state.bodyMetrics.find(m => m.id === newMetricData.id); + if (existing) { + Object.assign(existing, newMetricData); + existing.synced = false; + } + } else { + const metric = { + id: generateUUID(), + sync_id: generateUUID(), + date: newMetricData.date, + notes: newMetricData.notes || "", + values: newMetricData.values || [], + client_id: parseInt(clientId), // Привязка к клиенту + synced: false, + }; + state.bodyMetrics.unshift(metric); + } + + state.bodyMetrics.sort((a, b) => new Date(b.date) - new Date(a.date)); + saveState(); + + // Перерисовываем список замеров клиента в модалке настроек + showClientMetrics(clientId); + window.renderMainScreen(); + }); +} + +export function showAddMetricTypeModal() { + const html = ` + + `; + window.ModalBase.showModal(html); +} + +export async function submitMetricType() { + const nameInput = document.getElementById('m-mt-name'); + const unitSelect = document.getElementById('m-mt-unit'); + const orderInput = document.getElementById('m-mt-order'); + + const name = nameInput.value.trim(); + const unit = unitSelect.value; + const sort_order = parseInt(orderInput.value) || 99; + + if (!name) { + alert('Введите название типа замера'); return; } - list.innerHTML = personalMetrics.map(m => { - const date = new Date(m.date); - const dateStr = date.toLocaleDateString('ru-RU') + ' ' + date.toLocaleTimeString('ru-RU', {hour:'2-digit', minute:'2-digit'}); - const parts = []; - if (m.weight) parts.push(`⚖️ ${m.weight} кг`); - if (m.chest) parts.push(`📏 ${m.chest} см`); - if (m.waist) parts.push(`📏 ${m.waist} см`); - if (m.hips) parts.push(`📏 ${m.hips} см`); - if (m.arms) parts.push(`💪 ${m.arms} см`); - if (m.legs) parts.push(`🦵 ${m.legs} см`); + try { + const res = await apiFetch('/metric-types/', { + method: 'POST', + body: JSON.stringify({ + sync_id: generateUUID(), + name: name, + unit: unit, + category: 'body', + sort_order: sort_order + }) + }); + + if (!res.ok) { + const errText = await res.text(); + throw new Error(errText || 'Failed to create metric type'); + } + + const created = await res.json(); + + // Обновляем локальный стейт + if (!Array.isArray(state.metricTypes)) state.metricTypes = []; + state.metricTypes.push(created); + state.metricTypes.sort((a,b) => a.sort_order - b.sort_order); + + saveState(); + + window.ModalBase.closeModal(); + _renderMetricTypesList(); // Перерисовываем список + + // Сообщаем об успехе + console.log('✅ Тип замера создан:', created.name); + + } catch (e) { + console.error('❌ Error creating metric type:', e); + alert('Ошибка создания типа: ' + e.message); + } +} + +export async function deleteMetricType(id) { + if(!confirm('Удалить этот тип замера?\nДанные в прошлых замерах останутся, но поле исчезнет из формы.')) return; + + try { + // TODO: Реализовать DELETE endpoint на бэкенде, если нужно удалять глобально + // Пока просто удаляем локально из view-списка, чтобы UI обновился + // Если бэк поддерживает удаление: + // const res = await apiFetch(`/metric-types/${id}`, { method: 'DELETE' }); + // if(res.ok) { ... } + + // Для MVP просто скрываем из локального состояния, пока не будет полного CRUD + state.metricTypes = state.metricTypes.filter(t => t.id != id); + saveState(); + _renderMetricTypesList(); + + } catch (e) { + console.error(e); + alert('Не удалось удалить тип.'); + } +} + +export function _renderMetricTypesList() { + const list = document.getElementById('metric-types-list'); + if (!list) return; + + // Если массив пустой или undefined + if (!Array.isArray(state.metricTypes) || state.metricTypes.length === 0) { + list.innerHTML = ` +
+

Нет активных типов замеров.

+

Нажмите "🔄 Обновить" сверху или добавьте новый тип.

+
+ `; + return; + } + + list.innerHTML = state.metricTypes.map(mt => ` +
+
+ ${mt.name} + (${mt.unit}) • Порядок: ${mt.sort_order} +
+ +
+ `).join(''); +} + +// ============================================================ +// ЛОГИКА: КЛИЕНТЫ +// ============================================================ + +export function showAddClientModal(editingClient = null) { + const isEdit = !!editingClient; + const client = editingClient || { full_name: '', birth_date: '', goal: '', color: DEFAULT_COLOR }; + + // Палитра цветов + const paletteHtml = CLIENT_COLORS.map(color => ` +
+ `).join(''); + + const html = ` + + `; + + window.ModalBase.showModal(html); + window._tempClientColor = client.color || DEFAULT_COLOR; +} + +export function selectClientColor(color) { + window._tempClientColor = color; + // Визуально выделяем выбранный цвет + document.querySelectorAll('#m-client-palette .color-swatch').forEach(el => { + el.classList.toggle('selected', el.dataset.color === color); + }); +} + +export async function submitClient(editingId) { + const nameInput = document.getElementById('m-client-name'); + const dobInput = document.getElementById('m-client-dob'); + const goalInput = document.getElementById('m-client-goal'); + + const name = nameInput.value.trim(); + if (!name) { + alert('Введите ФИО клиента'); + return; + } + + const color = window._tempClientColor || DEFAULT_COLOR; + const birthDate = dobInput.value || null; + const goal = goalInput.value.trim(); + + const payload = { + sync_id: editingId ? undefined : generateUUID(), // При редактировании sync_id не меняем + full_name: name, + birth_date: birthDate, + goal: goal, + notes: "", + color: color, + is_active: 1 + }; + + try { + let res; + if (editingId) { + // PUT /clients/{id} + res = await apiFetch(`/clients/${editingId}`, { + method: 'PUT', + body: JSON.stringify(payload) + }); + } else { + // POST /clients/ + res = await apiFetch('/clients/', { + method: 'POST', + body: JSON.stringify(payload) + }); + } + + if (!res.ok) { + const errText = await res.text(); + throw new Error(errText || 'Failed to save client'); + } + + const savedClient = await res.json(); + + // Обновляем локальный стейт + if (!Array.isArray(state.clients)) state.clients = []; + + if (editingId) { + const idx = state.clients.findIndex(c => c.id == editingId); + if (idx !== -1) { + state.clients[idx] = savedClient; + } + } else { + state.clients.push(savedClient); + } + + // Сортируем по имени + state.clients.sort((a, b) => a.full_name.localeCompare(b.full_name)); + + saveState(); + window.ModalBase.closeModal(); + _renderClientsList(); + + // Если мы в режиме тренера и выбрали этого клиента автоматически (если был пуст) + if (state.mode === 'trainer' && !state.currentClientId && !editingId) { + // Можно автовыбрать первого нового, но лучше оставить выбор пользователю + } + + window.renderMainScreen(); // Обновляем цвета на главном экране + + } catch (e) { + console.error('❌ Error saving client:', e); + alert('Ошибка сохранения клиента: ' + e.message); + } +} + +export async function deleteClient(id) { + if (!confirm('Удалить клиента?\nЕго тренировки останутся, но потеряют привязку и цвет.')) return; + + try { + const res = await apiFetch(`/clients/${id}`, { method: 'DELETE' }); + + if (!res.ok) throw new Error(await res.text()); + + // Удаляем локально + state.clients = state.clients.filter(c => c.id != id); + + // Отвязываем тренировки и замеры локально (на сервере они тоже отвязались через ON DELETE SET NULL) + state.workouts.forEach(w => { + if (w.client_id == id) w.client_id = null; + }); + state.bodyMetrics.forEach(m => { + if (m.client_id == id) m.client_id = null; + }); + + saveState(); + _renderClientsList(); + window.renderMainScreen(); + + } catch (e) { + console.error(e); + alert('Не удалось удалить клиента.'); + } +} + +export function _renderClientsList() { + const list = document.getElementById('clients-list'); + if (!list) return; + + if (!state.clients || state.clients.length === 0) { + list.innerHTML = '

Нет клиентов. Добавьте первого!

'; + return; + } + + list.innerHTML = state.clients.map(c => { + // Статистика + const clientWorkouts = state.workouts.filter(w => w.client_id == c.id); + const clientMetrics = state.bodyMetrics.filter(m => m.client_id == c.id); + return ` -
-
-
${dateStr}
-
${parts.join(' • ') || '—'}
+
+
+
${c.full_name}
+
${c.goal || 'Цель не указана'}
+
+ 🏋️ ${clientWorkouts.length} трен. • 📏 ${clientMetrics.length} замеров +
- - + +
`; }).join(''); } +// ============================================================ +// ЛОГИКА: УПРАЖНЕНИЯ (СПРАВОЧНИК) +// ============================================================ + export function addRefExercise() { const input = document.getElementById('new-ref-exercise'); const typeSelect = document.getElementById('new-ref-type'); const name = input.value.trim(); + if (!name) return; - const normalizedName = name.trim().toLowerCase(); - const exists = state.exerciseRef.find( - e => e.name.trim().toLowerCase() === normalizedName - ); - if (!exists) { - state.exerciseRef.push({ - id: (state.nextId++).toString(), - name: name.trim(), - workoutType: typeSelect.value, - }); + + const normalizedName = name.toLowerCase(); + const exists = state.exerciseRef.find(e => e.name.toLowerCase() === normalizedName); + + if (exists) { + alert('Такого упражнения уже нет в справочнике? Оно есть!'); + return; } + + // Добавляем локально + const newEx = { + id: genId(), + sync_id: generateUUID(), + name: name, + workoutType: typeSelect.value || '', + }; + + state.exerciseRef.push(newEx); saveState(); + input.value = ''; typeSelect.value = ''; + _renderRefExercises(); } export function deleteRefExercise(id) { - if (!confirm('Удалить из справочника? (в тренировках останется)')) return; + if (!confirm('Удалить из справочника? (в тренировках останется как текст)')) return; state.exerciseRef = state.exerciseRef.filter(e => e.id !== id); saveState(); _renderRefExercises(); @@ -127,12 +566,15 @@ export function updateRefExerciseType(id, newType) { if (ex) { ex.workoutType = newType; saveState(); + // Не перерисовываем весь список, чтобы не сбросить фокус, + // но можно обновить badge визуально, если нужно } } export function editRefExercise(id) { const ex = state.exerciseRef.find(e => e.id === id); if (!ex) return; + showEditExerciseDialog(ex, (updatedData) => { if (!updatedData) return; Object.assign(ex, updatedData); @@ -141,28 +583,26 @@ export function editRefExercise(id) { }); } -export function clearAllData() { - if (!confirm('Удалить ВСЕ данные? Это действие необратимо!')) return; - if (!confirm('Точно уверены?')) return; - localStorage.clear(); - location.reload(); -} - export function _renderRefExercises() { const list = document.getElementById('ref-exercises-list'); if (!list) return; + if (state.exerciseRef.length === 0) { list.innerHTML = '

Справочник пуст

'; return; } + + // Сортировка: сначала по типу, потом по алфавиту const sorted = [...state.exerciseRef].sort((a, b) => { - if (a.workoutType !== b.workoutType) return (a.workoutType || '').localeCompare(b.workoutType || ''); + const typeA = a.workoutType || ''; + const typeB = b.workoutType || ''; + if (typeA !== typeB) return typeA.localeCompare(typeB); return a.name.localeCompare(b.name); }); - // Генерируем опции для select динамически из state.workoutTypes - const typeOptions = state.workoutTypes.map(wt => - `` + // Опции для селекта внутри карточки + const typeOptionsHtml = state.workoutTypes.map(wt => + `` ).join(''); list.innerHTML = sorted.map(ex => { @@ -172,6 +612,7 @@ export function _renderRefExercises() { if (e.name.trim().toLowerCase() === ex.name.trim().toLowerCase()) count++; }); }); + return `
@@ -183,7 +624,11 @@ export function _renderRefExercises() { @@ -193,45 +638,52 @@ export function _renderRefExercises() { }).join(''); } -export function _renderMetricTypes() { - const container = document.getElementById('metric-types-list'); - if (!container) return; - if (state.metricTypes.length === 0) { - container.innerHTML = '

Нет типов замеров

'; - return; - } - container.innerHTML = state.metricTypes.map(mt => ` -
-
- ${mt.name} - ${mt.unit} -
-
- `).join(''); -} +// ============================================================ +// ЛОГИКА: ЛИЧНЫЕ ЗАМЕРЫ +// ============================================================ -export function _renderBodyMetricsList() { +export function _renderPersonalMetricsList() { const list = document.getElementById('body-metrics-list'); if (!list) return; - if (state.bodyMetrics.length === 0) { - list.innerHTML = '

Нет замеров

'; + + // Фильтруем только личные (без client_id) + const personalMetrics = state.bodyMetrics.filter(m => !m.client_id); + + if (personalMetrics.length === 0) { + list.innerHTML = '

Нет личных замеров

'; return; } - list.innerHTML = state.bodyMetrics.map(m => { - const date = new Date(m.date); - const dateStr = date.toLocaleDateString('ru-RU') + ' ' + date.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' }); - const parts = []; - if (m.weight) parts.push(`⚖️ ${m.weight} кг`); - if (m.chest) parts.push(`📏 ${m.chest} см`); - if (m.waist) parts.push(`📏 ${m.waist} см`); - if (m.hips) parts.push(`📏 ${m.hips} см`); - if (m.arms) parts.push(`💪 ${m.arms} см`); - if (m.legs) parts.push(`🦵 ${m.legs} см`); + + // Сортируем по дате (новые сверху) + const sorted = [...personalMetrics].sort((a, b) => new Date(b.date) - new Date(a.date)); + + list.innerHTML = sorted.map(m => { + const dateStr = new Date(m.date).toLocaleDateString('ru-RU') + ' ' + + new Date(m.date).toLocaleTimeString('ru-RU', {hour:'2-digit', minute:'2-digit'}); + + // Форматируем значения динамически + let valuesStr = '—'; + if (Array.isArray(m.values) && m.values.length > 0) { + const parts = m.values.map(v => { + const mt = state.metricTypes.find(t => t.id == v.metric_type_id); + const name = mt ? mt.name : '?'; + const unit = mt ? mt.unit : ''; + return `${name}: ${v.value}${unit}`; + }); + valuesStr = parts.join(' • '); + } else { + // Legacy support + const legacyParts = []; + if (m.weight) legacyParts.push(`Вес: ${m.weight} кг`); + if (m.chest) legacyParts.push(`Грудь: ${m.chest} см`); + if (legacyParts.length) valuesStr = legacyParts.join(' • '); + } + return `
${dateStr}
-
${parts.join(' • ') || '—'}
+
${valuesStr}
@@ -242,257 +694,46 @@ export function _renderBodyMetricsList() { }).join(''); } -export function showAddClientModal(editingClient = null) { - const isEdit = !!editingClient; - const client = editingClient || { full_name: '', birth_date: '', goal: '', color: DEFAULT_COLOR }; +// ============================================================ +// ПРОЧИЕ +// ============================================================ - const paletteHtml = CLIENT_COLORS.map(color => ` -
- `).join(''); +export function clearAllData() { + if (!confirm('Удалить ВСЕ локальные данные? Это действие необратимо!\n(Данные на сервере останутся)')) return; + if (!confirm('Точно уверены?')) return; - const html = ` - - `; - showModal(html); - window._tempClientColor = client.color; + localStorage.clear(); + location.reload(); } -export function selectClientColor(color) { - window._tempClientColor = color; - document.querySelectorAll('#m-client-palette .color-swatch').forEach(el => { - el.classList.toggle('selected', el.style.background === color || - rgbToHex(el.style.backgroundColor) === color.toLowerCase()); - }); -} - -function rgbToHex(rgb) { - if (rgb.startsWith('#')) return rgb.toLowerCase(); - const match = rgb.match(/\d+/g); - if (!match) return rgb; - return '#' + match.slice(0, 3).map(x => parseInt(x).toString(16).padStart(2, '0')).join(''); -} - -export function submitClient(editingId) { - const name = document.getElementById('m-client-name').value.trim(); - if (!name) { alert('Введите ФИО'); return; } - - const color = window._tempClientColor || DEFAULT_COLOR; - - if (editingId) { - // Редактирование - const client = state.clients.find(c => c.id == editingId); - if (client) { - client.full_name = name; - client.birth_date = document.getElementById('m-client-dob').value || null; - client.goal = document.getElementById('m-client-goal').value.trim(); - client.color = color; - } - } else { - // Создание - const newClient = { - id: genId(), - sync_id: generateUUID(), - full_name: name, - birth_date: document.getElementById('m-client-dob').value || null, - goal: document.getElementById('m-client-goal').value.trim(), - color: color, - is_active: 1, - }; - state.clients.push(newClient); - } - - saveState(); - window.ModalBase.closeModal(); - _renderClientsList(); - window.renderMainScreen(); // Обновляем цвета тренировок -} - -export function deleteClient(id) { - if (!confirm('Удалить клиента? Тренировки останутся, но без привязки.')) return; - state.clients = state.clients.filter(c => c.id != id); - // Отвязываем тренировки - state.workouts.forEach(w => { - if (w.client_id == id) w.client_id = null; - }); - // Отвязываем замеры - state.bodyMetrics.forEach(m => { - if (m.client_id == id) m.client_id = null; - }); - saveState(); - _renderClientsList(); - window.renderMainScreen(); -} - -export function _renderClientsList() { - const list = document.getElementById('clients-list'); - if (!list) return; - - if (state.clients.length === 0) { - list.innerHTML = '

Нет клиентов. Добавьте первого!

'; - return; - } - - list.innerHTML = state.clients.map(c => { - // Считаем замеры этого клиента - const clientMetrics = state.bodyMetrics.filter(m => m.client_id == c.id); - const lastMetric = clientMetrics[0]; // уже отсортированы по дате - - let metricsPreview = 'Нет замеров'; - if (lastMetric) { - const parts = []; - if (lastMetric.weight) parts.push(`⚖️ ${lastMetric.weight} кг`); - if (lastMetric.chest) parts.push(`📏 ${lastMetric.chest} см`); - metricsPreview = parts.join(' • ') || 'Замеры без значений'; - } - - // Считаем тренировки - const clientWorkouts = state.workouts.filter(w => w.client_id == c.id); - - return ` -
-
-
${c.full_name}
-
${c.goal || 'Цель не указана'}
-
- 🏋️ ${clientWorkouts.length} трен. • 📏 ${clientMetrics.length} замеров -
- ${lastMetric ? `
Последний: ${metricsPreview}
` : ''} -
-
- - - -
-
- `; - }).join(''); -} - -export function showClientMetrics(clientId) { - const client = state.clients.find(c => c.id == clientId); - if (!client) return; - - const clientMetrics = state.bodyMetrics - .filter(m => m.client_id == clientId) - .sort((a, b) => new Date(b.date) - new Date(a.date)); - - const metricsHtml = clientMetrics.length === 0 - ? '

Нет замеров

' - : clientMetrics.map(m => { - const date = new Date(m.date); - const dateStr = date.toLocaleDateString('ru-RU') + ' ' + date.toLocaleTimeString('ru-RU', {hour:'2-digit', minute:'2-digit'}); - const parts = []; - if (m.weight) parts.push(`⚖️ ${m.weight} кг`); - if (m.chest) parts.push(`📏 ${m.chest} см`); - if (m.waist) parts.push(`📏 ${m.waist} см`); - if (m.hips) parts.push(`📏 ${m.hips} см`); - if (m.arms) parts.push(`💪 ${m.arms} см`); - if (m.legs) parts.push(`🦵 ${m.legs} см`); - return ` -
-
-
${dateStr}
-
${parts.join(' • ') || '—'}
-
-
- - -
-
- `; - }).join(''); - - const html = ` - - `; - showModal(html); -} - -export function addClientMetric(clientId) { - showBodyMetricsDialog( - state.bodyMetrics.filter(m => m.client_id == clientId), - (newMetric) => { - if (!newMetric) return; - newMetric.id = genId(); - newMetric.client_id = parseInt(clientId); - state.bodyMetrics.unshift(newMetric); - state.bodyMetrics.sort((a, b) => new Date(b.date) - new Date(a.date)); - saveState(); - showClientMetrics(clientId); // Перерисовываем модалку - } - ); -} - -export function editClientMetric(metricId, clientId) { - const metric = state.bodyMetrics.find(m => m.id === metricId); - if (!metric) return; - showBodyMetricsDialog( - state.bodyMetrics, - (updatedData) => { - if (!updatedData) return; - Object.assign(metric, updatedData); - state.bodyMetrics.sort((a, b) => new Date(b.date) - new Date(a.date)); - saveState(); - showClientMetrics(clientId); - }, - metric - ); -} - -export function deleteClientMetric(metricId, clientId) { - if (!confirm('Удалить замер?')) return; - state.bodyMetrics = state.bodyMetrics.filter(m => m.id !== metricId); - saveState(); - showClientMetrics(clientId); -} - -// Обновляем экспорт +// Экспорт всего объекта SettingsLogic window.SettingsLogic = { show: showSettings, - addRefExercise, deleteRefExercise, updateRefExerciseType, - editRefExercise, clearAllData, - _renderRefExercises, _renderBodyMetricsList, - // Клиенты: - showAddClientModal, submitClient, deleteClient, _renderClientsList, - selectClientColor, - // Замеры клиента: - showClientMetrics, addClientMetric, editClientMetric, deleteClientMetric, -}; + refreshDicts, // <-- ДОБАВИЛИ В ЭКСПОРТ -// Делаем state доступным для inline onclick -window.state = state; + // Metric Types + showAddMetricTypeModal, + submitMetricType, + deleteMetricType, + _renderMetricTypesList, + + // Clients + showAddClientModal, + selectClientColor, + submitClient, + deleteClient, + _renderClientsList, + + // Exercises Ref + addRefExercise, + deleteRefExercise, + updateRefExerciseType, + editRefExercise, + _renderRefExercises, + + // Personal Metrics + _renderPersonalMetricsList, + + // Danger Zone + clearAllData, +}; diff --git a/frontend/js/modals/metrics-modal.js b/frontend/js/modals/metrics-modal.js index 60f6cda..debb180 100644 --- a/frontend/js/modals/metrics-modal.js +++ b/frontend/js/modals/metrics-modal.js @@ -1,44 +1,143 @@ +// frontend/js/modals/metrics-modal.js + import { showModal, closeModal, stepperHtml } from './modal-base.js'; +import { state } from '../state.js'; import { toDatetimeLocal } from '../utils.js'; let _cb = null; +let _types = []; +let _isEdit = false; -export function showBodyMetricsDialog(metrics, callback, editing = null) { - _cb = callback; - const src = editing || metrics[0] || {}; - const isEdit = !!editing; - const dateVal = src.date ? toDatetimeLocal(src.date) : toDatetimeLocal(new Date().toISOString()); - - showModal(``); +function stepForUnit(unit) { + const u = String(unit || '').toLowerCase(); + if (u.includes('кг') || u.includes('%')) return 0.1; + if (u.includes('см') || u.includes('мм')) return 0.5; + return 1; } -export function submit(isEdit) { - const r = { - date: new Date(document.getElementById('m-md').value).toISOString(), - weight: parseFloat(document.getElementById('m-mw').value)||null, - chest: parseInt(document.getElementById('m-mc').value)||null, - waist: parseInt(document.getElementById('m-mwa').value)||null, - hips: parseInt(document.getElementById('m-mh').value)||null, - arms: parseFloat(document.getElementById('m-ma').value)||null, - legs: parseFloat(document.getElementById('m-ml').value)||null, +export function showBodyMetricsDialog(existingMetrics, callback, editing = null) { + _cb = callback; + _isEdit = !!editing; + + // Берем типы из состояния (загруженные с бэкенда) + _types = [...(state.metricTypes || [])].sort((a, b) => { + const orderDiff = (a.sort_order || 0) - (b.sort_order || 0); + if (orderDiff !== 0) return orderDiff; + return String(a.name || '').localeCompare(String(b.name || '')); + }); + + if (_types.length === 0) { + showModal(` + + `); + return; + } + + const source = editing || (existingMetrics && existingMetrics[0]) || {}; + const dateValue = source.date ? toDatetimeLocal(source.date) : toDatetimeLocal(new Date().toISOString()); + + // Генерируем HTML для каждого типа замера динамически + const fieldsHtml = _types.map(mt => { + const id = `m-metric-${mt.id}`; + const step = stepForUnit(mt.unit); + + // Ищем значение в объекте замера + // Новый формат: values: [{ metric_type_id, value }] + let value = ''; + if (Array.isArray(source.values)) { + const valObj = source.values.find(v => v.metric_type_id == mt.id); + value = valObj ? valObj.value : ''; + } else { + // Legacy fallback (если вдруг остались старые данные) + const legacyMap = { + weight: 'weight', chest: 'chest', waist: 'waist', + hips: 'hips', arms: 'arms', legs: 'legs' + }; + // Пытаемся угадать поле по имени или единице измерения, если нет ID + // Но лучше всего полагаться на новый формат + } + + return ` +
+ + ${stepperHtml(id, value, step, mt.unit || '', 'decimal')} +
+ `; + }).join(''); + + showModal(` + + `); +} + +export function submit() { + const dateInput = document.getElementById('m-metric-date'); + const notesInput = document.getElementById('m-metric-notes'); + + if (!dateInput || !dateInput.value) { + alert('Укажите дату'); + return; + } + + // Собираем значения только тех полей, которые были заполнены + const values = _types.map(mt => { + const input = document.getElementById(`m-metric-${mt.id}`); + if (!input) return null; + + const rawVal = parseFloat(input.value); + if (isNaN(rawVal)) return null; + + return { + metric_type_id: mt.id, + value: rawVal + }; + }).filter(Boolean); + + if (values.length === 0) { + alert('Заполните хотя бы одно поле'); + return; + } + + const result = { + date: new Date(dateInput.value).toISOString(), + notes: notesInput.value.trim(), + values: values // Отправляем массив пар {type_id, value} }; - if (!Object.values(r).some((v,i) => i>0 && v!==null)) { alert('Заполните поле'); return; } - closeModal(); _cb?.(r, isEdit); + + closeModal(); + if (_cb) _cb(result, _isEdit); } window.MetricsModal = { submit }; diff --git a/frontend/js/render/dashboard-screen.js b/frontend/js/render/dashboard-screen.js new file mode 100644 index 0000000..0e873d7 --- /dev/null +++ b/frontend/js/render/dashboard-screen.js @@ -0,0 +1,96 @@ +// frontend/js/render/dashboard-screen.js + +import { state } from '../state.js'; +import { drawExerciseProgress, drawBodyMetricsGraph } from './dashboard.js'; + +export function renderDashboard() { + const app = document.getElementById('app'); + if (!app) return; + + app.innerHTML = ` +
+

📊 Статистика

+ +
+ + +
+

💪 Прогресс упражнения

+
+ + +
+ +

Показаны макс. вес и повторения за последние 10 тренировок.

+
+ + +
+

⚖️ Динамика тела

+
+
+ + +
+
+ + +
+
+ +
+ `; + + window.DashboardLogic = { + updateExerciseChart: () => { + const select = document.getElementById('dash-ex-select'); + const canvas = document.getElementById('chart-exercise'); + if (select.value) { + drawExerciseProgress(canvas, select.value); + } else { + const ctx = canvas.getContext('2d'); + ctx.clearRect(0,0,canvas.width,canvas.height); + ctx.fillStyle='#666'; + ctx.textAlign='center'; + ctx.fillText('Выберите упражнение выше', canvas.width/2, canvas.height/2); + } + }, + updateBodyChart: () => { + const clientSel = document.getElementById('dash-client-select'); + const metricSel = document.getElementById('dash-metric-select'); + const canvas = document.getElementById('chart-body'); + + const clientId = clientSel.value ? parseInt(clientSel.value) : null; + const metricId = metricSel.value ? parseInt(metricSel.value) : null; + + if (metricId) { + drawBodyMetricsGraph(canvas, clientId, metricId); + } + } + }; + + // Первичная отрисовка (пустые состояния) + DashboardLogic.updateExerciseChart(); + if(state.metricTypes.length > 0) { + document.getElementById('dash-metric-select').value = state.metricTypes[0].id; + DashboardLogic.updateBodyChart(); + } +} + +function getUniqueExercises() { + const set = new Set(); + state.workouts.forEach(w => { + w.exercises.forEach(ex => { + set.add(ex.name); + }); + }); + return Array.from(set).sort(); +} diff --git a/frontend/js/render/dashboard.js b/frontend/js/render/dashboard.js new file mode 100644 index 0000000..53ce54e --- /dev/null +++ b/frontend/js/render/dashboard.js @@ -0,0 +1,381 @@ +// frontend/js/render/dashboard.js + +import { state } from '../state.js'; +import { formatDate } from '../utils.js'; + +/** + * Рисует линейный график прогресса упражнения + * @param {HTMLCanvasElement} canvas + * @param {string} exerciseName + */ +export function drawExerciseProgress(canvas, exerciseName) { + const ctx = canvas.getContext('2d'); + const width = canvas.width; + const height = canvas.height; + + ctx.clearRect(0, 0, width, height); + + const history = getCumulativeExerciseHistory(exerciseName); + + if (history.length < 2) { + drawEmptyState(ctx, width, height, "Недостаточно данных\nНужно минимум 2 тренировки"); + return; + } + + // Находим максимальный ИТОГОВЫЙ объем для масштабирования оси Y + const maxVolume = Math.max(...history.map(h => h.totalVolume)); + + const padding = { top: 20, right: 20, bottom: 30, left: 40 }; + const chartW = width - padding.left - padding.right; + const chartH = height - padding.top - padding.bottom; + + // Рисуем сетку (используем maxVolume для оси Y) + drawGridAndAxes(ctx, padding, chartW, chartH, maxVolume, 'Дата', 'Общий вес (кг)'); + + // Рисуем новый график со стеком + drawCumulativeVolumeChart(ctx, history, padding, chartW, chartH, maxVolume); + + // Легенда (обновленная) + drawLegend(ctx, width, [ + { color: '#bb86fc', label: 'Итоговый объем' }, + { color: 'rgba(187, 134, 252, 0.4)', label: 'Накопление по подходам' } + ]); +} + +/** + * Рисует график динамики телесных замеров + * @param {HTMLCanvasElement} canvas + * @param {number|null} clientId - null для личных замеров + * @param {number} metricTypeId - ID типа замера (например, вес) + */ +export function drawBodyMetricsGraph(canvas, clientId, metricTypeId) { + const ctx = canvas.getContext('2d'); + const width = canvas.width; + const height = canvas.height; + + ctx.clearRect(0, 0, width, height); + + // Фильтруем замеры + const metrics = state.bodyMetrics + .filter(m => m.client_id == clientId) + .sort((a, b) => new Date(a.date) - new Date(b.date)); + + // Извлекаем значения конкретного типа + const dataPoints = []; + metrics.forEach(m => { + const valObj = m.values?.find(v => v.metric_type_id == metricTypeId); + if (valObj && valObj.value !== undefined && valObj.value !== null) { + dataPoints.push({ date: new Date(m.date), value: parseFloat(valObj.value) }); + } + }); + + if (dataPoints.length < 2) { + drawEmptyState(ctx, width, height, "Недостаточно данных\nНужно минимум 2 замера"); + return; + } + + const minVal = Math.min(...dataPoints.map(p => p.value)); + const maxVal = Math.max(...dataPoints.map(p => p.value)); + const range = maxVal - minVal || 1; // Защита от деления на ноль + + const padding = { top: 20, right: 20, bottom: 30, left: 40 }; + const chartW = width - padding.left - padding.right; + const chartH = height - padding.top - padding.bottom; + + // Простая ось Y (значения) + ctx.strokeStyle = '#333'; + ctx.lineWidth = 1; + ctx.beginPath(); + ctx.moveTo(padding.left, padding.top); + ctx.lineTo(padding.left, height - padding.bottom); + ctx.stroke(); + + // Подписи осей Y + ctx.fillStyle = '#b0b0b0'; + ctx.font = '10px sans-serif'; + ctx.textAlign = 'right'; + for (let i = 0; i <= 4; i++) { + const y = height - padding.bottom - (i / 4) * chartH; + const val = minVal + (range * i / 4); + ctx.fillText(val.toFixed(1), padding.left - 5, y + 3); + + // Горизонтальная линия сетки + ctx.strokeStyle = '#2c2c2c'; + ctx.beginPath(); + ctx.moveTo(padding.left, y); + ctx.lineTo(width - padding.right, y); + ctx.stroke(); + } + + // Рисуем точку начала и конца по X (дата) + const firstDate = dataPoints[0].date.getTime(); + const lastDate = dataPoints[dataPoints.length - 1].date.getTime(); + const timeRange = lastDate - firstDate || 1; + + ctx.strokeStyle = '#bb86fc'; // Цвет линии графика + ctx.lineWidth = 2; + ctx.beginPath(); + + dataPoints.forEach((p, index) => { + const x = padding.left + ((p.date.getTime() - firstDate) / timeRange) * chartW; + const y = height - padding.bottom - ((p.value - minVal) / range) * chartH; + + if (index === 0) ctx.moveTo(x, y); + else ctx.lineTo(x, y); + + // Точки + ctx.fillStyle = '#fff'; + ctx.fillRect(x - 2, y - 2, 4, 4); + }); + ctx.stroke(); + + // Подпись даты слева и справа + ctx.fillStyle = '#b0b0b0'; + ctx.textAlign = 'left'; + ctx.fillText(formatShortDate(dataPoints[0].date.toISOString()), padding.left, height - 10); + ctx.textAlign = 'right'; + ctx.fillText(formatShortDate(dataPoints[dataPoints.length-1].date.toISOString()), width - padding.right, height - 10); +} + +/** + * Собирает историю с накопительным весом по каждому подходу + */ +function getCumulativeExerciseHistory(name) { + const normalized = name.trim().toLowerCase(); + const history = []; + + state.workouts.forEach(w => { + w.exercises.forEach(ex => { + if (ex.name.trim().toLowerCase() === normalized && ex.sets.length > 0) { + let currentCumulativeWeight = 0; + const cumulativePoints = []; + + ex.sets.forEach(s => { + // Учитываем вес подхода (для дроп-сетов можно брать средний или максимальный, здесь берем основной) + const setWeight = s.isDropset && s.subSets + ? Math.max(...s.subSets.map(ss => ss.weight)) + : s.weight; + + // Объем подхода = вес * повторения (или просто вес, если вы считаете тоннаж) + // В вашем примере (15, 30, 45, 60) вы суммируете именно вес подходов. + // Если нужно суммировать тоннаж (вес * повторы), замените на: setWeight * s.reps + const volume = setWeight * s.reps; + + currentCumulativeWeight += volume; + cumulativePoints.push(currentCumulativeWeight); + }); + + history.push({ + date: new Date(w.startTime), + cumulativePoints: cumulativePoints, // [15, 30, 45, 60] + totalVolume: currentCumulativeWeight // 60 + }); + } + }); + }); + + history.sort((a, b) => a.date - b.date); + return history.slice(-10); // Последние 10 тренировок +} + +// --- Вспомогательные функции --- + +function getExerciseHistoryData(name) { + const normalized = name.trim().toLowerCase(); + const history = []; + + // Собираем из всех тренировок текущего пользователя (или клиента, если режим тренера реализован глобально) + // Здесь упрощение: берем все тренировки из state.workouts + state.workouts.forEach(w => { + w.exercises.forEach(ex => { + if (ex.name.trim().toLowerCase() === normalized && ex.sets.length > 0) { + history.push({ + date: new Date(w.startTime), + sets: ex.sets + }); + } + }); + }); + + // Сортируем по дате + history.sort((a, b) => a.date - b.date); + return history.slice(-10); // Берем последние 10 тренировок для читаемости +} + +function getMaxWeightInSet(historyItem) { + let max = 0; + historyItem.sets.forEach(s => { + if (s.isDropset && s.subSets) { + s.subSets.forEach(ss => { if (ss.weight > max) max = ss.weight; }); + } else if (s.weight > max) { + max = s.weight; + } + }); + return max; +} + +function getMaxRepsInSet(historyItem) { + let max = 0; + historyItem.sets.forEach(s => { + if (s.isDropset && s.subSets) { + s.subSets.forEach(ss => { if (ss.reps > max) max = ss.reps; }); + } else if (s.reps > max) { + max = s.reps; + } + }); + return max; +} + +function drawGridAndAxes(ctx, pad, cw, ch, maxY, maxXAxisLabel, yAxisLabel) { + ctx.strokeStyle = '#333'; + ctx.lineWidth = 1; + + // Ось Y + ctx.beginPath(); + ctx.moveTo(pad.left, pad.top); + ctx.lineTo(pad.left, ch + pad.top); + ctx.stroke(); + + // Ось X + ctx.beginPath(); + ctx.moveTo(pad.left, ch + pad.top); + ctx.lineTo(cw + pad.left, ch + pad.top); + ctx.stroke(); + + // Подписи Y + ctx.fillStyle = '#b0b0b0'; + ctx.font = '10px sans-serif'; + ctx.textAlign = 'right'; + for(let i=0; i<=4; i++) { + const val = (maxY * i / 4).toFixed(0); + const y = ch + pad.top - (ch * i / 4); + ctx.fillText(val, pad.left - 5, y + 3); + + // Сетка + ctx.strokeStyle = '#2c2c2c'; + ctx.beginPath(); + ctx.moveTo(pad.left, y); + ctx.lineTo(cw + pad.left, y); + ctx.stroke(); + } + + // Заголовок оси Y + ctx.save(); + ctx.translate(15, ch/2 + pad.top); + ctx.rotate(-Math.PI/2); + ctx.textAlign = 'center'; + ctx.fillText(yAxisLabel, 0, 0); + ctx.restore(); +} + +function drawLineChart(ctx, data, pad, cw, ch, maxY, getValueFn, color, lineWidth) { + if (!data.length) return; + + ctx.strokeStyle = color; + ctx.lineWidth = lineWidth; + ctx.beginPath(); + + data.forEach((item, index) => { + const val = getValueFn(item); + const x = pad.left + (index / (data.length - 1)) * cw; + const y = pad.top + ch - (val / maxY) * ch; + + if (index === 0) ctx.moveTo(x, y); + else ctx.lineTo(x, y); + + // Точка + ctx.fillStyle = '#fff'; + ctx.fillRect(x-2, y-2, 4, 4); + }); + ctx.stroke(); +} + +/** + * Рисует график прогресса с вертикальным стеком накопительного веса + */ +function drawCumulativeVolumeChart(ctx, data, pad, cw, ch, maxY) { + if (!data.length) return; + + // 1. Сначала рисуем соединительную линию для ОБЩИХ итогов (тренд) + ctx.strokeStyle = '#bb86fc'; // Основной цвет (например, фиолетовый) + ctx.lineWidth = 2; + ctx.beginPath(); + + data.forEach((item, index) => { + const x = pad.left + (index / (data.length - 1 || 1)) * cw; + const y = pad.top + ch - (item.totalVolume / maxY) * ch; + + if (index === 0) ctx.moveTo(x, y); + else ctx.lineTo(x, y); + }); + ctx.stroke(); + + // 2. Рисуем вертикальные стеки точек для каждой даты + data.forEach((item, index) => { + const x = pad.left + (index / (data.length - 1 || 1)) * cw; + + item.cumulativePoints.forEach((cumWeight, pointIndex) => { + const isLast = pointIndex === item.cumulativePoints.length - 1; + const y = pad.top + ch - (cumWeight / maxY) * ch; + + ctx.beginPath(); + + if (isLast) { + // Финальная точка: крупная, непрозрачная, с белой обводкой для контраста + ctx.fillStyle = '#bb86fc'; + ctx.arc(x, y, 5, 0, Math.PI * 2); + ctx.fill(); + + ctx.strokeStyle = '#ffffff'; + ctx.lineWidth = 1.5; + ctx.stroke(); + } else { + // Промежуточные точки: полупрозрачные, поменьше + ctx.fillStyle = 'rgba(187, 134, 252, 0.4)'; // Тот же цвет, но 40% непрозрачности + ctx.arc(x, y, 3, 0, Math.PI * 2); + ctx.fill(); + } + }); + + // Опционально: провести бледную вертикальную линию от 0 до итоговой точки, + // чтобы визуально связать подходы в один "столбик" + if (item.cumulativePoints.length > 1) { + const bottomY = pad.top + ch; // Ось X + const topY = pad.top + ch - (item.totalVolume / maxY) * ch; + + ctx.strokeStyle = 'rgba(187, 134, 252, 0.15)'; + ctx.lineWidth = 1; + ctx.beginPath(); + ctx.moveTo(x, bottomY); + ctx.lineTo(x, topY); + ctx.stroke(); + } + }); +} + +function drawLegend(ctx, width, items) { + ctx.font = '10px sans-serif'; + ctx.textAlign = 'left'; + let xOffset = 10; + items.forEach(item => { + ctx.fillStyle = item.color; + ctx.fillRect(xOffset, 10, 10, 10); + ctx.fillStyle = '#fff'; + ctx.fillText(item.label, xOffset + 15, 19); + xOffset += ctx.measureText(item.label).width + 30; + }); +} + +function drawEmptyState(ctx, w, h, text) { + ctx.fillStyle = '#666'; + ctx.font = '14px sans-serif'; + ctx.textAlign = 'center'; + const lines = text.split('\n'); + lines.forEach((line, i) => { + ctx.fillText(line, w/2, h/2 + (i * 20) - (lines.length*10)/2); + }); +} + +function formatShortDate(isoString) { + return new Date(isoString).toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit' }); +} diff --git a/frontend/js/state.js b/frontend/js/state.js index d868278..378f710 100644 --- a/frontend/js/state.js +++ b/frontend/js/state.js @@ -1,88 +1,167 @@ -const STORAGE_KEY = 'gym_tracker_v6'; +// frontend/js/state.js -// Палитра из 16 контрастных цветов для клиентов -export const CLIENT_COLORS = [ - '#bb86fc', // фиолетовый (дефолтный для личного режима) - '#03dac6', // бирюзовый - '#fbbc04', // жёлтый - '#cf6679', // розовый - '#64b5f6', // голубой - '#81c784', // зелёный - '#ffb74d', // оранжевый - '#ba68c8', // светло-фиолетовый - '#4dd0e1', // циан - '#e57373', // красный - '#aed581', // салатовый - '#ffd54f', // янтарный - '#9575cd', // пурпурный - '#4db6ac', // тиловый - '#f06292', // малиновый - '#7986cb', // индиго +const CURRENT_STORAGE_PREFIX = "gym_tracker_v7_user_"; +const GUEST_STORAGE_KEY = "gym_tracker_v7_guest"; + +const LEGACY_KEYS = [ + "gym_tracker_v6", + "gym_tracker_v5", + "gym_tracker_v4", ]; -export const DEFAULT_COLOR = CLIENT_COLORS[0]; +const MIGRATION_FLAG = "gym_tracker_legacy_migrated_to_user"; -export const state = { +function freshState() { + return { workouts: [], exerciseRef: [], bodyMetrics: [], workoutTypes: [], metricTypes: [], - clients: [], // каждый клиент: {id, sync_id, full_name, birth_date, goal, color} + clients: [], expandedWorkoutId: null, expandedExerciseId: null, nextId: 1, - mode: 'personal', - currentClientId: null, // больше не используется глобально, но оставим для совместимости -}; + mode: "personal", + currentClientId: null, + }; +} + +export const state = freshState(); + +// Внутренняя переменная для хранения текущего пользователя (не сохраняется в localStorage напрямую) +let activeUser = null; + +/** + * Установить текущего пользователя после логина + */ +export function setActiveUser(user) { + activeUser = user; +} + +/** + * Получить данные текущего пользователя + */ +export function getActiveUser() { + return activeUser; +} + +/** + * Сбросить состояние при логауте + */ +export function resetState() { + Object.assign(state, freshState()); + activeUser = null; +} + +function storageKey() { + return activeUser + ? `${CURRENT_STORAGE_PREFIX}${activeUser.id}` + : GUEST_STORAGE_KEY; +} + +export function migrateLegacyStateForUser() { + if (!activeUser) return; + + // Уже мигрировали — не трогаем + if (localStorage.getItem(MIGRATION_FLAG)) return; + + const key = storageKey(); + + // Если у пользователя уже есть данные — просто помечаем миграцию выполненной + if (localStorage.getItem(key)) { + localStorage.setItem(MIGRATION_FLAG, String(activeUser.id)); + return; + } + + // Ищем старые данные и переносим первому вошедшему пользователю + for (const legacyKey of LEGACY_KEYS) { + const raw = localStorage.getItem(legacyKey); + if (raw) { + localStorage.setItem(key, raw); + localStorage.setItem(MIGRATION_FLAG, String(activeUser.id)); + return; + } + } +} export function loadState() { - const saved = localStorage.getItem(STORAGE_KEY); - if (saved) { - try { - const parsed = JSON.parse(saved); - // Объединяем, чтобы не потерять новые поля при обновлении версии - Object.assign(state, parsed); - if (!state.workoutTypes) state.workoutTypes = []; - if (!state.metricTypes) state.metricTypes = []; - if (!state.clients) state.clients = []; - if (!state.mode) state.mode = 'personal'; - } catch (e) { - console.error('Failed to load state', e); - } + migrateLegacyStateForUser(); + + const raw = localStorage.getItem(storageKey()); + + Object.assign(state, freshState()); + + if (raw) { + try { + const parsed = JSON.parse(raw); + Object.assign(state, parsed); + } catch (e) { + console.error("Failed to load state", e); } + } + + if (!Array.isArray(state.workouts)) state.workouts = []; + if (!Array.isArray(state.exerciseRef)) state.exerciseRef = []; + if (!Array.isArray(state.bodyMetrics)) state.bodyMetrics = []; + if (!Array.isArray(state.workoutTypes)) state.workoutTypes = []; + if (!Array.isArray(state.metricTypes)) state.metricTypes = []; + if (!Array.isArray(state.clients)) state.clients = []; + + if (!state.mode) state.mode = "personal"; } export function saveState() { - localStorage.setItem(STORAGE_KEY, JSON.stringify(state)); - updateSyncStatus(); + localStorage.setItem(storageKey(), JSON.stringify(state)); + updateSyncStatus(); } export function genId() { - return (state.nextId++).toString(); + return (state.nextId++).toString(); } -// Генерация UUID v4 для sync_id (идемпотентность на бэкенде) export function generateUUID() { - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => { - const r = Math.random() * 16 | 0; - const v = c === 'x' ? r : (r & 0x3 | 0x8); - return v.toString(16); - }); + return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { + const r = (Math.random() * 16) | 0; + const v = c === "x" ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); } export function updateSyncStatus() { - const dirty = state.workouts.filter(w => !w.synced); - const el = document.getElementById('sync-status'); - if (!el) return; - if (dirty.length === 0) { - el.textContent = '● Всё синхронизировано'; - el.className = 'sync-status synced'; - } else { - el.textContent = `● ${dirty.length} не сохран.`; - el.className = 'sync-status pending'; - } + const dirty = state.workouts.filter((w) => !w.synced); + const el = document.getElementById("sync-status"); + if (!el) return; + + if (dirty.length === 0) { + el.textContent = "● Всё синхронизировано"; + el.className = "sync-status synced"; + } else { + el.textContent = `● ${dirty.length} не сохран.`; + el.className = "sync-status pending"; + } } + +export const CLIENT_COLORS = [ + "#bb86fc", + "#03dac6", + "#fbbc04", + "#cf6679", + "#64b5f6", + "#81c784", + "#ffb74d", + "#ba68c8", + "#4dd0e1", + "#e57373", + "#aed581", + "#ffd54f", + "#9575cd", + "#4db6ac", + "#f06292", + "#7986cb", +]; + +export const DEFAULT_COLOR = CLIENT_COLORS[0]; diff --git a/frontend/js/sync.js b/frontend/js/sync.js index 12c161d..2a547b8 100644 --- a/frontend/js/sync.js +++ b/frontend/js/sync.js @@ -1,23 +1,37 @@ -import { state, saveState, generateUUID } from "./state.js"; -import { syncData } from "./api.js"; +// frontend/js/sync.js + +import { state, saveState, generateUUID, DEFAULT_COLOR } from "./state.js"; +import { + fetchBootstrapData, + fetchWorkoutTypes, + fetchMetricTypes, + syncData, +} from "./api.js"; import { renderMainScreen } from "./render/main-screen.js"; -export async function initAppData() { - try { - const { fetchWorkoutTypes, fetchMetricTypes } = await import("./api.js"); +// ============================================================ +// Хелперы +// ============================================================ - state.workoutTypes = await fetchWorkoutTypes(); - state.metricTypes = await fetchMetricTypes(); - saveState(); - - console.log("Справочники загружены с бэкенда"); - } catch (e) { - console.warn("Не удалось загрузить справочники (возможно, бэк недоступен):", e); - } +function asString(value) { + if (value === undefined || value === null) return ""; + return String(value); } -export function getDirtyWorkouts() { - return state.workouts.filter((w) => !w.synced); +function normalizeName(value) { + return String(value || "").trim().toLowerCase(); +} + +function toNumberOrNull(value) { + if (value === "" || value === null || value === undefined) return null; + const n = Number(value); + return Number.isFinite(n) ? n : null; +} + +function toIntOrNull(value) { + if (value === "" || value === null || value === undefined) return null; + const n = Number(value); + return Number.isFinite(n) ? Math.trunc(n) : null; } function ensureSyncId(obj) { @@ -28,32 +42,574 @@ function ensureSyncId(obj) { return obj.sync_id; } +// ============================================================ +// Миграция локальных ID в sync_id +// ============================================================ + +/** + * Делает локальные ID совместимыми с серверными sync_id. + * + * Важно: + * - тренировки, упражнения, подходы, кардио, замеры, справочник упражнений + * переводим на sync_id как основной локальный id; + * - клиенты остаются с числовым server_id, если он есть, потому что + * API клиентов использует /clients/{id} с числовым id. + */ +function migrateLocalIdsToSyncId() { + const clientOldToNew = new Map(); + + // Клиенты + for (const client of state.clients || []) { + const oldId = asString(client.id); + + if (!client.sync_id) { + client.sync_id = generateUUID(); + } + + // Если клиент уже синхронизирован, используем серверный числовой id + if (client.server_id) { + client.id = asString(client.server_id); + } else if (!client.id) { + client.id = asString(client.sync_id); + } + + const newId = asString(client.id); + if (oldId && newId && oldId !== newId) { + clientOldToNew.set(oldId, newId); + } + } + + // Тренировки + for (const workout of state.workouts || []) { + const oldClientKey = asString(workout.client_id); + if (oldClientKey && clientOldToNew.has(oldClientKey)) { + workout.client_id = clientOldToNew.get(oldClientKey); + } + + if (!workout.sync_id) { + workout.sync_id = generateUUID(); + } + + const oldWorkoutId = asString(workout.id); + const newWorkoutId = asString(workout.sync_id); + workout.id = newWorkoutId; + + if (asString(state.expandedWorkoutId) === oldWorkoutId) { + state.expandedWorkoutId = newWorkoutId; + } + + for (const exercise of workout.exercises || []) { + if (!exercise.sync_id) { + exercise.sync_id = generateUUID(); + } + + const oldExerciseId = asString(exercise.id); + const newExerciseId = asString(exercise.sync_id); + exercise.id = newExerciseId; + + if (asString(state.expandedExerciseId) === oldExerciseId) { + state.expandedExerciseId = newExerciseId; + } + + for (const set of exercise.sets || []) { + if (!set.sync_id) { + set.sync_id = generateUUID(); + } + set.id = asString(set.sync_id); + } + } + + for (const cardio of workout.cardio || []) { + if (!cardio.sync_id) { + cardio.sync_id = generateUUID(); + } + cardio.id = asString(cardio.sync_id); + } + } + + // Замеры + for (const metric of state.bodyMetrics || []) { + const oldClientKey = asString(metric.client_id); + if (oldClientKey && clientOldToNew.has(oldClientKey)) { + metric.client_id = clientOldToNew.get(oldClientKey); + } + + if (!metric.sync_id) { + metric.sync_id = generateUUID(); + } + + metric.id = asString(metric.sync_id); + } + + // Справочник упражнений + for (const exercise of state.exerciseRef || []) { + if (!exercise.sync_id) { + exercise.sync_id = generateUUID(); + } + exercise.id = asString(exercise.sync_id); + } +} + +// ============================================================ +// Конвертация backend -> frontend +// ============================================================ + +function convertBackendClient(c) { + const syncId = c.sync_id || generateUUID(); + const serverId = asString(c.id); + + return { + id: serverId || syncId, + sync_id: syncId, + server_id: serverId || null, + full_name: c.full_name || "", + birth_date: c.birth_date || "", + goal: c.goal || "", + notes: c.notes || "", + color: c.color || DEFAULT_COLOR, + is_active: c.is_active ?? 1, + }; +} + +function convertBackendExercise(e, workoutTypeNameById) { + const syncId = e.sync_id || generateUUID(); + + return { + id: syncId, + sync_id: syncId, + server_id: e.id ?? null, + name: e.name || "", + workoutType: e.workout_type_id + ? workoutTypeNameById[asString(e.workout_type_id)] || "" + : "", + }; +} + +function convertBackendWorkoutToFrontend(w) { + const workoutSyncId = w.sync_id || generateUUID(); + + // Используем подготовленное имя типа из бэкенда, если оно есть, иначе ищем по ID + let typeStr = w.workout_type_name; + if (!typeStr && w.workout_type_id) { + const wt = state.workoutTypes.find(t => String(t.id) === String(w.workout_type_id)); + typeStr = wt ? wt.name : ""; + } + + return { + id: workoutSyncId, + sync_id: workoutSyncId, + server_id: w.id ?? null, + client_id: w.client_id ? asString(w.client_id) : null, + startTime: w.start_time || new Date().toISOString(), + endTime: w.end_time || null, + type: typeStr || "", // Имя типа тренировки + notes: w.notes || "", + synced: true, + + exercises: (w.workout_exercises || []).map((ex) => { + const exSyncId = ex.sync_id || generateUUID(); + + return { + id: exSyncId, + sync_id: exSyncId, + server_id: ex.id ?? null, + exercise_id: ex.exercise_id ?? null, + name: ex.exercise_name || "", + sort_order: ex.sort_order ?? 0, + + sets: (ex.sets || []).map((s) => { + const setSyncId = s.sync_id || generateUUID(); + + return { + id: setSyncId, + sync_id: setSyncId, + server_id: s.id ?? null, + isDropset: !!s.is_dropset, + weight: s.weight ?? null, + reps: s.reps ?? null, + rating: s.rating ?? 3, + notes: s.notes || "", + timestamp: s.timestamp || w.start_time || new Date().toISOString(), + sort_order: s.sort_order ?? 0, + + subSets: (s.dropset_items || []).map((di) => ({ + weight: di.weight ?? 0, + reps: di.reps ?? 0, + sort_order: di.sort_order ?? 0, + })), + }; + }), + }; + }), + + cardio: (w.cardio_sessions || []).map((c) => { + const cardioSyncId = c.sync_id || generateUUID(); + + return { + id: cardioSyncId, + sync_id: cardioSyncId, + server_id: c.id ?? null, + type: c.cardio_type || "", + purpose: c.purpose || "separate", + duration: c.duration ?? null, + distance: c.distance ?? null, + speed: c.speed ?? null, + incline: c.incline ?? null, + resistance: c.resistance ?? null, + notes: c.notes || "", + sort_order: c.sort_order ?? 0, + }; + }), + }; +} + +function convertBackendWorkout(w, workoutTypeNameById) { + const workoutSyncId = w.sync_id || generateUUID(); + + return { + id: workoutSyncId, + sync_id: workoutSyncId, + server_id: w.id ?? null, + client_id: w.client_id ? asString(w.client_id) : null, + startTime: w.start_time || new Date().toISOString(), + endTime: w.end_time || null, + type: w.workout_type_id + ? workoutTypeNameById[asString(w.workout_type_id)] || "" + : "", + notes: w.notes || "", + synced: true, + + exercises: (w.workout_exercises || []).map((ex) => { + const exSyncId = ex.sync_id || generateUUID(); + + return { + id: exSyncId, + sync_id: exSyncId, + server_id: ex.id ?? null, + exercise_id: ex.exercise_id ?? null, + name: ex.exercise_name || "", + sort_order: ex.sort_order ?? 0, + + sets: (ex.sets || []).map((s) => { + const setSyncId = s.sync_id || generateUUID(); + + return { + id: setSyncId, + sync_id: setSyncId, + server_id: s.id ?? null, + isDropset: !!s.is_dropset, + weight: s.weight ?? null, + reps: s.reps ?? null, + rating: s.rating ?? 3, + notes: s.notes || "", + timestamp: s.timestamp || w.start_time || new Date().toISOString(), + sort_order: s.sort_order ?? 0, + + subSets: (s.dropset_items || []).map((di) => ({ + weight: di.weight ?? 0, + reps: di.reps ?? 0, + sort_order: di.sort_order ?? 0, + })), + }; + }), + }; + }), + + cardio: (w.cardio_sessions || []).map((c) => { + const cardioSyncId = c.sync_id || generateUUID(); + + return { + id: cardioSyncId, + sync_id: cardioSyncId, + server_id: c.id ?? null, + type: c.cardio_type || "", + purpose: c.purpose || "separate", + duration: c.duration ?? null, + distance: c.distance ?? null, + speed: c.speed ?? null, + incline: c.incline ?? null, + resistance: c.resistance ?? null, + notes: c.notes || "", + sort_order: c.sort_order ?? 0, + }; + }), + }; +} + +function convertBackendMetric(m) { + const metricSyncId = m.sync_id || generateUUID(); + + return { + id: metricSyncId, + sync_id: metricSyncId, + server_id: m.id ?? null, + client_id: m.client_id ? asString(m.client_id) : null, + date: m.metric_date || new Date().toISOString(), + notes: m.notes || "", + values: (m.values || []).map((v) => ({ + metric_type_id: v.metric_type_id, + value: v.value, + })), + }; +} + +// ============================================================ +// Merge локальных и серверных данных +// ============================================================ + +function mergeBySyncId(localItems, serverItems, options = {}) { + const map = new Map(); + + // Сначала серверные данные + for (const item of serverItems || []) { + const key = item?.sync_id; + if (key) { + map.set(key, item); + } + } + + // Потом локальные + for (const item of localItems || []) { + const key = item?.sync_id; + + if (!key) { + // На всякий случай: если вдруг нет sync_id, сохраняем локальное по id + map.set(`local:${item?.id}`, item); + continue; + } + + const shouldKeepLocal = + options.localWinsIfDirty && item.synced === false; + + if (shouldKeepLocal) { + // Несинхронизированная локальная тренировка важнее серверной копии + map.set(key, item); + } else if (!map.has(key)) { + map.set(key, item); + } + } + + return Array.from(map.values()); +} + +function mergeClients(localItems, serverItems) { + // 1. Merge по sync_id + const bySync = new Map(); + + for (const item of serverItems || []) { + if (item?.sync_id) { + bySync.set(item.sync_id, item); + } + } + + for (const item of localItems || []) { + if (!item?.sync_id) continue; + + // Серверный клиент важнее локального с тем же sync_id + if (!bySync.has(item.sync_id)) { + bySync.set(item.sync_id, item); + } + } + + // 2. Deduplicate по id, чтобы не было двух клиентов с одним числовым id + const byId = new Map(); + + for (const item of bySync.values()) { + const id = asString(item.id); + if (!id) continue; + + const existing = byId.get(id); + + if (!existing) { + byId.set(id, item); + } else if (item.server_id && !existing.server_id) { + // Серверный клиент побеждает локальный при конфликте id + byId.set(id, item); + } + } + + return Array.from(byId.values()); +} + +function mergeExerciseRef(localItems, serverItems) { + // Справочник упражнений лучше мержить по имени, + // иначе могут появиться дубли "Жим лежа" с разными sync_id. + const map = new Map(); + + for (const item of serverItems || []) { + const key = normalizeName(item.name); + if (key) { + map.set(key, item); + } + } + + for (const item of localItems || []) { + const key = normalizeName(item.name); + if (key && !map.has(key)) { + map.set(key, item); + } + } + + return Array.from(map.values()).sort((a, b) => + String(a.name || "").localeCompare(String(b.name || "")) + ); +} + +function resolveClientId(rawId, clients) { + const key = asString(rawId); + if (!key) return null; + + // Ищем по id + const byId = (clients || []).find((c) => asString(c.id) === key); + if (byId) return asString(byId.id); + + // Ищем по sync_id + const bySync = (clients || []).find((c) => asString(c.sync_id) === key); + if (bySync) return asString(bySync.id); + + // Если не нашли — оставляем как есть + return key; +} + +function reconcileClientReferences() { + for (const workout of state.workouts || []) { + workout.client_id = resolveClientId(workout.client_id, state.clients); + } + + for (const metric of state.bodyMetrics || []) { + metric.client_id = resolveClientId(metric.client_id, state.clients); + } +} + +// ============================================================ +// Загрузка данных пользователя с сервера +// ============================================================ + +export async function initAppData() { + try { + console.log("🔄 Загружаем bootstrap-данные с сервера..."); + + const data = await fetchBootstrapData(); + + // Сначала нормализуем локальные ID, чтобы корректно смержить + migrateLocalIdsToSyncId(); + + // Справочники + state.workoutTypes = Array.isArray(data.workout_types) + ? data.workout_types + : []; + + state.metricTypes = Array.isArray(data.metric_types) + ? data.metric_types + : []; + + const workoutTypeNameById = {}; + for (const wt of state.workoutTypes || []) { + workoutTypeNameById[asString(wt.id)] = wt.name; + } + + // Клиенты + const serverClients = (data.clients || []).map(convertBackendClient); + state.clients = mergeClients(state.clients || [], serverClients); + + // Упражнения / справочник + const serverExercises = (data.exercises || []).map((e) => + convertBackendExercise(e, workoutTypeNameById) + ); + state.exerciseRef = mergeExerciseRef( + state.exerciseRef || [], + serverExercises + ); + + // Тренировки + const serverWorkouts = (data.workouts || []).map((w) => + convertBackendWorkout(w, workoutTypeNameById) + ); + + state.workouts = mergeBySyncId( + state.workouts || [], + serverWorkouts, + { localWinsIfDirty: true } + ); + + // Замеры + const serverMetrics = (data.body_metrics || []).map(convertBackendMetric); + state.bodyMetrics = mergeBySyncId( + state.bodyMetrics || [], + serverMetrics + ); + + // Чиним ссылки на клиентов после merge + reconcileClientReferences(); + + saveState(); + renderMainScreen(); + + console.log( + `✅ Bootstrap загружен: тренировок ${state.workouts.length}, клиентов ${state.clients.length}, замеров ${state.bodyMetrics.length}` + ); + } catch (e) { + console.warn("❌ Bootstrap не удался, пробуем загрузить только справочники:", e); + + try { + const [workoutTypes, metricTypes] = await Promise.all([ + fetchWorkoutTypes(), + fetchMetricTypes(), + ]); + + state.workoutTypes = Array.isArray(workoutTypes) ? workoutTypes : []; + state.metricTypes = Array.isArray(metricTypes) ? metricTypes : []; + + saveState(); + renderMainScreen(); + + console.log("✅ Справочники загружены отдельно"); + } catch (e2) { + console.warn("❌ Не удалось загрузить даже справочники:", e2); + + if (!Array.isArray(state.workoutTypes)) state.workoutTypes = []; + if (!Array.isArray(state.metricTypes)) state.metricTypes = []; + } + } +} + +// ============================================================ +// Синхронизация frontend -> backend +// ============================================================ + +export function getDirtyWorkouts() { + return state.workouts.filter((w) => !w.synced); +} + function findWorkoutTypeByName(name) { if (!name) return null; return state.workoutTypes.find((t) => t.name === name) || null; } function findExerciseRefByName(name) { - const normalized = String(name || "").trim().toLowerCase(); + const normalized = normalizeName(name); if (!normalized) return null; return ( state.exerciseRef.find( - (e) => String(e.name || "").trim().toLowerCase() === normalized + (e) => normalizeName(e.name) === normalized ) || null ); } function findClientByLocalId(clientId) { - if (clientId === undefined || clientId === null || clientId === "") return null; + const key = asString(clientId); + if (!key) return null; return ( - state.clients.find((c) => String(c.id) === String(clientId)) || null + state.clients.find( + (c) => asString(c.id) === key || asString(c.sync_id) === key + ) || null ); } function buildClientsPayload() { - return state.clients.map((c) => { + return (state.clients || []).map((c) => { ensureSyncId(c); return { @@ -69,7 +625,7 @@ function buildClientsPayload() { } function buildExercisesPayload() { - return state.exerciseRef.map((e) => { + return (state.exerciseRef || []).map((e) => { ensureSyncId(e); const wt = findWorkoutTypeByName(e.workoutType); @@ -91,18 +647,21 @@ function buildSetsPayload(sets) { return { sync_id: s.sync_id, is_dropset: isDropset ? 1 : 0, - weight: isDropset ? null : (parseFloat(s.weight) || null), - reps: isDropset ? null : (parseInt(s.reps, 10) || null), - rating: s.rating || 3, + weight: isDropset ? null : toNumberOrNull(s.weight), + reps: isDropset ? null : toIntOrNull(s.reps), + rating: toIntOrNull(s.rating) ?? 3, notes: s.notes || "", sort_order: s.sort_order ?? setIndex, timestamp: s.timestamp || new Date().toISOString(), + dropset_items: isDropset - ? (s.subSets || []).map((item, itemIndex) => ({ - weight: parseFloat(item.weight) || 0, - reps: parseInt(item.reps, 10) || 0, - sort_order: item.sort_order ?? itemIndex, - })) + ? (s.subSets || []) + .map((item, itemIndex) => ({ + weight: toNumberOrNull(item.weight) ?? 0, + reps: toIntOrNull(item.reps) ?? 0, + sort_order: item.sort_order ?? itemIndex, + })) + .filter((item) => item.weight > 0 && item.reps > 0) : [], }; }); @@ -117,7 +676,7 @@ function buildWorkoutExercisesPayload(exercises) { return { sync_id: ex.sync_id, exercise_sync_id: exerciseRef ? exerciseRef.sync_id : null, - exercise_id: ex.exercise_id || null, + exercise_id: ex.exercise_id || ex.server_id || null, exercise_name: ex.name, sort_order: ex.sort_order ?? exIndex, sets: buildSetsPayload(ex.sets), @@ -133,11 +692,11 @@ function buildCardioPayload(cardioList) { sync_id: c.sync_id, cardio_type: c.type || "другое", purpose: c.purpose || "separate", - duration: c.duration || null, - distance: c.distance || null, - speed: c.speed || null, - incline: c.incline || null, - resistance: c.resistance || null, + duration: toIntOrNull(c.duration), + distance: toNumberOrNull(c.distance), + speed: toNumberOrNull(c.speed), + incline: toNumberOrNull(c.incline), + resistance: toIntOrNull(c.resistance), notes: c.notes || "", sort_order: c.sort_order ?? cIndex, }; @@ -153,91 +712,150 @@ function buildWorkoutsPayload(dirty) { return { sync_id: w.sync_id, + + // Для клиентов отправляем именно sync_id, + // потому что локальный id может отличаться на разных устройствах. client_id: null, client_sync_id: client ? client.sync_id : null, + workout_type_id: wt ? wt.id : null, start_time: w.startTime, end_time: w.endTime || null, notes: w.notes || "", + workout_exercises: buildWorkoutExercisesPayload(w.exercises), cardio_sessions: buildCardioPayload(w.cardio), }; }); } +// ... предыдущие импорты и хелперы остаются ... + export async function sync() { - const dirty = getDirtyWorkouts(); + const dirtyWorkouts = getDirtyWorkouts(); + const dirtyMetrics = getDirtyMetrics(); // Новая функция - if (dirty.length === 0) { - alert("Нет данных для синхронизации"); - return; - } - - const btn = document.querySelector(".header-actions .btn-secondary"); - if (btn) { - btn.disabled = true; - btn.textContent = "⏳"; - } - - try { - // Генерируем sync_id локально и сохраняем, чтобы при повторе не плодить дубли - state.clients.forEach(ensureSyncId); - state.exerciseRef.forEach(ensureSyncId); - - dirty.forEach((w) => { - ensureSyncId(w); - - (w.exercises || []).forEach((ex) => { - ensureSyncId(ex); - (ex.sets || []).forEach(ensureSyncId); - }); - - (w.cardio || []).forEach(ensureSyncId); - }); - - saveState(); - - const payload = { - clients: buildClientsPayload(), - exercises: buildExercisesPayload(), - workouts: buildWorkoutsPayload(dirty), - body_metrics: [], // динамические замеры подключим следующим этапом - }; - - console.log("📤 Отправляем на синхронизацию:", payload); - - const response = await syncData(payload); - console.log("✅ Ответ синхронизации:", response); - - dirty.forEach((w) => { - w.synced = true; - }); - - saveState(); - - if (typeof window.renderMainScreen === "function") { - window.renderMainScreen(); - } else { - renderMainScreen(); + if (dirtyWorkouts.length === 0 && dirtyMetrics.length === 0) { + alert("Нет данных для синхронизации"); + return; } - const createdWorkouts = response.created?.workouts || 0; - const updatedWorkouts = response.updated?.workouts || 0; - const warnings = response.warnings || []; - - let message = `Синхронизировано: создано ${createdWorkouts}, обновлено ${updatedWorkouts}`; - if (warnings.length) { - message += `\n\nПредупреждения:\n${warnings.join("\n")}`; - } - - alert(message); - } catch (e) { - console.error("❌ Sync error:", e); - alert("Ошибка синхронизации: " + e.message); - } finally { + const btn = document.querySelector(".header-actions .btn-secondary"); if (btn) { - btn.disabled = false; - btn.textContent = "🔄"; + btn.disabled = true; + btn.textContent = "⏳"; + } + + try { + // Генерируем sync_id для всего необходимого + ensureSyncIds(dirtyWorkouts, dirtyMetrics); + + const payload = { + clients: buildClientsPayload(), + exercises: buildExercisesPayload(), + workouts: buildWorkoutsPayload(dirtyWorkouts), + body_metrics: buildMetricsPayload(dirtyMetrics), // Отправляем замеры + }; + + console.log("📤 Sending sync payload:", payload); + + const response = await syncData(payload); + console.log("✅ Sync response:", response); + + // Помечаем все как синхронизированные + dirtyWorkouts.forEach(w => w.synced = true); + dirtyMetrics.forEach(m => m.synced = true); + + saveState(); + + if (typeof window.renderMainScreen === "function") { + window.renderMainScreen(); + } + + const createdW = response.created?.workouts || 0; + const createdM = response.created?.body_metrics || 0; + + let message = `Синхронизировано:\nТренировок: ${createdW}\nЗамеров: ${createdM}`; + + if (response.warnings?.length) { + message += `\n\nПредупреждения:\n${response.warnings.join("\n")}`; + } + + alert(message); + + } catch (e) { + console.error("❌ Sync error:", e); + alert("Ошибка синхронизации: " + e.message); + } finally { + if (btn) { + btn.disabled = false; + btn.textContent = "🔄"; + } } - } +} + +// --- НОВЫЕ ХЕЛПЕРЫ ДЛЯ ЗАМЕРОВ --- + +function getDirtyMetrics() { + return state.bodyMetrics.filter(m => !m.synced); +} + +function ensureSyncIds(workouts, metrics) { + // Тренировки + workouts.forEach(w => { + if (!w.sync_id) w.sync_id = generateUUID(); + (w.exercises || []).forEach(ex => { + if (!ex.sync_id) ex.sync_id = generateUUID(); + (ex.sets || []).forEach(s => { + if (!s.sync_id) s.sync_id = generateUUID(); + }); + }); + (w.cardio || []).forEach(c => { + if (!c.sync_id) c.sync_id = generateUUID(); + }); + }); + + // Замеры + metrics.forEach(m => { + if (!m.sync_id) m.sync_id = generateUUID(); + }); +} + +function buildMetricsPayload(metrics) { + return metrics.map(m => { + // Ищем server_id клиента, если есть + let clientServerId = null; + if (m.client_id) { + const client = state.clients.find(c => String(c.id) === String(m.client_id)); + if (client && client.server_id) { + clientServerId = client.server_id; + } else if (client && client.sync_id) { + // Если нет server_id, но есть sync_id, бэк может найти его по sync_id + // Но в нашей схеме BodyMetricCreate ожидает client_id (int) или client_sync_id (str)? + // Смотрим schemas.py: BodyMetricCreate имеет client_id: Optional[int] и client_sync_id: Optional[str] + // Лучше отправить sync_id, если server_id неизвестен + return { + sync_id: m.sync_id, + client_sync_id: client.sync_id, + metric_date: m.date, + notes: m.notes || "", + values: (m.values || []).map(v => ({ + metric_type_id: v.metric_type_id, + value: v.value + })) + }; + } + } + + return { + sync_id: m.sync_id, + client_id: clientServerId, // Числовой ID, если известен + metric_date: m.date, + notes: m.notes || "", + values: (m.values || []).map(v => ({ + metric_type_id: v.metric_type_id, + value: v.value + })) + }; + }); } diff --git a/frontend/nginx.conf b/frontend/nginx.conf index 003fb0d..4fd86f0 100644 --- a/frontend/nginx.conf +++ b/frontend/nginx.conf @@ -6,19 +6,28 @@ server { location / { root /usr/share/nginx/html; index index.html; - try_files $uri $uri/ /index.html; # Для SPA роутинга (если понадобится) + try_files $uri $uri/ /index.html; } # Проксирование API на бэкенд location /api/ { proxy_pass http://backend:8000/; + + # КРИТИЧЕСКИ ВАЖНЫЕ ЗАГОЛОВКИ ДЛЯ JWT/AUTHORIZATION + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + # ЭТА СТРОКА ИСПРАВЛЯЕТ ОШИБКУ 401: + proxy_set_header Authorization $http_authorization; + + # Для WebSocket (если понадобится в будущем) proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection 'upgrade'; - proxy_set_header Host $host; - proxy_cache_bypass $http_upgrade; + proxy_set_header Connection "upgrade"; - # Важно: убираем префикс /api, так как бэк ожидает пути вроде /auth/login + # Убираем префикс /api, так как бэк ожидает пути вроде /auth/login rewrite ^/api/(.*)$ /$1 break; } }