Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 232d03eebd | |||
| b19c864bbf | |||
| e3ec434f03 | |||
| 0968e2a86d | |||
| e6cc7eda0a | |||
| ec476f5ce6 | |||
| b72f5f8e36 | |||
| d7b9d0fa2d | |||
| 569b94f799 | |||
| 5d2ed76e29 | |||
| 7343a950f8 | |||
| 97176ed90e | |||
| e77aa6df17 | |||
| baa0f57536 | |||
| 4da4fd9365 | |||
| 35fabb1610 | |||
| 50eba83266 | |||
| 9fe1b41c2c | |||
| 7c42744d10 | |||
| 9979859b76 | |||
| b0fa3f7291 | |||
| c3a34192ab | |||
| 9a987baa5c | |||
| 83ff9ae6e4 | |||
| a9d535c688 | |||
| a33c1b4bb2 | |||
| a38ebbb941 | |||
| cd1720158a | |||
| 340751dd17 | |||
| 2a5c9709e0 | |||
| 459e5ff136 | |||
| 728d342a89 |
@@ -0,0 +1,9 @@
|
||||
.git
|
||||
__pycache__
|
||||
*.pyc
|
||||
node_modules
|
||||
.env
|
||||
data/
|
||||
*.md
|
||||
.vscode
|
||||
.idea
|
||||
@@ -0,0 +1 @@
|
||||
JWT_SECRET=my-very-long-random-string-for-production
|
||||
@@ -1,2 +1,7 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
*.db
|
||||
.venv/
|
||||
data/
|
||||
node_modules/
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.db
|
||||
*.sqlite*
|
||||
.env
|
||||
.env.*
|
||||
venv/
|
||||
.venv/
|
||||
data/
|
||||
.dockerignore
|
||||
@@ -0,0 +1,18 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Устанавливаем зависимости
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Копируем код
|
||||
COPY . .
|
||||
|
||||
# Создаём директорию для БД внутри контейнера (будет смонтирована volume)
|
||||
RUN mkdir -p /data
|
||||
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
+10
-2
@@ -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
|
||||
|
||||
|
||||
+5
-4
@@ -1,18 +1,19 @@
|
||||
import os
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, declarative_base
|
||||
|
||||
SQLALCHEMY_DATABASE_URL = "sqlite:///./gym.db"
|
||||
# По умолчанию используем локальный файл, но в Docker мы зададим env var
|
||||
DB_PATH = os.getenv("GYM_DB_PATH", "./gym.db")
|
||||
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_PATH}"
|
||||
|
||||
engine = create_engine(
|
||||
SQLALCHEMY_DATABASE_URL,
|
||||
connect_args={"check_same_thread": False} # только для SQLite
|
||||
connect_args={"check_same_thread": False}
|
||||
)
|
||||
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
# Dependency
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
|
||||
+26
-1
@@ -1,8 +1,12 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
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
|
||||
@@ -11,9 +15,29 @@ 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)
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
# Лёгкая миграция: create_all не трогает уже существующие таблицы, а колонки,
|
||||
# добавленные после релиза, заводить надо (SQLite, без alembic)
|
||||
def _ensure_columns():
|
||||
from sqlalchemy import inspect, text
|
||||
insp = inspect(engine)
|
||||
if "workouts" not in insp.get_table_names():
|
||||
return
|
||||
cols = {c["name"] for c in insp.get_columns("workouts")}
|
||||
if "set_groups" not in cols:
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("ALTER TABLE workouts ADD COLUMN set_groups TEXT DEFAULT '[]'"))
|
||||
|
||||
_ensure_columns()
|
||||
|
||||
app = FastAPI(
|
||||
title="Gym Bro API",
|
||||
description="API для трекера тренировок с офлайн-синхронизацией и авторизацией",
|
||||
@@ -36,6 +60,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("/")
|
||||
|
||||
+13
-12
@@ -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")
|
||||
@@ -97,6 +95,9 @@ class Workout(Base):
|
||||
start_time = Column(String, nullable=False)
|
||||
end_time = Column(String)
|
||||
notes = Column(String, default="")
|
||||
# Состав сетов (JSON: [{"sync_id","name","exercise_sync_ids":[...]}]) —
|
||||
# плоским полем, т.к. структура целиком принадлежит клиенту
|
||||
set_groups = Column(String, default="[]")
|
||||
synced = Column(Integer, default=0)
|
||||
|
||||
created_at = Column(String)
|
||||
@@ -232,7 +233,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 +249,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(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
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
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
# backend/routers/bootstrap.py
|
||||
|
||||
import json
|
||||
|
||||
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
|
||||
try:
|
||||
set_groups = json.loads(w.set_groups or "[]")
|
||||
if not isinstance(set_groups, list):
|
||||
set_groups = []
|
||||
except Exception:
|
||||
set_groups = []
|
||||
|
||||
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,
|
||||
"set_groups": set_groups,
|
||||
"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))
|
||||
+144
-84
@@ -1,3 +1,4 @@
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Dict, Optional, Tuple
|
||||
@@ -168,26 +169,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 +285,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
|
||||
|
||||
@@ -331,6 +323,47 @@ def sync_data(
|
||||
client_map: Dict[str, int] = {}
|
||||
exercise_map: Dict[str, int] = {}
|
||||
|
||||
deleted = {"workouts": 0}
|
||||
|
||||
# ========================================================
|
||||
# 0. Удаления (надгробия с клиента): снимаем тренировки по sync_id
|
||||
# вместе с упражнениями, сетами, дроп-сетами и кардио.
|
||||
# ========================================================
|
||||
for sid in payload.deleted_sync_ids or []:
|
||||
target = (
|
||||
db.query(models.Workout)
|
||||
.filter(
|
||||
models.Workout.sync_id == sid,
|
||||
models.Workout.owner_id == current_user.id,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not target:
|
||||
continue
|
||||
we_ids = [e.id for e in target.workout_exercises]
|
||||
if we_ids:
|
||||
set_ids = [
|
||||
s.id
|
||||
for s in db.query(models.Set)
|
||||
.filter(models.Set.workout_exercise_id.in_(we_ids))
|
||||
.all()
|
||||
]
|
||||
if set_ids:
|
||||
db.query(models.DropsetItem).filter(
|
||||
models.DropsetItem.set_id.in_(set_ids)
|
||||
).delete(synchronize_session=False)
|
||||
db.query(models.Set).filter(
|
||||
models.Set.workout_exercise_id.in_(we_ids)
|
||||
).delete(synchronize_session=False)
|
||||
db.query(models.WorkoutExercise).filter(
|
||||
models.WorkoutExercise.id.in_(we_ids)
|
||||
).delete(synchronize_session=False)
|
||||
db.query(models.Cardio).filter(
|
||||
models.Cardio.workout_id == target.id
|
||||
).delete(synchronize_session=False)
|
||||
db.delete(target)
|
||||
deleted["workouts"] += 1
|
||||
|
||||
# ========================================================
|
||||
# 1. Clients
|
||||
# ========================================================
|
||||
@@ -370,6 +403,10 @@ def sync_data(
|
||||
existing.end_time = workout_data.end_time if workout_data.end_time is not None else existing.end_time
|
||||
existing.notes = workout_data.notes if workout_data.notes is not None else existing.notes
|
||||
existing.workout_type_id = resolve_workout_type_id(db, workout_data.workout_type_id)
|
||||
if workout_data.set_groups is not None:
|
||||
existing.set_groups = json.dumps(
|
||||
[g.model_dump() for g in workout_data.set_groups], ensure_ascii=False
|
||||
)
|
||||
existing.synced = 1
|
||||
existing.updated_at = timestamp
|
||||
|
||||
@@ -407,6 +444,9 @@ def sync_data(
|
||||
start_time=workout_data.start_time,
|
||||
end_time=workout_data.end_time,
|
||||
notes=workout_data.notes or "",
|
||||
set_groups=json.dumps(
|
||||
[g.model_dump() for g in workout_data.set_groups or []], ensure_ascii=False
|
||||
),
|
||||
synced=1,
|
||||
created_at=timestamp,
|
||||
updated_at=timestamp,
|
||||
@@ -449,21 +489,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,80 +516,96 @@ 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(
|
||||
status="success",
|
||||
created=created,
|
||||
updated=updated,
|
||||
deleted=deleted,
|
||||
warnings=warnings,
|
||||
)
|
||||
|
||||
+10
-1
@@ -1,7 +1,6 @@
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional, List, Dict, Any
|
||||
|
||||
|
||||
# ============================================================
|
||||
# AUTH / USERS
|
||||
# ============================================================
|
||||
@@ -253,10 +252,17 @@ class WorkoutBase(BaseModel):
|
||||
workout_type_id: Optional[int] = None
|
||||
|
||||
|
||||
class SetGroupData(BaseModel):
|
||||
sync_id: Optional[str] = None
|
||||
name: str = "Сет"
|
||||
exercise_sync_ids: List[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class WorkoutCreate(WorkoutBase):
|
||||
sync_id: Optional[str] = None
|
||||
client_id: Optional[int] = None
|
||||
client_sync_id: Optional[str] = None
|
||||
set_groups: Optional[List[SetGroupData]] = None
|
||||
workout_exercises: List[WorkoutExerciseCreate] = Field(default_factory=list)
|
||||
cardio_sessions: List[CardioCreate] = Field(default_factory=list)
|
||||
|
||||
@@ -338,10 +344,13 @@ class SyncPayload(BaseModel):
|
||||
exercises: List[ExerciseCreate] = Field(default_factory=list)
|
||||
workouts: List[WorkoutCreate] = Field(default_factory=list)
|
||||
body_metrics: List[BodyMetricCreate] = Field(default_factory=list)
|
||||
# Удалённые на клиенте тренировки (sync_id) — иначе bootstrap возвращает их обратно
|
||||
deleted_sync_ids: List[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class SyncResponse(BaseModel):
|
||||
status: str
|
||||
created: Dict[str, int]
|
||||
updated: Dict[str, int]
|
||||
deleted: Dict[str, int] = Field(default_factory=dict)
|
||||
warnings: List[str] = Field(default_factory=list)
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
services:
|
||||
backend:
|
||||
build:
|
||||
context: ./backend
|
||||
network: host
|
||||
container_name: gym-bro-backend
|
||||
environment:
|
||||
- GYM_JWT_SECRET=${JWT_SECRET:-super-secret-key-change-in-prod}
|
||||
- GYM_DB_PATH=/data/gym.db
|
||||
volumes:
|
||||
- ./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 занят другим nginx на сервере — поднимите на другом порту: APP_PORT=8080 docker compose up -d
|
||||
- "${APP_PORT:-80}:80"
|
||||
depends_on:
|
||||
backend:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- gym-net
|
||||
|
||||
networks:
|
||||
gym-net:
|
||||
driver: bridge
|
||||
@@ -0,0 +1,4 @@
|
||||
demo.html
|
||||
.env
|
||||
.env.*
|
||||
.dockerignore
|
||||
@@ -0,0 +1,9 @@
|
||||
FROM nginx:alpine
|
||||
|
||||
# Копируем конфиг
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
# Копируем статику
|
||||
COPY . /usr/share/nginx/html
|
||||
|
||||
EXPOSE 80
|
||||
@@ -0,0 +1,57 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>График прогрессии (просмотр)</title>
|
||||
<link rel="stylesheet" href="styles/main.css?v=2">
|
||||
<link rel="stylesheet" href="styles/components.css?v=2">
|
||||
<link rel="stylesheet" href="styles/workout.css?v=2">
|
||||
<link rel="stylesheet" href="styles/modal.css?v=2">
|
||||
<style>
|
||||
.chart-page { max-width: 760px; margin: 0 auto; padding: 16px; }
|
||||
.chart-page h2 { margin: 14px 0 2px; }
|
||||
.chart-page .hint { font-size: 0.75rem; color: var(--text-secondary, #888); margin: 4px 0 8px; }
|
||||
.chart-page canvas { width: 100%; background: #1e1e1e; border-radius: 10px; }
|
||||
.chart-open { margin: 8px 0 4px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="chart-page">
|
||||
<h2>📈 Жим штанги лёжа — рабочий максимум важнее числа подходов</h2>
|
||||
<p class="hint">Вершина линии — главный вес дня «вес × повторы». 12.11: <b>100×1</b> (шесть подходов), 19.11: <b>100×2</b> (пять подходов, разминочных меньше) — вершина зелёная: вес тот же, повторов больше, это прогресс, хотя подходов меньше. Тусклые точки — разминочные и остальные подходы.</p>
|
||||
<canvas id="chart-barbell" width="680" height="320"></canvas>
|
||||
<button class="btn btn-small btn-secondary chart-open" onclick="window.CM.showChartDialog('Жим штанги лёжа')">Открыть карточку графика (как в приложении) 📈</button>
|
||||
<button class="btn btn-small btn-secondary chart-open" onclick="window.EM.showSummaryDialog('Жим штанги лёжа')">Сводка по упражнению 📋</button>
|
||||
|
||||
<h2>📈 Жим гантелей на лавке (30/45 — одна группа вариантов)</h2>
|
||||
<p class="hint">Прогрессия 20→28 кг; 17.11 после паузы — красный откат, это тоже видно.</p>
|
||||
<canvas id="chart-dumbbell" width="680" height="320"></canvas>
|
||||
<button class="btn btn-small btn-secondary chart-open" onclick="window.CM.showChartDialog('Жим гантелей на лавке 30')">Карточка графика 📈</button>
|
||||
<button class="btn btn-small btn-secondary chart-open" onclick="window.EM.showSummaryDialog('Жим гантелей на лавке 30')">Сводка по упражнению 📋</button>
|
||||
</div>
|
||||
<div id="modal-container"></div>
|
||||
<script src="demo-seed.js"></script>
|
||||
<script>
|
||||
// Превью всегда работает в гостевом режиме на свежем датасете:
|
||||
// если в этом браузере есть сохранённый вход, данные читались бы из пустого
|
||||
// пользовательского ключа и график показал бы «нет завершённых тренировок».
|
||||
localStorage.removeItem('gym_auth_token');
|
||||
localStorage.removeItem('gym_auth_user');
|
||||
localStorage.setItem('gym_tracker_v7_guest', JSON.stringify(window.GYM_DEMO_SEED));
|
||||
</script>
|
||||
<script type="module">
|
||||
import { loadState } from './js/state.js';
|
||||
import { drawExerciseProgress } from './js/render/dashboard.js';
|
||||
import './js/modals/chart-modal.js';
|
||||
import './js/modals/exercise-summary.js';
|
||||
|
||||
loadState(); // state наполняется из localStorage только этим вызовом (как в app.js)
|
||||
drawExerciseProgress(document.getElementById('chart-barbell'), 'Жим штанги лёжа');
|
||||
drawExerciseProgress(document.getElementById('chart-dumbbell'), 'Жим гантелей на лавке 30');
|
||||
// ?modal=1 — сразу открыть полноэкранный график (для проверки модалки без клика)
|
||||
if (location.search.includes('modal=1')) window.CM.showChartDialog('Жим штанги лёжа');
|
||||
if (location.search.includes('summary=1')) window.EM.showSummaryDialog('Жим штанги лёжа');
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,975 @@
|
||||
// автосгенерировано (gym_seed + пиратка жима) — демо-датасет (не коммитить)
|
||||
window.GYM_DEMO_SEED = {
|
||||
"workouts": [
|
||||
{
|
||||
"id": "w1",
|
||||
"client_id": null,
|
||||
"startTime": "2026-10-16T18:30:00+03:00",
|
||||
"endTime": "2026-10-16T19:30:00+03:00",
|
||||
"type": "грудь-руки",
|
||||
"exercises": [
|
||||
{
|
||||
"id": "e2",
|
||||
"name": "Жим гантелей на лавке 30",
|
||||
"sets": [
|
||||
{
|
||||
"id": "s3",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-10-16T18:40:00+03:00",
|
||||
"weight": 20,
|
||||
"reps": 12,
|
||||
"isDropset": false
|
||||
},
|
||||
{
|
||||
"id": "s4",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-10-16T18:50:00+03:00",
|
||||
"weight": 20,
|
||||
"reps": 12,
|
||||
"isDropset": false
|
||||
},
|
||||
{
|
||||
"id": "s5",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-10-16T19:00:00+03:00",
|
||||
"weight": 20,
|
||||
"reps": 10,
|
||||
"isDropset": false
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "e6",
|
||||
"name": "Разводка",
|
||||
"sets": [
|
||||
{
|
||||
"id": "s7",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-10-16T19:10:00+03:00",
|
||||
"weight": 8,
|
||||
"reps": 15,
|
||||
"isDropset": false
|
||||
},
|
||||
{
|
||||
"id": "s8",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-10-16T19:18:00+03:00",
|
||||
"weight": 8,
|
||||
"reps": 15,
|
||||
"isDropset": false
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"cardio": [],
|
||||
"setGroups": [],
|
||||
"notes": "",
|
||||
"synced": true
|
||||
},
|
||||
{
|
||||
"id": "w9",
|
||||
"client_id": null,
|
||||
"startTime": "2026-10-20T18:30:00+03:00",
|
||||
"endTime": "2026-10-20T19:30:00+03:00",
|
||||
"type": "грудь-руки",
|
||||
"exercises": [
|
||||
{
|
||||
"id": "e10",
|
||||
"name": "Жим гантелей на лавке 45",
|
||||
"sets": [
|
||||
{
|
||||
"id": "s11",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-10-20T18:40:00+03:00",
|
||||
"weight": 22,
|
||||
"reps": 10,
|
||||
"isDropset": false
|
||||
},
|
||||
{
|
||||
"id": "s12",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-10-20T18:52:00+03:00",
|
||||
"weight": 22,
|
||||
"reps": 10,
|
||||
"isDropset": false
|
||||
},
|
||||
{
|
||||
"id": "s13",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-10-20T19:04:00+03:00",
|
||||
"weight": 22,
|
||||
"reps": 8,
|
||||
"isDropset": false
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "e14",
|
||||
"name": "Молотки",
|
||||
"sets": [
|
||||
{
|
||||
"id": "s15",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-10-20T19:14:00+03:00",
|
||||
"weight": 10,
|
||||
"reps": 12,
|
||||
"isDropset": false
|
||||
},
|
||||
{
|
||||
"id": "s16",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-10-20T19:20:00+03:00",
|
||||
"weight": 10,
|
||||
"reps": 12,
|
||||
"isDropset": false
|
||||
},
|
||||
{
|
||||
"id": "s17",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-10-20T19:26:00+03:00",
|
||||
"weight": 10,
|
||||
"reps": 12,
|
||||
"isDropset": false
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"cardio": [],
|
||||
"setGroups": [],
|
||||
"notes": "",
|
||||
"synced": true
|
||||
},
|
||||
{
|
||||
"id": "w900",
|
||||
"client_id": null,
|
||||
"startTime": "2026-10-22T18:30:00+03:00",
|
||||
"endTime": "2026-10-22T19:30:00+03:00",
|
||||
"type": "грудь-руки",
|
||||
"exercises": [
|
||||
{
|
||||
"id": "e901",
|
||||
"name": "Жим штанги лёжа",
|
||||
"sets": [
|
||||
{
|
||||
"id": "s902",
|
||||
"weight": 20,
|
||||
"reps": 20,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-10-22T18:30:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s903",
|
||||
"weight": 50,
|
||||
"reps": 15,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-10-22T18:37:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s904",
|
||||
"weight": 70,
|
||||
"reps": 12,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-10-22T18:44:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s905",
|
||||
"weight": 80,
|
||||
"reps": 4,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-10-22T18:51:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s906",
|
||||
"weight": 90,
|
||||
"reps": 1,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-10-22T18:58:00+03:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"cardio": [],
|
||||
"setGroups": [],
|
||||
"notes": "",
|
||||
"synced": true
|
||||
},
|
||||
{
|
||||
"id": "w18",
|
||||
"client_id": null,
|
||||
"startTime": "2026-10-24T18:30:00+03:00",
|
||||
"endTime": "2026-10-24T19:30:00+03:00",
|
||||
"type": "грудь-руки",
|
||||
"exercises": [
|
||||
{
|
||||
"id": "e19",
|
||||
"name": "Жим гантелей на лавке 30",
|
||||
"sets": [
|
||||
{
|
||||
"id": "s20",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-10-24T18:40:00+03:00",
|
||||
"weight": 22,
|
||||
"reps": 12,
|
||||
"isDropset": false
|
||||
},
|
||||
{
|
||||
"id": "s21",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-10-24T18:52:00+03:00",
|
||||
"weight": 22,
|
||||
"reps": 10,
|
||||
"isDropset": false
|
||||
},
|
||||
{
|
||||
"id": "s22",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-10-24T19:04:00+03:00",
|
||||
"weight": 22,
|
||||
"reps": 10,
|
||||
"isDropset": false
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"cardio": [],
|
||||
"setGroups": [],
|
||||
"notes": "",
|
||||
"synced": true
|
||||
},
|
||||
{
|
||||
"id": "w23",
|
||||
"client_id": null,
|
||||
"startTime": "2026-10-29T18:30:00+03:00",
|
||||
"endTime": "2026-10-29T19:30:00+03:00",
|
||||
"type": "грудь-руки",
|
||||
"exercises": [
|
||||
{
|
||||
"id": "e24",
|
||||
"name": "Жим гантелей на лавке 45",
|
||||
"sets": [
|
||||
{
|
||||
"id": "s25",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-10-29T18:40:00+03:00",
|
||||
"weight": 24,
|
||||
"reps": 10,
|
||||
"isDropset": false
|
||||
},
|
||||
{
|
||||
"id": "s26",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-10-29T18:52:00+03:00",
|
||||
"weight": 24,
|
||||
"reps": 10,
|
||||
"isDropset": false
|
||||
},
|
||||
{
|
||||
"id": "s27",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-10-29T19:04:00+03:00",
|
||||
"weight": 24,
|
||||
"reps": 8,
|
||||
"isDropset": false
|
||||
},
|
||||
{
|
||||
"id": "s28",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-10-29T19:16:00+03:00",
|
||||
"weight": 24,
|
||||
"reps": 6,
|
||||
"isDropset": false
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"cardio": [],
|
||||
"setGroups": [],
|
||||
"notes": "",
|
||||
"synced": true
|
||||
},
|
||||
{
|
||||
"id": "w907",
|
||||
"client_id": null,
|
||||
"startTime": "2026-10-29T18:30:00+03:00",
|
||||
"endTime": "2026-10-29T19:30:00+03:00",
|
||||
"type": "грудь-руки",
|
||||
"exercises": [
|
||||
{
|
||||
"id": "e908",
|
||||
"name": "Жим штанги лёжа",
|
||||
"sets": [
|
||||
{
|
||||
"id": "s909",
|
||||
"weight": 20,
|
||||
"reps": 20,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-10-29T18:30:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s910",
|
||||
"weight": 50,
|
||||
"reps": 15,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-10-29T18:37:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s911",
|
||||
"weight": 70,
|
||||
"reps": 12,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-10-29T18:44:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s912",
|
||||
"weight": 80,
|
||||
"reps": 4,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-10-29T18:51:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s913",
|
||||
"weight": 90,
|
||||
"reps": 2,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-10-29T18:58:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s914",
|
||||
"weight": 100,
|
||||
"reps": 1,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-10-29T18:65:00+03:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"cardio": [],
|
||||
"setGroups": [],
|
||||
"notes": "новый максимум",
|
||||
"synced": true
|
||||
},
|
||||
{
|
||||
"id": "w29",
|
||||
"client_id": null,
|
||||
"startTime": "2026-11-03T18:30:00+03:00",
|
||||
"endTime": "2026-11-03T19:30:00+03:00",
|
||||
"type": "грудь-руки",
|
||||
"exercises": [
|
||||
{
|
||||
"id": "e30",
|
||||
"name": "Жим гантелей на лавке 30",
|
||||
"sets": [
|
||||
{
|
||||
"id": "s31",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-11-03T18:40:00+03:00",
|
||||
"weight": 24,
|
||||
"reps": 12,
|
||||
"isDropset": false
|
||||
},
|
||||
{
|
||||
"id": "s32",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-11-03T18:52:00+03:00",
|
||||
"weight": 24,
|
||||
"reps": 10,
|
||||
"isDropset": false
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "e33",
|
||||
"name": "Разводка",
|
||||
"sets": [
|
||||
{
|
||||
"id": "s34",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-11-03T19:02:00+03:00",
|
||||
"weight": 10,
|
||||
"reps": 12,
|
||||
"isDropset": false
|
||||
},
|
||||
{
|
||||
"id": "s35",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-11-03T19:10:00+03:00",
|
||||
"weight": 10,
|
||||
"reps": 12,
|
||||
"isDropset": false
|
||||
},
|
||||
{
|
||||
"id": "s36",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-11-03T19:18:00+03:00",
|
||||
"weight": 10,
|
||||
"reps": 12,
|
||||
"isDropset": false
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"cardio": [],
|
||||
"setGroups": [],
|
||||
"notes": "",
|
||||
"synced": true
|
||||
},
|
||||
{
|
||||
"id": "w915",
|
||||
"client_id": null,
|
||||
"startTime": "2026-11-05T18:30:00+03:00",
|
||||
"endTime": "2026-11-05T19:30:00+03:00",
|
||||
"type": "грудь-руки",
|
||||
"exercises": [
|
||||
{
|
||||
"id": "e916",
|
||||
"name": "Жим штанги лёжа",
|
||||
"sets": [
|
||||
{
|
||||
"id": "s917",
|
||||
"weight": 20,
|
||||
"reps": 20,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-11-05T18:30:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s918",
|
||||
"weight": 50,
|
||||
"reps": 15,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-11-05T18:37:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s919",
|
||||
"weight": 70,
|
||||
"reps": 12,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-11-05T18:44:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s920",
|
||||
"weight": 80,
|
||||
"reps": 4,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-11-05T18:51:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s921",
|
||||
"weight": 90,
|
||||
"reps": 2,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-11-05T18:58:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s922",
|
||||
"weight": 100,
|
||||
"reps": 1,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-11-05T18:65:00+03:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"cardio": [],
|
||||
"setGroups": [],
|
||||
"notes": "",
|
||||
"synced": true
|
||||
},
|
||||
{
|
||||
"id": "w37",
|
||||
"client_id": null,
|
||||
"startTime": "2026-11-08T18:30:00+03:00",
|
||||
"endTime": "2026-11-08T19:30:00+03:00",
|
||||
"type": "грудь-руки",
|
||||
"exercises": [
|
||||
{
|
||||
"id": "e38",
|
||||
"name": "Жим гантелей на лавке 45",
|
||||
"sets": [
|
||||
{
|
||||
"id": "s39",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-11-08T18:40:00+03:00",
|
||||
"weight": 26,
|
||||
"reps": 8,
|
||||
"isDropset": true,
|
||||
"subSets": [
|
||||
{
|
||||
"weight": 26,
|
||||
"reps": 8
|
||||
},
|
||||
{
|
||||
"weight": 20,
|
||||
"reps": 10
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "s40",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-11-08T19:00:00+03:00",
|
||||
"weight": 26,
|
||||
"reps": 8,
|
||||
"isDropset": false
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"cardio": [],
|
||||
"setGroups": [],
|
||||
"notes": "",
|
||||
"synced": true
|
||||
},
|
||||
{
|
||||
"id": "w923",
|
||||
"client_id": null,
|
||||
"startTime": "2026-11-12T18:30:00+03:00",
|
||||
"endTime": "2026-11-12T19:30:00+03:00",
|
||||
"type": "грудь-руки",
|
||||
"exercises": [
|
||||
{
|
||||
"id": "e924",
|
||||
"name": "Жим штанги лёжа",
|
||||
"sets": [
|
||||
{
|
||||
"id": "s925",
|
||||
"weight": 20,
|
||||
"reps": 20,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-11-12T18:30:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s926",
|
||||
"weight": 50,
|
||||
"reps": 15,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-11-12T18:37:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s927",
|
||||
"weight": 70,
|
||||
"reps": 12,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-11-12T18:44:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s928",
|
||||
"weight": 80,
|
||||
"reps": 4,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-11-12T18:51:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s929",
|
||||
"weight": 90,
|
||||
"reps": 2,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-11-12T18:58:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s930",
|
||||
"weight": 100,
|
||||
"reps": 1,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-11-12T18:65:00+03:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"cardio": [],
|
||||
"setGroups": [],
|
||||
"notes": "",
|
||||
"synced": true
|
||||
},
|
||||
{
|
||||
"id": "w41",
|
||||
"client_id": null,
|
||||
"startTime": "2026-11-13T18:30:00+03:00",
|
||||
"endTime": "2026-11-13T19:30:00+03:00",
|
||||
"type": "грудь-руки",
|
||||
"exercises": [
|
||||
{
|
||||
"id": "e43",
|
||||
"name": "Жим гантелей на лавке 45",
|
||||
"sets": [
|
||||
{
|
||||
"id": "s44",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-11-13T18:40:00+03:00",
|
||||
"weight": 28,
|
||||
"reps": 8,
|
||||
"isDropset": false
|
||||
},
|
||||
{
|
||||
"id": "s45",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-11-13T18:52:00+03:00",
|
||||
"weight": 28,
|
||||
"reps": 6,
|
||||
"isDropset": false
|
||||
},
|
||||
{
|
||||
"id": "s46",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-11-13T19:04:00+03:00",
|
||||
"weight": 26,
|
||||
"reps": 8,
|
||||
"isDropset": false
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"cardio": [
|
||||
{
|
||||
"id": "c42",
|
||||
"type": "бег",
|
||||
"purpose": "warmup",
|
||||
"duration": 10
|
||||
}
|
||||
],
|
||||
"setGroups": [],
|
||||
"notes": "",
|
||||
"synced": true
|
||||
},
|
||||
{
|
||||
"id": "w47",
|
||||
"client_id": null,
|
||||
"startTime": "2026-11-17T18:30:00+03:00",
|
||||
"endTime": "2026-11-17T19:30:00+03:00",
|
||||
"type": "грудь-руки",
|
||||
"exercises": [
|
||||
{
|
||||
"id": "e48",
|
||||
"name": "Жим гантелей на лавке 30",
|
||||
"sets": [
|
||||
{
|
||||
"id": "s49",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-11-17T18:40:00+03:00",
|
||||
"weight": 26,
|
||||
"reps": 10,
|
||||
"isDropset": false
|
||||
},
|
||||
{
|
||||
"id": "s50",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-11-17T18:52:00+03:00",
|
||||
"weight": 26,
|
||||
"reps": 10,
|
||||
"isDropset": false
|
||||
},
|
||||
{
|
||||
"id": "s51",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-11-17T19:04:00+03:00",
|
||||
"weight": 24,
|
||||
"reps": 12,
|
||||
"isDropset": false
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"cardio": [],
|
||||
"setGroups": [],
|
||||
"notes": "после паузы",
|
||||
"synced": true
|
||||
},
|
||||
{
|
||||
"id": "w52",
|
||||
"client_id": null,
|
||||
"startTime": "2026-11-19T18:30:00+03:00",
|
||||
"endTime": "2026-11-19T19:30:00+03:00",
|
||||
"type": "спина-плечи",
|
||||
"exercises": [
|
||||
{
|
||||
"id": "e53",
|
||||
"name": "Косичка",
|
||||
"sets": [
|
||||
{
|
||||
"id": "s54",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-11-19T18:40:00+03:00",
|
||||
"weight": 32,
|
||||
"reps": 15,
|
||||
"isDropset": false
|
||||
},
|
||||
{
|
||||
"id": "s55",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-11-19T18:50:00+03:00",
|
||||
"weight": 32,
|
||||
"reps": 15,
|
||||
"isDropset": false
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "e56",
|
||||
"name": "Разгибание на блоке",
|
||||
"sets": [
|
||||
{
|
||||
"id": "s57",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-11-19T18:42:00+03:00",
|
||||
"weight": 27,
|
||||
"reps": 15,
|
||||
"isDropset": false
|
||||
},
|
||||
{
|
||||
"id": "s58",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-11-19T18:52:00+03:00",
|
||||
"weight": 27,
|
||||
"reps": 15,
|
||||
"isDropset": false
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"cardio": [],
|
||||
"setGroups": [
|
||||
{
|
||||
"id": "g59",
|
||||
"name": "суперсет на спину",
|
||||
"exerciseIds": [
|
||||
"e53",
|
||||
"e56"
|
||||
]
|
||||
}
|
||||
],
|
||||
"notes": "",
|
||||
"synced": true
|
||||
},
|
||||
{
|
||||
"id": "w931",
|
||||
"client_id": null,
|
||||
"startTime": "2026-11-19T18:30:00+03:00",
|
||||
"endTime": "2026-11-19T19:30:00+03:00",
|
||||
"type": "грудь-руки",
|
||||
"exercises": [
|
||||
{
|
||||
"id": "e932",
|
||||
"name": "Жим штанги лёжа",
|
||||
"sets": [
|
||||
{
|
||||
"id": "s933",
|
||||
"weight": 20,
|
||||
"reps": 20,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-11-19T18:30:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s934",
|
||||
"weight": 50,
|
||||
"reps": 15,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-11-19T18:37:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s935",
|
||||
"weight": 70,
|
||||
"reps": 12,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-11-19T18:44:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s936",
|
||||
"weight": 90,
|
||||
"reps": 3,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-11-19T18:51:00+03:00"
|
||||
},
|
||||
{
|
||||
"id": "s937",
|
||||
"weight": 100,
|
||||
"reps": 2,
|
||||
"rating": 5,
|
||||
"isDropset": false,
|
||||
"timestamp": "2026-11-19T18:58:00+03:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"cardio": [],
|
||||
"setGroups": [],
|
||||
"notes": "меньше подходов — больше вес",
|
||||
"synced": true
|
||||
},
|
||||
{
|
||||
"id": "w60",
|
||||
"client_id": null,
|
||||
"startTime": "2026-11-20T18:30:00+03:00",
|
||||
"endTime": null,
|
||||
"type": "грудь-руки",
|
||||
"exercises": [
|
||||
{
|
||||
"id": "e61",
|
||||
"name": "Жим гантелей на лавке 45",
|
||||
"sets": [
|
||||
{
|
||||
"id": "s62",
|
||||
"rating": 5,
|
||||
"timestamp": "2026-11-20T09:10:00+03:00",
|
||||
"weight": 28,
|
||||
"reps": 10,
|
||||
"isDropset": false
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"cardio": [],
|
||||
"setGroups": [],
|
||||
"notes": "",
|
||||
"synced": false
|
||||
}
|
||||
],
|
||||
"exerciseRef": [
|
||||
{
|
||||
"id": "r63",
|
||||
"name": "Косичка",
|
||||
"workoutType": "спина-плечи",
|
||||
"group": ""
|
||||
},
|
||||
{
|
||||
"id": "r64",
|
||||
"name": "Разгибание на блоке",
|
||||
"workoutType": "спина-плечи",
|
||||
"group": ""
|
||||
},
|
||||
{
|
||||
"id": "r65",
|
||||
"name": "Жим гантелей на лавке 30",
|
||||
"workoutType": "грудь-руки",
|
||||
"group": "жим гантелей на лавке"
|
||||
},
|
||||
{
|
||||
"id": "r66",
|
||||
"name": "Жим гантелей на лавке 45",
|
||||
"workoutType": "грудь-руки",
|
||||
"group": "жим гантелей на лавке"
|
||||
},
|
||||
{
|
||||
"id": "r67",
|
||||
"name": "Молотки",
|
||||
"workoutType": "грудь-руки",
|
||||
"group": ""
|
||||
},
|
||||
{
|
||||
"id": "r68",
|
||||
"name": "Разводка",
|
||||
"workoutType": "грудь-руки",
|
||||
"group": ""
|
||||
},
|
||||
{
|
||||
"id": "r938",
|
||||
"name": "Жим штанги лёжа",
|
||||
"workoutType": "грудь-руки",
|
||||
"group": "жим лёжа"
|
||||
}
|
||||
],
|
||||
"bodyMetrics": [
|
||||
{
|
||||
"id": "b69",
|
||||
"client_id": null,
|
||||
"date": "2026-10-16",
|
||||
"values": [
|
||||
{
|
||||
"metric_type_id": 1,
|
||||
"value": 78.5
|
||||
},
|
||||
{
|
||||
"metric_type_id": 2,
|
||||
"value": 100
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "b70",
|
||||
"client_id": null,
|
||||
"date": "2026-11-01",
|
||||
"values": [
|
||||
{
|
||||
"metric_type_id": 1,
|
||||
"value": 77.8
|
||||
},
|
||||
{
|
||||
"metric_type_id": 2,
|
||||
"value": 101
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "b71",
|
||||
"client_id": null,
|
||||
"date": "2026-11-18",
|
||||
"values": [
|
||||
{
|
||||
"metric_type_id": 1,
|
||||
"value": 77.1
|
||||
},
|
||||
{
|
||||
"metric_type_id": 2,
|
||||
"value": 102
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"workoutTypes": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "грудь-руки"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"name": "спина-плечи"
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"name": "ноги"
|
||||
}
|
||||
],
|
||||
"metricTypes": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Вес",
|
||||
"unit": "кг"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"name": "Грудь",
|
||||
"unit": "см"
|
||||
}
|
||||
],
|
||||
"clients": [],
|
||||
"expandedWorkoutId": "w60",
|
||||
"expandedExerciseId": null,
|
||||
"nextId": 1000,
|
||||
"mode": "personal",
|
||||
"currentClientId": null
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
||||
<title>Gym Bro 😈 (демо)</title>
|
||||
<link rel="stylesheet" href="styles/main.css">
|
||||
<link rel="stylesheet" href="styles/components.css">
|
||||
<link rel="stylesheet" href="styles/workout.css">
|
||||
<link rel="stylesheet" href="styles/modal.css">
|
||||
<link rel="stylesheet" href="styles/settings.css">
|
||||
</head>
|
||||
<body>
|
||||
<header id="app-header"></header>
|
||||
<main id="app" class="container"></main>
|
||||
<div id="modal-container"></div>
|
||||
<script>
|
||||
// Локальный тест: API указывает на локальный бэкенд (иначе относительный /api упрётся в статику)
|
||||
localStorage.setItem('gym_api_base', 'http://127.0.0.1:8000');
|
||||
</script>
|
||||
<script src="demo-seed.js"></script>
|
||||
<script>
|
||||
// Демо-датасет v4 (прогрессия жима, пиратка штанги, суперсет, дропсет): пересев при смене версии
|
||||
if (localStorage.getItem('gym_demo_seed') !== 'v4') {
|
||||
localStorage.setItem('gym_tracker_v7_guest', JSON.stringify(window.GYM_DEMO_SEED));
|
||||
// если уже выполнен вход — обновить и пользовательский ключ (в него мигрировали старые данные)
|
||||
try {
|
||||
const u = JSON.parse(localStorage.getItem('gym_auth_user'));
|
||||
if (u && u.id) localStorage.setItem('gym_tracker_v7_user_' + u.id, JSON.stringify(window.GYM_DEMO_SEED));
|
||||
} catch (e) { /* гостевой режим */ }
|
||||
localStorage.setItem('gym_demo_seed', 'v4');
|
||||
}
|
||||
</script>
|
||||
<script type="module" src="js/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
||||
<title>Gym Tracker</title>
|
||||
<title>Gym Bro 😈</title>
|
||||
<link rel="stylesheet" href="styles/main.css">
|
||||
<link rel="stylesheet" href="styles/components.css">
|
||||
<link rel="stylesheet" href="styles/workout.css">
|
||||
|
||||
+52
-27
@@ -1,44 +1,69 @@
|
||||
// Базовый URL API. Если фронт и бэк на одном домене, можно использовать '' или '/api'
|
||||
const API_BASE = 'http://localhost:8000';
|
||||
// frontend/js/api.js
|
||||
|
||||
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 fetch(`${API_BASE}/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");
|
||||
}
|
||||
|
||||
+226
-48
@@ -1,65 +1,243 @@
|
||||
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 "./logic/group.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";
|
||||
import "./modals/group-modal.js";
|
||||
import "./modals/chart-modal.js";
|
||||
import "./modals/exercise-summary.js";
|
||||
|
||||
function renderHeader() {
|
||||
const modeLabel = state.mode === 'trainer' ? '👨🏫 Тренер' : '👤 Личный';
|
||||
document.getElementById('app-header').innerHTML = `
|
||||
<div>
|
||||
<h2>Gym Bro <span style="font-size:0.8rem; color:var(--text-secondary); font-weight:400;">(${modeLabel})</span></h2>
|
||||
<div id="sync-status" class="sync-status">● Локально</div>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<button class="icon-btn header-btn" onclick="App.toggleMode()" title="Сменить режим">🔄</button>
|
||||
<button class="icon-btn header-btn" onclick="ML.showBodyMetrics()" title="Личные замеры">📏</button>
|
||||
<button class="icon-btn header-btn" onclick="SettingsLogic.show()" title="Настройки">⚙️</button>
|
||||
<button class="btn btn-small btn-secondary" onclick="AppSync.sync()" title="Синхронизация">🔄</button>
|
||||
</div>
|
||||
`;
|
||||
const user = getActiveUser();
|
||||
const modeLabel = state.mode === "trainer" ? "👨🏫 Тренер" : "👤 Личный";
|
||||
|
||||
document.getElementById("app-header").innerHTML = `
|
||||
<div>
|
||||
<h2>
|
||||
Gym Bro 😈
|
||||
<span style="font-size:0.8rem; color:var(--text-secondary); font-weight:400;">
|
||||
(${modeLabel})
|
||||
</span>
|
||||
</h2>
|
||||
<div id="sync-status" class="sync-status">● Локально</div>
|
||||
${user ? `<div class="text-small text-muted">${user.display_name || user.username}</div>` : ""}
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<button class="icon-btn header-btn" onclick="App.showDashboard()" title="Статистика">📊</button>
|
||||
<button class="icon-btn header-btn" onclick="ML.showBodyMetrics()" title="Личные замеры">📏</button>
|
||||
<button class="icon-btn header-btn" onclick="SettingsLogic.show()" title="Настройки">⚙️</button>
|
||||
<button class="btn btn-small btn-secondary" onclick="AppSync.sync()" title="Синхронизация">🔄</button>
|
||||
<button class="icon-btn header-btn" onclick="AuthUI.logout()" title="Выйти">🚪</button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
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 = `
|
||||
<div>
|
||||
<h2>Gym Bro 😈</h2>
|
||||
<div class="sync-status">Требуется вход</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
app.innerHTML = `
|
||||
<div class="card auth-card">
|
||||
<h3>Вход / Регистрация</h3>
|
||||
|
||||
<div class="field-group">
|
||||
<label>Логин</label>
|
||||
<input type="text" id="auth-username" placeholder="username" autocomplete="username">
|
||||
</div>
|
||||
|
||||
<div class="field-group">
|
||||
<label>Пароль</label>
|
||||
<input type="password" id="auth-password" placeholder="••••••" autocomplete="current-password">
|
||||
</div>
|
||||
|
||||
<div class="field-group">
|
||||
<label>Роль при регистрации</label>
|
||||
<select id="auth-role">
|
||||
<option value="personal">Личный трекер</option>
|
||||
<option value="trainer">Тренер</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-secondary" onclick="AuthUI.doLogin()">Войти</button>
|
||||
<button class="btn" onclick="AuthUI.doRegister()">Регистрация</button>
|
||||
</div>
|
||||
|
||||
<div id="auth-error" class="auth-error">${message}</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
// frontend/js/auth.js
|
||||
|
||||
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);
|
||||
return raw ? JSON.parse(raw) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
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';
|
||||
}
|
||||
}
|
||||
|
||||
export function clearSession() {
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
localStorage.removeItem(USER_KEY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Защищённый Fetch wrapper.
|
||||
*/
|
||||
export async function apiFetch(path, options = {}) {
|
||||
const token = getToken();
|
||||
|
||||
// Критическая проверка: если токена нет, не идем на сервер
|
||||
if (!token) {
|
||||
console.warn(`⚠️ [AUTH] No token found for request: ${path}. Skipping.`);
|
||||
throw new Error("Not authenticated");
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(`${API_BASE}${path}`, {
|
||||
...options,
|
||||
headers,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(`❌ [NETWORK] Failed to reach ${path}:`, e);
|
||||
throw e;
|
||||
}
|
||||
|
||||
// Если 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",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await parseError(res, "Login failed");
|
||||
throw new Error(err);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
setSession(data.access_token, data.user);
|
||||
return data.user;
|
||||
}
|
||||
|
||||
export async function register(username, password, role = "personal") {
|
||||
const res = await fetch(`${API_BASE}/auth/register`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username, password, role }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await parseError(res, "Register failed");
|
||||
throw new Error(err);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
setSession(data.access_token, data.user);
|
||||
return data.user;
|
||||
}
|
||||
|
||||
export async function me() {
|
||||
// Используем apiFetch, чтобы автоматически добавить токен
|
||||
const res = await apiFetch("/auth/me");
|
||||
if (!res.ok) return null;
|
||||
return await res.json();
|
||||
}
|
||||
|
||||
async function parseError(res, fallbackMessage) {
|
||||
try {
|
||||
const err = await res.json();
|
||||
if (typeof err.detail === "string") return err.detail;
|
||||
if (Array.isArray(err.detail)) {
|
||||
return err.detail
|
||||
.map((d) => `${d.loc?.join(".") || ""}: ${d.msg || ""}`.trim())
|
||||
.join("; ");
|
||||
}
|
||||
return JSON.stringify(err.detail || err);
|
||||
} catch {
|
||||
return fallbackMessage || res.statusText;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
// frontend/js/config.js
|
||||
export const API_BASE =
|
||||
window.GYM_API_BASE ||
|
||||
localStorage.getItem("gym_api_base") ||
|
||||
"/api";
|
||||
@@ -38,7 +38,7 @@ export function addExercise(workoutId) {
|
||||
});
|
||||
}
|
||||
|
||||
export function addToRef(name, workoutType = '') {
|
||||
export function addToRef(name, workoutType = '', group = '') {
|
||||
const normalizedName = normalizeName(name);
|
||||
|
||||
const exists = state.exerciseRef.find(
|
||||
@@ -50,9 +50,11 @@ export function addToRef(name, workoutType = '') {
|
||||
id: genId(),
|
||||
name: String(name).trim(),
|
||||
workoutType,
|
||||
group: String(group || '').trim(),
|
||||
});
|
||||
} else if (!exists.workoutType && workoutType) {
|
||||
exists.workoutType = workoutType;
|
||||
} else {
|
||||
if (!exists.workoutType && workoutType) exists.workoutType = workoutType;
|
||||
if (!exists.group && group) exists.group = String(group).trim();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,10 +73,39 @@ export function deleteExercise(workoutId, exerciseId) {
|
||||
|
||||
w.exercises = w.exercises.filter(e => e.id !== exerciseId);
|
||||
|
||||
// Упражнение удалилось — чистим сеты, где оно состояло
|
||||
if (Array.isArray(w.setGroups)) {
|
||||
w.setGroups = w.setGroups
|
||||
.map(g => ({ ...g, exerciseIds: g.exerciseIds.filter(id => id !== exerciseId) }))
|
||||
.filter(g => g.exerciseIds.length >= 2);
|
||||
}
|
||||
|
||||
saveState();
|
||||
renderMainScreen();
|
||||
}
|
||||
|
||||
/**
|
||||
* Имена упражнений-вариантов в справочнике: та же «группа вариантов»
|
||||
* и тот же тип тренировки (пустой тип ни у одной из записей не препятствие).
|
||||
*/
|
||||
function refVariantNames(exerciseName) {
|
||||
const norm = normalizeName(exerciseName);
|
||||
const names = new Set([norm]);
|
||||
|
||||
const entry = state.exerciseRef.find(e => normalizeName(e.name) === norm);
|
||||
const group = String(entry?.group || '').trim().toLowerCase();
|
||||
if (!group) return names;
|
||||
|
||||
const entryType = String(entry.workoutType || '').trim().toLowerCase();
|
||||
for (const e of state.exerciseRef) {
|
||||
if (String(e.group || '').trim().toLowerCase() !== group) continue;
|
||||
const eType = String(e.workoutType || '').trim().toLowerCase();
|
||||
if (entryType && eType && entryType !== eType) continue;
|
||||
names.add(normalizeName(e.name));
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* Локальная история упражнения.
|
||||
*
|
||||
@@ -83,7 +114,7 @@ export function deleteExercise(workoutId, exerciseId) {
|
||||
* @param {string|number|null} excludeWorkoutId - чтобы не показывать текущую тренировку как "прошлую"
|
||||
*/
|
||||
export function getExerciseHistory(exerciseName, clientId = null, excludeWorkoutId = null) {
|
||||
const normalizedName = normalizeName(exerciseName);
|
||||
const variantNames = refVariantNames(exerciseName);
|
||||
const targetClient = normalizeClientId(clientId);
|
||||
|
||||
const history = [];
|
||||
@@ -102,12 +133,13 @@ export function getExerciseHistory(exerciseName, clientId = null, excludeWorkout
|
||||
|
||||
for (const ex of w.exercises || []) {
|
||||
if (
|
||||
normalizeName(ex.name) === normalizedName &&
|
||||
variantNames.has(normalizeName(ex.name)) &&
|
||||
Array.isArray(ex.sets) &&
|
||||
ex.sets.length > 0
|
||||
) {
|
||||
history.push({
|
||||
date: w.startTime,
|
||||
name: ex.name,
|
||||
sets: ex.sets,
|
||||
});
|
||||
}
|
||||
@@ -116,7 +148,150 @@ export function getExerciseHistory(exerciseName, clientId = null, excludeWorkout
|
||||
|
||||
history.sort((a, b) => new Date(b.date) - new Date(a.date));
|
||||
|
||||
return history.slice(0, 3);
|
||||
return history.slice(0, 5);
|
||||
}
|
||||
|
||||
/**
|
||||
* Полная история для графика (без среза в 5 записей): варианты из одной
|
||||
* группы складывают в одну прогрессию.
|
||||
*/
|
||||
export function getExerciseChart(exerciseName, clientId = null) {
|
||||
const variantNames = refVariantNames(exerciseName);
|
||||
const targetClient = normalizeClientId(clientId);
|
||||
const points = [];
|
||||
|
||||
for (const w of state.workouts) {
|
||||
if (!isSameClient(w.client_id, targetClient)) continue;
|
||||
if (!w.endTime) continue; // активная тренировка ещё не результат
|
||||
|
||||
for (const ex of w.exercises || []) {
|
||||
if (!variantNames.has(normalizeName(ex.name))) continue;
|
||||
let maxWeight = 0, totalReps = 0;
|
||||
const sets = []; // каждый подход отдельно: точка на графике
|
||||
for (const s of ex.sets || []) {
|
||||
const parts = s.isDropset && s.subSets?.length
|
||||
? s.subSets
|
||||
: [s];
|
||||
for (const p of parts) {
|
||||
const wgt = parseFloat(p.weight) || 0;
|
||||
const rps = parseInt(p.reps) || 0;
|
||||
if (wgt > 0 || rps > 0) sets.push({ weight: wgt, reps: rps });
|
||||
if (wgt > maxWeight) maxWeight = wgt;
|
||||
totalReps += rps;
|
||||
}
|
||||
}
|
||||
// повторы, взятые на максимальном весе — по ним видно прогресс при том же весе
|
||||
let topReps = 0;
|
||||
for (const st of sets) {
|
||||
if (st.weight === maxWeight && st.reps > topReps) topReps = st.reps;
|
||||
}
|
||||
if (maxWeight > 0 || totalReps > 0) {
|
||||
points.push({ date: w.startTime, name: ex.name, maxWeight, topReps, totalReps, sets });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
points.sort((a, b) => new Date(a.date) - new Date(b.date));
|
||||
return points;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сводка по упражнению (все завершённые тренировки): рекорды, средние за
|
||||
* тренировку и за всё время, синергичные упражнения (делались в тот же день)
|
||||
* и максимальный вес среди них. Варианты из одной группы считаются вместе.
|
||||
*/
|
||||
export function getExerciseSummary(exerciseName, clientId = null) {
|
||||
const variantNames = refVariantNames(exerciseName);
|
||||
const targetClient = normalizeClientId(clientId);
|
||||
|
||||
let best = null; // {weight, reps, date, variant}
|
||||
let maxSetsDay = null; // {count, date}
|
||||
let totalSets = 0, totalVolume = 0, totalReps = 0, totalRating = 0;
|
||||
let sumTopWeight = 0, days = 0;
|
||||
let from = null, to = null;
|
||||
const variantsSeen = new Set();
|
||||
const synergic = new Map(); // нормализованное имя -> {name, count, best}
|
||||
|
||||
for (const w of state.workouts) {
|
||||
if (!isSameClient(w.client_id, targetClient)) continue;
|
||||
if (!w.endTime) continue;
|
||||
const hits = (w.exercises || []).filter(ex => variantNames.has(normalizeName(ex.name)));
|
||||
if (!hits.length) continue;
|
||||
|
||||
days++;
|
||||
if (!from || new Date(w.startTime) < new Date(from)) from = w.startTime;
|
||||
if (!to || new Date(w.startTime) > new Date(to)) to = w.startTime;
|
||||
|
||||
let daySets = 0, dayVolume = 0, dayTop = 0;
|
||||
for (const ex of hits) {
|
||||
variantsSeen.add(ex.name);
|
||||
for (const s of ex.sets || []) {
|
||||
const parts = s.isDropset && s.subSets?.length ? s.subSets : [s];
|
||||
for (const p of parts) {
|
||||
const wgt = parseFloat(p.weight) || 0;
|
||||
const rps = parseInt(p.reps) || 0;
|
||||
if (!wgt && !rps) continue;
|
||||
daySets++; totalSets++;
|
||||
dayVolume += wgt * rps; totalVolume += wgt * rps;
|
||||
totalReps += rps;
|
||||
if ((parseFloat(s.rating) || 5) > 0) totalRating += (parseFloat(s.rating) || 5);
|
||||
if (wgt > dayTop) dayTop = wgt;
|
||||
if (!best || wgt > best.weight || (wgt === best.weight && rps > best.reps)) {
|
||||
best = { weight: wgt, reps: rps, date: w.startTime, variant: ex.name };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
sumTopWeight += dayTop;
|
||||
if (!maxSetsDay || daySets > maxSetsDay.count) maxSetsDay = { count: daySets, date: w.startTime };
|
||||
|
||||
// Синергичные: другие упражнения этих же тренировок
|
||||
for (const ex of w.exercises || []) {
|
||||
if (variantNames.has(normalizeName(ex.name))) continue;
|
||||
const key = normalizeName(ex.name);
|
||||
const rec = synergic.get(key) || { name: ex.name, count: 0, best: null };
|
||||
rec.count++;
|
||||
for (const s of ex.sets || []) {
|
||||
const parts = s.isDropset && s.subSets?.length ? s.subSets : [s];
|
||||
for (const p of parts) {
|
||||
const wgt = parseFloat(p.weight) || 0;
|
||||
const rps = parseInt(p.reps) || 0;
|
||||
if (!wgt) continue;
|
||||
if (!rec.best || wgt > rec.best.weight || (wgt === rec.best.weight && rps > rec.best.reps)) {
|
||||
rec.best = { weight: wgt, reps: rps, date: w.startTime };
|
||||
}
|
||||
}
|
||||
}
|
||||
synergic.set(key, rec);
|
||||
}
|
||||
}
|
||||
|
||||
const synergicList = Array.from(synergic.values())
|
||||
.sort((a, b) => b.count - a.count || (b.best?.weight || 0) - (a.best?.weight || 0));
|
||||
let synergicBest = null;
|
||||
for (const s of synergicList) {
|
||||
if (s.best && (!synergicBest || s.best.weight > synergicBest.weight)) {
|
||||
synergicBest = { ...s.best, name: s.name };
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
days,
|
||||
variants: Array.from(variantsSeen),
|
||||
period: from ? { from, to } : null,
|
||||
best,
|
||||
maxSetsDay,
|
||||
totals: { sets: totalSets, volume: totalVolume, reps: totalReps },
|
||||
avg: days ? {
|
||||
topWeight: Math.round(sumTopWeight / days * 10) / 10,
|
||||
sets: Math.round(totalSets / days * 10) / 10,
|
||||
volume: Math.round(totalVolume / days),
|
||||
reps: Math.round(totalReps / days),
|
||||
rating: Math.round(totalRating / totalSets * 10) / 10 || 0,
|
||||
} : null,
|
||||
synergic: synergicList,
|
||||
synergicBest,
|
||||
};
|
||||
}
|
||||
|
||||
window.EL = {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { state, saveState, genId } from '../state.js';
|
||||
import { renderMainScreen } from '../render/main-screen.js';
|
||||
import { showGroupDialog } from '../modals/group-modal.js';
|
||||
|
||||
/**
|
||||
* Открыть диалог создания (groupId = null) или редактирования состава сета.
|
||||
*/
|
||||
export function showGroupDialogFor(workoutId, groupId = null) {
|
||||
const w = state.workouts.find(x => x.id === workoutId);
|
||||
if (!w) return;
|
||||
|
||||
if ((w.exercises || []).length < 2) {
|
||||
alert('Для сета нужно минимум 2 упражнения');
|
||||
return;
|
||||
}
|
||||
|
||||
const group = groupId ? (w.setGroups || []).find(g => g.id === groupId) : null;
|
||||
|
||||
showGroupDialog(w, group, (data) => {
|
||||
if (!data) return;
|
||||
if (!Array.isArray(w.setGroups)) w.setGroups = [];
|
||||
|
||||
if (group) {
|
||||
group.name = data.name;
|
||||
group.exerciseIds = data.exerciseIds;
|
||||
} else {
|
||||
w.setGroups.push({ id: genId(), name: data.name, exerciseIds: data.exerciseIds });
|
||||
}
|
||||
|
||||
// Состав сета меняет саму тренировку — пусть уедет на сервер заново
|
||||
if (w.endTime) w.synced = false;
|
||||
|
||||
saveState();
|
||||
renderMainScreen();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Расформировать сет: упражнения и подходы остаются.
|
||||
*/
|
||||
export function removeGroup(workoutId, groupId) {
|
||||
if (!confirm('Разъединить сет? Упражнения и подходы останутся.')) return;
|
||||
const w = state.workouts.find(x => x.id === workoutId);
|
||||
if (!w) return;
|
||||
w.setGroups = (w.setGroups || []).filter(g => g.id !== groupId);
|
||||
if (w.endTime) w.synced = false;
|
||||
saveState();
|
||||
renderMainScreen();
|
||||
}
|
||||
|
||||
window.GL = { showGroupDialogFor, removeGroup };
|
||||
@@ -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
|
||||
};
|
||||
|
||||
@@ -22,7 +22,7 @@ export function addSet(workoutId, exerciseId) {
|
||||
w.id
|
||||
);
|
||||
|
||||
showSetDialog(lastSet, history, (setData) => {
|
||||
showSetDialog(null, history, (setData) => {
|
||||
if (!setData) return;
|
||||
|
||||
setData.id = genId();
|
||||
@@ -32,6 +32,9 @@ export function addSet(workoutId, exerciseId) {
|
||||
|
||||
saveState();
|
||||
renderMainScreen();
|
||||
}, {
|
||||
prefill: lastSet,
|
||||
historyLabel: ex.name,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -62,7 +65,7 @@ export function editSet(workoutId, exerciseId, setId) {
|
||||
|
||||
saveState();
|
||||
renderMainScreen();
|
||||
});
|
||||
}, { historyLabel: ex.name });
|
||||
}
|
||||
|
||||
export function deleteSet(workoutId, exerciseId, setId) {
|
||||
|
||||
+640
-336
File diff suppressed because it is too large
Load Diff
@@ -23,6 +23,7 @@ function _createWorkout(clientId) {
|
||||
type: '',
|
||||
exercises: [],
|
||||
cardio: [],
|
||||
setGroups: [],
|
||||
notes: '',
|
||||
synced: false,
|
||||
};
|
||||
@@ -42,6 +43,15 @@ export function finishWorkout(workoutId) {
|
||||
|
||||
export function deleteWorkout(workoutId) {
|
||||
if (!confirm('Удалить тренировку полностью?')) return;
|
||||
|
||||
// Надгробие: без него bootstrap вернёт удалённую тренировку с сервера
|
||||
const w = state.workouts.find(x => x.id === workoutId);
|
||||
const sid = w && (w.sync_id || w.id);
|
||||
if (sid) {
|
||||
if (!Array.isArray(state.deletedWorkouts)) state.deletedWorkouts = [];
|
||||
if (!state.deletedWorkouts.includes(sid)) state.deletedWorkouts.push(sid);
|
||||
}
|
||||
|
||||
state.workouts = state.workouts.filter(w => w.id !== workoutId);
|
||||
saveState();
|
||||
renderMainScreen();
|
||||
|
||||
@@ -1,19 +1,30 @@
|
||||
import { showModal, closeModal, stepperHtml } from './modal-base.js';
|
||||
import { state } from '../state.js';
|
||||
|
||||
let _cb = null;
|
||||
|
||||
export function showCardioDialog(existing, callback) {
|
||||
_cb = callback;
|
||||
const e = existing || {};
|
||||
const types = [
|
||||
['вело', '🚴 Вело'],
|
||||
['ходьба', '🚶 Ходьба'],
|
||||
['бег', '🏃 Бег'],
|
||||
['эллипс', '⚡ Эллипс'],
|
||||
['гребля', '🚣 Гребля'],
|
||||
];
|
||||
// Популярные типы — выше: считаем, сколько раз каждый уже использовался
|
||||
const counts = {};
|
||||
state.workouts.forEach(w => (w.cardio || []).forEach(c => {
|
||||
counts[c.type] = (counts[c.type] || 0) + 1;
|
||||
}));
|
||||
const orderedTypes = [...types].sort((a, b) => (counts[b[0]] || 0) - (counts[a[0]] || 0));
|
||||
|
||||
showModal(`<div class="modal-content">
|
||||
<h3 class="modal-title">${existing ? 'Редактировать' : 'Новое'} кардио</h3>
|
||||
<div class="field-row">
|
||||
<div class="field-group"><label>Тип</label><select id="m-ct">
|
||||
<option value="вело" ${e.type==='вело'?'selected':''}>🚴 Вело</option>
|
||||
<option value="ходьба" ${e.type==='ходьба'?'selected':''}>🚶 Ходьба</option>
|
||||
<option value="бег" ${e.type==='бег'?'selected':''}>🏃 Бег</option>
|
||||
<option value="эллипс" ${e.type==='эллипс'?'selected':''}>⚡ Эллипс</option>
|
||||
<option value="гребля" ${e.type==='гребля'?'selected':''}>🚣 Гребля</option>
|
||||
${orderedTypes.map(([v, label]) => `<option value="${v}" ${e.type === v ? 'selected' : ''}>${label}</option>`).join('')}
|
||||
</select></div>
|
||||
<div class="field-group"><label>Назначение</label><select id="m-cp">
|
||||
<option value="warmup" ${e.purpose==='warmup'?'selected':''}>🔥 Разминка</option>
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import { state } from '../state.js';
|
||||
import { escapeHtml } from '../utils.js';
|
||||
import { showModal, closeModal } from './modal-base.js';
|
||||
import { getExerciseChart } from '../logic/exercise.js';
|
||||
|
||||
/**
|
||||
* График прогрессии упражнения. Главный элемент — рабочий максимум тренировки:
|
||||
* вершина «вес × повторения» (например 100×2). Зелёный — лучше прошлого раза
|
||||
* (вес больше, или тот же вес и больше повторов), красный — откат, фиолетовый —
|
||||
* так же. Остальные подходы — тусклые точки (размер = повторения). Варианты из
|
||||
* одной группы справочника — на одной линии.
|
||||
*/
|
||||
export function showChartDialog(exerciseName, clientId = null) {
|
||||
const points = getExerciseChart(exerciseName, clientId);
|
||||
|
||||
if (points.length === 0) {
|
||||
showModal(`
|
||||
<div class="modal-content">
|
||||
<div class="modal-header"><span class="modal-title">${escapeHtml(exerciseName)}</span><button class="btn-icon" onclick="closeModal()">✕</button></div>
|
||||
<div class="history-hint" style="margin:8px 0">Нет завершённых тренировок с этим упражнением — график появится после первых результатов.</div>
|
||||
</div>
|
||||
`);
|
||||
return;
|
||||
}
|
||||
|
||||
const byWeight = points.some(p => p.maxWeight > 0);
|
||||
const val = s => byWeight ? s.weight : s.reps; // что откладывать по вертикали
|
||||
const dayTop = p => byWeight ? p.maxWeight : Math.max(...p.sets.map(val), 0);
|
||||
const dayTopReps = p => byWeight ? p.topReps : 0;
|
||||
|
||||
// Цель из настроек: «Сила» — по максимальному весу (тот же вес и больше
|
||||
// повторов — тоже прогресс, но суммарный объём не учитывается);
|
||||
// «Выносливость» — по суммарному объёму вес × повторы. По умолчанию — сила.
|
||||
const goal = state.goal === 'endurance' ? 'endurance' : 'strength';
|
||||
const volume = p => p.sets.reduce((a, s) => a + (s.weight || 0) * (s.reps || 0), 0);
|
||||
|
||||
const cls = i => {
|
||||
if (i === 0) return 'chart-flat';
|
||||
if (goal === 'endurance') {
|
||||
const cur = volume(points[i]), prev = volume(points[i - 1]);
|
||||
if (cur > prev) return 'chart-up';
|
||||
if (cur < prev) return 'chart-down';
|
||||
return 'chart-flat';
|
||||
}
|
||||
const cur = dayTop(points[i]), prev = dayTop(points[i - 1]);
|
||||
if (cur > prev) return 'chart-up';
|
||||
if (cur < prev) return 'chart-down';
|
||||
// Тот же максимальный вес: больше повторов — лучше, меньше — хуже
|
||||
if (dayTopReps(points[i]) > dayTopReps(points[i - 1])) return 'chart-up';
|
||||
if (dayTopReps(points[i]) < dayTopReps(points[i - 1])) return 'chart-down';
|
||||
return 'chart-flat';
|
||||
};
|
||||
const classes = points.map((_, i) => cls(i));
|
||||
const topLabel = p => byWeight ? `${dayTop(p)}×${dayTopReps(p)}` : `${dayTop(p)}`;
|
||||
|
||||
// Полноэкранный график: размер под текущий вьюпорт, а не фиксированные 320px
|
||||
const W = Math.max(320, (window.innerWidth || 900) - 12);
|
||||
const H = Math.min(640, Math.max(300, Math.round((window.innerHeight || 700) * 0.52)));
|
||||
const padL = 46, padR = 34, padT = 36, padB = 58;
|
||||
const n = points.length;
|
||||
const x = i => n === 1 ? (padL + W - padR) / 2
|
||||
: padL + (W - padL - padR) * i / (n - 1);
|
||||
|
||||
const allVals = points.flatMap(p => p.sets.map(val)).concat(points.map(dayTop));
|
||||
const vMax = Math.max(...allVals), vMin = Math.min(0, ...allVals);
|
||||
const vTop = vMax + (vMax - vMin) * 0.1 || vMax + 1;
|
||||
const y = v => padT + (H - padT - padB) * (1 - (v - vMin) / (vTop - vMin || 1));
|
||||
|
||||
const maxReps = Math.max(1, ...points.flatMap(p => p.sets.map(s => s.reps || 0)));
|
||||
const rOf = s => 2.6 + 3.6 * Math.min(1, (s.reps || 0) / maxReps);
|
||||
|
||||
// Все подходы — тусклые фоновые точки, слегка раскиданные вокруг дня
|
||||
const dots = [];
|
||||
points.forEach((p, i) => {
|
||||
const spread = p.sets.length > 1 ? Math.min(20, (W - padL - padR) / (2 * n)) : 0;
|
||||
p.sets.forEach((s, k) => {
|
||||
if (byWeight && s.weight === p.maxWeight) return; // максимум покажет вершина линии
|
||||
const dx = p.sets.length > 1 ? -spread + 2 * spread * k / (p.sets.length - 1) : 0;
|
||||
dots.push(
|
||||
`<circle class="chart-set" cx="${(x(i) + dx).toFixed(1)}" cy="${y(val(s)).toFixed(1)}" r="${rOf(s).toFixed(1)}">` +
|
||||
`<title>${new Date(p.date).toLocaleDateString('ru-RU')} · подход: ` +
|
||||
(byWeight ? `${s.weight} кг × ${s.reps}` : `${s.reps} повт.`) + `</title></circle>`
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// Линия рабочего максимума: каждый отрезок окрашен по прогрессу конца отрезка
|
||||
const segs = [];
|
||||
for (let i = 1; i < n; i++) {
|
||||
segs.push(`<line x1="${x(i - 1).toFixed(1)}" y1="${y(dayTop(points[i - 1])).toFixed(1)}" ` +
|
||||
`x2="${x(i).toFixed(1)}" y2="${y(dayTop(points[i])).toFixed(1)}" class="chart-seg ${classes[i]}"/>`);
|
||||
}
|
||||
// Вершины: крупная точка + подпись «вес×повт.» с цветом прогресса
|
||||
const showLabel = i => n <= 12 || i >= n - 6 || classes[i] !== 'chart-flat';
|
||||
const verts = points.map((p, i) =>
|
||||
`<circle class="chart-vert ${classes[i]}" cx="${x(i).toFixed(1)}" cy="${y(dayTop(p)).toFixed(1)}" r="6.5"></circle>` +
|
||||
(showLabel(i)
|
||||
? `<text x="${x(i).toFixed(1)}" y="${(y(dayTop(p)) - 11).toFixed(1)}" text-anchor="middle" class="chart-label chart-vert-label ${classes[i]}">${topLabel(p)}</text>`
|
||||
: '')
|
||||
).join('');
|
||||
|
||||
const fmt = d => new Date(d).toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit' });
|
||||
|
||||
const counts = points.map((p, i) =>
|
||||
(n <= 16 || i % 2 === 0)
|
||||
? `<text x="${x(i).toFixed(1)}" y="${H - 20}" text-anchor="middle" class="chart-label chart-count">×${p.sets.length}</text>` +
|
||||
`<text x="${x(i).toFixed(1)}" y="${H - 4}" text-anchor="middle" class="chart-label chart-date-lab">${fmt(p.date)}</text>`
|
||||
: ''
|
||||
).join('');
|
||||
|
||||
showModal(`
|
||||
<div class="modal-content modal-fullscreen">
|
||||
<div class="modal-header"><span class="modal-title">📈 ${escapeHtml(exerciseName)}</span></div>
|
||||
<div class="chart-legend-big">
|
||||
<span class="lg-line">— линия: максимум</span>
|
||||
<span class="lg-up">зелёный: прогресс</span>
|
||||
<span class="lg-down">красный: откат</span>
|
||||
<button class="lg-info" onclick="CM.toggleChartHint(this)">ⓘ</button>
|
||||
</div>
|
||||
<div class="chart-hint" style="display:none">${
|
||||
goal === 'endurance'
|
||||
? 'Прогресс и откат считаются по <b>суммарному объёму</b> (вес × повторы за тренировку). Цель: «🏃 Выносливость» — сменить на «💪 Сила» можно в ⚙️ Настройках. Тусклые точки — остальные подходы, ×N под датой — их число.'
|
||||
: 'Прогресс — <b>максимальный вес</b> за тренировку вырос (или тот же вес и больше повторов), откат — упал. Суммарный объём за тренировку не учитывается. Цель: «💪 Сила» — сменить на «🏃 Выносливость» можно в ⚙️ Настройках. Тусклые точки — остальные подходы, ×N под датой — их число.'
|
||||
}</div>
|
||||
<svg class="chart-svg" viewBox="0 0 ${W} ${H}">
|
||||
<line x1="${padL}" y1="${y(vMin).toFixed(1)}" x2="${W - padR}" y2="${y(vMin).toFixed(1)}" class="chart-axis"/>
|
||||
<line x1="${padL}" y1="${y(vMax).toFixed(1)}" x2="${W - padR}" y2="${y(vMax).toFixed(1)}" class="chart-axis"/>
|
||||
<text x="${padL - 6}" y="${(y(vMax) + 4).toFixed(1)}" text-anchor="end" class="chart-label">${vMax}</text>
|
||||
<text x="${padL - 6}" y="${(y(vMin) + 4).toFixed(1)}" text-anchor="end" class="chart-label">${vMin}</text>
|
||||
${dots.join('')}
|
||||
${segs.join('')}
|
||||
${verts}
|
||||
${counts}
|
||||
</svg>
|
||||
<div class="chart-list">${points.slice(-5).reverse().map((p, k) => {
|
||||
const i = points.length - 1 - k;
|
||||
return `<div class="chart-row"><span class="chart-date">${new Date(p.date).toLocaleDateString('ru-RU')}</span>` +
|
||||
`<span class="chart-val ${classes[i]}"><b>${topLabel(p)}</b></span>` +
|
||||
`<span class="chart-sets">${p.sets.map(s => byWeight ? s.weight + '×' + s.reps : s.reps).join(' ')}` +
|
||||
` · <span class="chart-count-num">${p.sets.length}</span> подх.</span></div>`;
|
||||
}).join('')}</div>
|
||||
<div class="modal-actions-row">
|
||||
<button class="btn btn-secondary big-touch" data-ex="${escapeHtml(exerciseName)}"
|
||||
onclick="EM.showSummaryFromBtn(this)">📋 Сводка</button>
|
||||
<button class="btn btn-primary big-touch" onclick="ModalBase.closeModal()">✕ Закрыть</button>
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
}
|
||||
|
||||
// Пояснение к легенде — по тапу на ⓘ (на телефоне наведение не работает)
|
||||
export function toggleChartHint(btn) {
|
||||
const hint = btn.closest('.chart-legend-big')?.nextElementSibling;
|
||||
if (hint) hint.style.display = hint.style.display === 'none' ? 'block' : 'none';
|
||||
}
|
||||
|
||||
// Клик с кнопки в карточке: имя берём из data-атрибута (без экранирования в JS-строке)
|
||||
export function showChartFromBtn(btn) {
|
||||
const name = btn.dataset.ex;
|
||||
const w = state.workouts.find(w => (w.exercises || []).some(e => e.name === name));
|
||||
showChartDialog(name, w ? w.client_id : null);
|
||||
}
|
||||
|
||||
window.CM = { showChartDialog, showChartFromBtn, toggleChartHint };
|
||||
@@ -1,28 +1,41 @@
|
||||
import { showModal, closeModal } from './modal-base.js';
|
||||
import { state } from '../state.js';
|
||||
import { escapeHtml } from '../utils.js';
|
||||
|
||||
let _cb = null;
|
||||
|
||||
export function showEditExerciseDialog(exercise, callback) {
|
||||
_cb = callback;
|
||||
const groups = [...new Set(state.exerciseRef.map(e => e.group).filter(Boolean))].sort();
|
||||
|
||||
showModal(`
|
||||
<div class="modal-content">
|
||||
<h3 class="modal-title">Редактировать упражнение</h3>
|
||||
<div class="field-group">
|
||||
<label>Название</label>
|
||||
<input type="text" id="m-edit-ex-name" value="${exercise.name}">
|
||||
<input type="text" id="m-edit-ex-name" value="${escapeHtml(exercise.name)}">
|
||||
</div>
|
||||
<div class="field-group">
|
||||
<label>Тип тренировки</label>
|
||||
<select id="m-edit-ex-type">
|
||||
<option value="">тип не указан</option>
|
||||
<option value="грудь-руки" ${exercise.workoutType==='грудь-руки'?'selected':''}>грудь-руки</option>
|
||||
<option value="ноги" ${exercise.workoutType==='ноги'?'selected':''}>ноги</option>
|
||||
<option value="спина-плечи" ${exercise.workoutType==='спина-плечи'?'selected':''}>спина-плечи</option>
|
||||
<option value="круговая" ${exercise.workoutType==='круговая'?'selected':''}>круговая</option>
|
||||
<option value="силовая" ${exercise.workoutType==='силовая'?'selected':''}>силовая</option>
|
||||
<option value="многоповторная" ${exercise.workoutType==='многоповторная'?'selected':''}>многоповторная</option>
|
||||
${state.workoutTypes.map(wt =>
|
||||
`<option value="${escapeHtml(wt.name)}" ${exercise.workoutType === wt.name ? 'selected' : ''}>${escapeHtml(wt.name)}</option>`
|
||||
).join('')}
|
||||
</select>
|
||||
</div>
|
||||
<div class="field-group">
|
||||
<label>Группа вариантов (общая статистика)</label>
|
||||
<input type="text" id="m-edit-ex-group" list="m-edit-groups-list"
|
||||
value="${escapeHtml(exercise.group || '')}"
|
||||
placeholder="Например: жим гантелей на лавке">
|
||||
<datalist id="m-edit-groups-list">${
|
||||
groups.map(g => `<option value="${escapeHtml(g)}"></option>`).join('')
|
||||
}</datalist>
|
||||
<p class="text-muted text-small" style="margin-top:4px;">
|
||||
Упражнения с одинаковой группой показывают историю друг друга
|
||||
</p>
|
||||
</div>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-secondary" onclick="ModalBase.close()">Отмена</button>
|
||||
<button class="btn btn-success" onclick="EditExModal.submit()">Сохранить</button>
|
||||
@@ -34,9 +47,10 @@ export function showEditExerciseDialog(exercise, callback) {
|
||||
export function submit() {
|
||||
const name = document.getElementById('m-edit-ex-name').value.trim();
|
||||
const type = document.getElementById('m-edit-ex-type').value;
|
||||
const group = document.getElementById('m-edit-ex-group').value.trim();
|
||||
if (!name) { alert('Название не может быть пустым'); return; }
|
||||
closeModal();
|
||||
if (_cb) _cb({ name, workoutType: type });
|
||||
if (_cb) _cb({ name, workoutType: type, group });
|
||||
}
|
||||
|
||||
window.EditExModal = { submit };
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { state } from '../state.js';
|
||||
import { escapeHtml } from '../utils.js';
|
||||
import { showModal, closeModal } from './modal-base.js';
|
||||
import { getExerciseSummary } from '../logic/exercise.js';
|
||||
import { showChartDialog } from './chart-modal.js';
|
||||
|
||||
const fmtDate = d => new Date(d).toLocaleDateString('ru-RU');
|
||||
|
||||
/**
|
||||
* Страница-сводка по упражнению: рекорды, средние за тренировку и за всё
|
||||
* время, синергичные упражнения и максимальный вес среди них.
|
||||
*/
|
||||
export function showExerciseSummary(exerciseName, clientId = null) {
|
||||
const s = getExerciseSummary(exerciseName, clientId);
|
||||
|
||||
if (!s.days) {
|
||||
showModal(`
|
||||
<div class="modal-content">
|
||||
<div class="modal-header"><span class="modal-title">${escapeHtml(exerciseName)}</span><button class="btn-icon" onclick="closeModal()">✕</button></div>
|
||||
<div class="history-hint" style="margin:8px 0">Нет завершённых тренировок с этим упражнением.</div>
|
||||
</div>
|
||||
`);
|
||||
return;
|
||||
}
|
||||
|
||||
const card = (label, value, sub = '') =>
|
||||
`<div class="sum-card"><div class="sum-value">${value}</div><div class="sum-label">${label}</div>` +
|
||||
(sub ? `<div class="sum-sub">${sub}</div>` : '') + `</div>`;
|
||||
|
||||
const synergRows = s.synergic.slice(0, 8).map(x =>
|
||||
`<div class="chart-row"><span class="chart-date">${x.count} трен.</span>` +
|
||||
`<span class="chart-name">${escapeHtml(x.name)}</span>` +
|
||||
`<span class="chart-val">${x.best ? x.best.weight + '×' + x.best.reps : '—'}</span></div>`
|
||||
).join('') || '<div class="history-hint">Пока нет данных по соседним упражнениям.</div>';
|
||||
|
||||
showModal(`
|
||||
<div class="modal-content modal-fullscreen">
|
||||
<div class="modal-header">
|
||||
<span class="modal-title">📋 ${escapeHtml(exerciseName)}</span>
|
||||
</div>
|
||||
<div class="chart-sub">
|
||||
${s.days} тренир.` +
|
||||
(s.period ? ` · ${fmtDate(s.period.from)} — ${fmtDate(s.period.to)}` : '') +
|
||||
(s.variants.length > 1 ? ` · варианты: ${s.variants.map(escapeHtml).join(', ')}` : '') + `
|
||||
</div>
|
||||
|
||||
<div class="sum-grid">
|
||||
${card('рабочий максимум', s.best ? `${s.best.weight}×${s.best.reps}` : '—',
|
||||
s.best ? `${fmtDate(s.best.date)} · ${escapeHtml(s.best.variant)}` : '')}
|
||||
${card('максимум подходов за тренировку', s.maxSetsDay ? `×${s.maxSetsDay.count}` : '—',
|
||||
s.maxSetsDay ? fmtDate(s.maxSetsDay.date) : '')}
|
||||
${card('средний рабочий вес', s.avg ? `${s.avg.topWeight} кг` : '—', 'за тренировку')}
|
||||
${card('средне подходов', s.avg ? `×${s.avg.sets}` : '—', `и ${s.avg ? s.avg.reps : 0} повт. за тренировку`)}
|
||||
${card('средний объём', s.avg ? `${s.avg.volume} кг` : '—', 'за тренировку')}
|
||||
${card('за всё время', `${s.totals.volume} кг`, `${s.totals.sets} подх. · ${s.totals.reps} повт.` +
|
||||
(s.avg && s.avg.rating ? ` · средняя оценка ${s.avg.rating}` : ''))}
|
||||
</div>
|
||||
|
||||
<h4 style="margin:12px 0 4px">🤝 Синергичные упражнения <span class="text-muted text-small">(делались в тот же день)</span></h4>
|
||||
<div class="chart-list">${synergRows}</div>
|
||||
${s.synergicBest ? `<div class="chart-sub" style="margin-top:6px">Максимум среди синергичных: <b>${escapeHtml(s.synergicBest.name)} ${s.synergicBest.weight}×${s.synergicBest.reps}</b> (${fmtDate(s.synergicBest.date)})</div>` : ''}
|
||||
|
||||
<div class="modal-actions-row">
|
||||
<button class="btn btn-secondary big-touch" data-ex="${escapeHtml(exerciseName)}"
|
||||
onclick="EM.showChartFrom(this)">📈 График</button>
|
||||
<button class="btn btn-primary big-touch" onclick="ModalBase.closeModal()">✕ Закрыть</button>
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
}
|
||||
|
||||
// Кнопка «📋 Сводка» в графике: имя из data-атрибута
|
||||
export function showSummaryFromBtn(btn) {
|
||||
const name = btn.dataset.ex;
|
||||
const w = state.workouts.find(w => (w.exercises || []).some(e => e.name === name));
|
||||
showExerciseSummary(name, w ? w.client_id : null);
|
||||
}
|
||||
|
||||
window.EM = {
|
||||
showSummaryDialog: (name) => showExerciseSummary(name),
|
||||
showSummaryFromBtn,
|
||||
showChartFrom: (btn) => showChartDialog(btn.dataset.ex),
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
import { showModal, closeModal } from './modal-base.js';
|
||||
import { escapeHtml } from '../utils.js';
|
||||
|
||||
let _cb = null;
|
||||
|
||||
/**
|
||||
* Диалог создания/редактирования сета (суперсета).
|
||||
* @param {object} workout - тренировка
|
||||
* @param {object|null} group - существующая группа {id, name, exerciseIds} или null для новой
|
||||
* @param {(data:{name:string, exerciseIds:string[]}|null)=>void} callback
|
||||
*/
|
||||
export function showGroupDialog(workout, group, callback) {
|
||||
_cb = callback;
|
||||
const memberIds = group ? [...group.exerciseIds] : [];
|
||||
|
||||
showModal(`<div class="modal-content">
|
||||
<h3 class="modal-title">${group ? '✎ Состав сета' : '🔗 Новый сет (суперсет)'}</h3>
|
||||
<p class="text-muted text-small" style="margin-bottom:12px;">
|
||||
Отметьте упражнения, подходы которых выполняются по очереди:
|
||||
1-й подход каждого → отдых → 2-й подход каждого → …
|
||||
</p>
|
||||
<div class="field-group">
|
||||
<label>Название</label>
|
||||
<input type="text" id="m-group-name" value="${escapeHtml(group?.name || '')}"
|
||||
placeholder="Например: суперсет на спину">
|
||||
</div>
|
||||
<div class="field-group">
|
||||
<label>Упражнения (минимум 2)</label>
|
||||
<div id="m-group-list" class="group-check-list">
|
||||
${(workout.exercises || []).map(ex => `
|
||||
<label class="group-check">
|
||||
<input type="checkbox" value="${ex.id}" ${memberIds.includes(ex.id) ? 'checked' : ''}>
|
||||
<span>${escapeHtml(ex.name)}</span>
|
||||
</label>`).join('')}
|
||||
</div>
|
||||
</div>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-secondary" onclick="ModalBase.close()">Отмена</button>
|
||||
<button class="btn btn-success" onclick="GroupModal.submit()">Сохранить</button>
|
||||
</div>
|
||||
</div>`);
|
||||
}
|
||||
|
||||
export function submit() {
|
||||
const name = document.getElementById('m-group-name').value.trim();
|
||||
const ids = [...document.querySelectorAll('#m-group-list input:checked')].map(i => i.value);
|
||||
if (ids.length < 2) {
|
||||
alert('Выберите минимум 2 упражнения');
|
||||
return;
|
||||
}
|
||||
closeModal();
|
||||
_cb?.({ name: name || 'Сет', exerciseIds: ids });
|
||||
}
|
||||
|
||||
window.GroupModal = { submit };
|
||||
@@ -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(`<div class="modal-content">
|
||||
<h3 class="modal-title">📏 Замеры ${isEdit ? '(ред.)' : ''}</h3>
|
||||
<div class="field-group"><label>📅 Дата</label><input type="datetime-local" id="m-md" value="${dateVal}"></div>
|
||||
<div class="field-row">
|
||||
<div class="field-group"><label>⚖️ Вес</label>${stepperHtml('m-mw', src.weight??'', 0.1, 'кг')}</div>
|
||||
<div class="field-group"><label>📏 Грудь</label>${stepperHtml('m-mc', src.chest??'', 1, 'см', 'numeric')}</div></div>
|
||||
<div class="field-row">
|
||||
<div class="field-group"><label>📏 Талия</label>${stepperHtml('m-mwa', src.waist??'', 1, 'см', 'numeric')}</div>
|
||||
<div class="field-group"><label>📏 Бёдра</label>${stepperHtml('m-mh', src.hips??'', 1, 'см', 'numeric')}</div></div>
|
||||
<div class="field-row">
|
||||
<div class="field-group"><label>💪 Руки</label>${stepperHtml('m-ma', src.arms??'', 0.5, 'см')}</div>
|
||||
<div class="field-group"><label>🦵 Ноги</label>${stepperHtml('m-ml', src.legs??'', 0.5, 'см')}</div></div>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-secondary" onclick="ModalBase.closeOnBg({target:document.querySelector('.modal-overlay')})">Отмена</button>
|
||||
<button class="btn btn-success" onclick="MetricsModal.submit(${isEdit})">Сохранить</button></div>
|
||||
</div>`);
|
||||
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(`
|
||||
<div class="modal-content">
|
||||
<h3 class="modal-title">📏 Нет типов замеров</h3>
|
||||
<p class="text-muted">
|
||||
В настройках не добавлено ни одного типа замера.<br>
|
||||
Перейдите в ⚙️ Настройки → 📏 Типы замеров и добавьте нужные метрики (Вес, Талия, Бицепс...).
|
||||
</p>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-secondary" onclick="ModalBase.closeModal()">Закрыть</button>
|
||||
<button class="btn" onclick="ModalBase.closeModal(); SettingsLogic.show();">⚙️ В настройки</button>
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
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 `
|
||||
<div class="field-group">
|
||||
<label>${mt.name} <span class="text-muted">(${mt.unit})</span></label>
|
||||
${stepperHtml(id, value, step, mt.unit || '', 'decimal')}
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
showModal(`
|
||||
<div class="modal-content">
|
||||
<h3 class="modal-title">📏 Замеры ${_isEdit ? '(ред.)' : ''}</h3>
|
||||
|
||||
<div class="field-group">
|
||||
<label>📅 Дата</label>
|
||||
<input type="datetime-local" id="m-metric-date" value="${dateValue}">
|
||||
</div>
|
||||
|
||||
<!-- Динамические поля здесь -->
|
||||
<div style="max-height: 50vh; overflow-y: auto;">
|
||||
${fieldsHtml}
|
||||
</div>
|
||||
|
||||
<div class="field-group">
|
||||
<label>Комментарий</label>
|
||||
<input type="text" id="m-metric-notes" value="${source.notes || ''}" placeholder="Например: утром натощак">
|
||||
</div>
|
||||
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-secondary" onclick="ModalBase.closeModal()">Отмена</button>
|
||||
<button class="btn btn-success" onclick="MetricsModal.submit()">Сохранить</button>
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
}
|
||||
|
||||
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 };
|
||||
|
||||
@@ -2,38 +2,92 @@ const container = () => document.getElementById('modal-container');
|
||||
|
||||
export function showModal(html) {
|
||||
container().innerHTML = `<div class="modal-overlay" onclick="ModalBase.closeOnBg(event)">${html}</div>`;
|
||||
const content = container().querySelector('.modal-content');
|
||||
if (content) content.scrollTop = 0;
|
||||
// Под модалкой страница не скроллится — иначе клавиатура «уводит» вёрстку
|
||||
document.body.classList.add('modal-open');
|
||||
}
|
||||
|
||||
export function closeModal() {
|
||||
container().innerHTML = '';
|
||||
document.body.classList.remove('modal-open');
|
||||
}
|
||||
|
||||
export function closeOnBg(e) {
|
||||
if (e.target.classList.contains('modal-overlay')) closeModal();
|
||||
}
|
||||
|
||||
export function stepperHtml(id, value, step, placeholder, inputmode = 'decimal') {
|
||||
/**
|
||||
* Фокус в числовом поле: выделяем текущее значение целиком, чтобы ввод с
|
||||
* клавиатуры сразу перезаписывал цифру; и подстраховываем скролл — мобильная
|
||||
* клавиатура часто перекрывает поле, а страница под модалкой не крутится.
|
||||
*/
|
||||
export function focusInput(el) {
|
||||
requestAnimationFrame(() => {
|
||||
try { el.select(); } catch (e) { /* не для всех типов select недоступен */ }
|
||||
});
|
||||
setTimeout(() => {
|
||||
el.scrollIntoView({ block: 'center', behavior: 'smooth' });
|
||||
}, 350);
|
||||
}
|
||||
|
||||
/**
|
||||
* Адаптивный шаг веса: лёгкие веса шагами мельче, тяжёлые — крупнее.
|
||||
*/
|
||||
export function weightStep(current) {
|
||||
const v = Math.abs(parseFloat(current) || 0);
|
||||
if (v < 12) return 1;
|
||||
if (v < 40) return 2.5;
|
||||
return 5;
|
||||
}
|
||||
|
||||
// inputmode='decimal'/'numeric' не даёт стрелкам и колесу мыши менять значение —
|
||||
// пересчитываем шаг по факту ввода, чтобы «+/-» продолжали идти по адаптивной сетке
|
||||
export function onStepperChange(id) {
|
||||
const input = document.getElementById(id);
|
||||
if (input && input.dataset.adaptive === 'weight') {
|
||||
input.step = weightStep(input.value);
|
||||
}
|
||||
}
|
||||
|
||||
export function stepperHtml(id, value, step, placeholder, inputmode = 'decimal', adaptive = false) {
|
||||
const v = value !== '' && value != null ? value : '';
|
||||
const stepVal = adaptive ? weightStep(v) : step;
|
||||
const adaptiveAttr = adaptive ? ` data-adaptive="weight" onchange="ModalBase.onStepperChange('${id}')"` : '';
|
||||
return `<div class="stepper-field">
|
||||
<button type="button" class="stepper-btn" onclick="ModalBase.stepValue('${id}', -${step})">−</button>
|
||||
<input type="number" id="${id}" step="${step}" value="${v}" placeholder="${placeholder}" inputmode="${inputmode}">
|
||||
<button type="button" class="stepper-btn" onclick="ModalBase.stepValue('${id}', ${step})">+</button>
|
||||
<button type="button" class="stepper-btn" onclick="ModalBase.stepValue('${id}', -${stepVal}, ${adaptive})">−</button>
|
||||
<input type="number" id="${id}" step="${stepVal}" value="${v}" placeholder="${placeholder}" inputmode="${inputmode}"
|
||||
onfocus="ModalBase.focusInput(this)"${adaptiveAttr}>
|
||||
<button type="button" class="stepper-btn" onclick="ModalBase.stepValue('${id}', ${stepVal}, ${adaptive})">+</button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
export function stepValue(id, delta) {
|
||||
export function stepValue(id, delta, adaptive = false) {
|
||||
const input = document.getElementById(id);
|
||||
if (!input) return;
|
||||
const current = parseFloat(input.value) || 0;
|
||||
const step = parseFloat(input.step) || 1;
|
||||
const newVal = Math.max(0, current + delta);
|
||||
const deltaAbs = Math.abs(delta);
|
||||
// Для адаптивных полей шаг берём по текущему значению, а не по step из кнопки
|
||||
const step = adaptive ? weightStep(current) : (parseFloat(input.step) || deltaAbs || 1);
|
||||
const newVal = Math.max(0, current + (delta > 0 ? step : -step));
|
||||
input.value = parseFloat((Math.round(newVal / step) * step).toFixed(4));
|
||||
input.dispatchEvent(new Event('change'));
|
||||
}
|
||||
|
||||
// Подложка модалки: закрытие по фону и по Esc; глобальный closeModal —
|
||||
// на него ссылаются onclick в разметке графиков и сводки
|
||||
window.closeModal = closeModal;
|
||||
document.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Escape" && container() && container().innerHTML) closeModal();
|
||||
});
|
||||
|
||||
window.ModalBase = {
|
||||
showModal,
|
||||
closeModal,
|
||||
close: closeModal,
|
||||
closeOnBg,
|
||||
focusInput,
|
||||
onStepperChange,
|
||||
weightStep,
|
||||
stepValue
|
||||
};
|
||||
|
||||
@@ -1,20 +1,43 @@
|
||||
import { showModal, closeModal, stepperHtml } from './modal-base.js';
|
||||
import { formatShortDate, formatSet } from '../utils.js';
|
||||
import { showModal, closeModal, stepperHtml, weightStep } from './modal-base.js';
|
||||
import { formatSet, escapeHtml } from '../utils.js';
|
||||
|
||||
let _data = {};
|
||||
let _cb = null;
|
||||
|
||||
export function showSetDialog(existingSet, history, callback) {
|
||||
function formatHistoryDate(iso) {
|
||||
const d = new Date(iso);
|
||||
return d.toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit', weekday: 'short' });
|
||||
}
|
||||
|
||||
function formatHistoryRow(h, historyLabel) {
|
||||
const sets = h.sets.map((s, i) =>
|
||||
`<span class="history-hint-set">${i + 1}) ${escapeHtml(formatSet(s))}</span>`).join('');
|
||||
const isVariant = historyLabel &&
|
||||
String(h.name || '').trim().toLowerCase() !== String(historyLabel).trim().toLowerCase();
|
||||
const nameLabel = isVariant
|
||||
? `<div class="history-hint-name">${escapeHtml(h.name)}</div>` : '';
|
||||
return `<div class="history-hint-row">
|
||||
<span class="history-hint-date">${formatHistoryDate(h.date)}</span>
|
||||
<span class="history-hint-sets">${nameLabel}${sets}</span>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object|null} existingSet - редактируемый подход
|
||||
* @param {Array} history - прошлые выполнения [{date, name, sets}]
|
||||
* @param {Function} callback
|
||||
* @param {object} options - { prefill - скопировать значения прошлого подхода,
|
||||
* historyLabel - имя текущего упражнения для подписи вариантов }
|
||||
*/
|
||||
export function showSetDialog(existingSet, history, callback, options = {}) {
|
||||
_cb = callback;
|
||||
const isEdit = !!existingSet;
|
||||
const isDropset = existingSet?.isDropset || false;
|
||||
const source = existingSet || options.prefill || null; // «+ подход» стартует с прошлого веса
|
||||
const isDropset = source?.isDropset || false;
|
||||
|
||||
let historyHtml = '';
|
||||
if (history?.length) {
|
||||
const rows = history.map(h => `<div class="history-hint-row">
|
||||
<span class="history-hint-date">${formatShortDate(h.date)}</span>
|
||||
<span class="history-hint-sets">${h.sets.map(formatSet).join(', ')}</span>
|
||||
</div>`).join('');
|
||||
const rows = history.map(h => formatHistoryRow(h, options.historyLabel)).join('');
|
||||
historyHtml = `<div class="history-hint"><div class="history-hint-title">📊 Прошлые тренировки</div>${rows}</div>`;
|
||||
}
|
||||
|
||||
@@ -26,15 +49,15 @@ export function showSetDialog(existingSet, history, callback) {
|
||||
Это дроп-сет</label></div>
|
||||
<div id="m-set-normal" class="${isDropset ? 'hidden' : ''}">
|
||||
<div class="field-row">
|
||||
<div class="field-group"><label>Вес (кг)</label>${stepperHtml('m-set-weight', existingSet?.weight ?? '', 0.5, 'Вес')}</div>
|
||||
<div class="field-group"><label>Повторения</label>${stepperHtml('m-set-reps', existingSet?.reps ?? '', 1, 'Повт.', 'numeric')}</div>
|
||||
<div class="field-group"><label>Вес (кг)</label>${stepperHtml('m-set-weight', source?.weight ?? '', 0.5, 'Вес', 'decimal', true)}</div>
|
||||
<div class="field-group"><label>Повторения</label>${stepperHtml('m-set-reps', source?.reps ?? '', 1, 'Повт.', 'numeric')}</div>
|
||||
</div></div>
|
||||
<div id="m-set-dropset-block" class="${isDropset ? '' : 'hidden'}">
|
||||
<div id="m-subsets-list"></div>
|
||||
<button class="btn btn-ghost mt-10" style="width:100%;" onclick="SetModal.addSubset()">+ Сбрасывание</button></div>
|
||||
<div class="field-group"><label>Оценка (1-5)</label>
|
||||
<div class="rating-grid" id="m-rating-grid">
|
||||
${[1,2,3,4,5].map(r => `<button class="rating-btn ${existingSet?.rating===r?'active':''}" data-rating="${r}" onclick="SetModal.rating(${r})">${r}</button>`).join('')}
|
||||
${[1,2,3,4,5].map(r => `<button class="rating-btn" data-rating="${r}" onclick="SetModal.rating(${r})">${r}</button>`).join('')}
|
||||
</div></div>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-secondary" onclick="ModalBase.closeOnBg({target:document.querySelector('.modal-overlay')})">Отмена</button>
|
||||
@@ -42,8 +65,8 @@ export function showSetDialog(existingSet, history, callback) {
|
||||
</div>`);
|
||||
|
||||
_data = {
|
||||
isDropset, rating: existingSet?.rating || 3,
|
||||
subSets: existingSet?.subSets ? JSON.parse(JSON.stringify(existingSet.subSets)) : [],
|
||||
isDropset, rating: source?.rating || 5,
|
||||
subSets: source?.subSets ? JSON.parse(JSON.stringify(source.subSets)) : [],
|
||||
};
|
||||
if (isDropset) { if (!_data.subSets.length) addSubset(); else renderSubsets(); }
|
||||
rating(_data.rating);
|
||||
@@ -64,33 +87,38 @@ export function addSubset() {
|
||||
}
|
||||
|
||||
export function renderSubsets() {
|
||||
document.getElementById('m-subsets-list').innerHTML = _data.subSets.map((s, i) => `
|
||||
document.getElementById('m-subsets-list').innerHTML = _data.subSets.map((s, i) => {
|
||||
const wStep = weightStep(s.weight);
|
||||
return `
|
||||
<div class="stepper-row">
|
||||
<div class="stepper-field">
|
||||
<button type="button" class="stepper-btn" onclick="SetModal.stepSubset(${i}, 'weight', -0.5)">−</button>
|
||||
<input type="number" id="m-sw-${i}" step="0.5" value="${s.weight || ''}" placeholder="Вес" inputmode="decimal" oninput="SetModal.updateSubset(${i}, 'weight', this.value)">
|
||||
<button type="button" class="stepper-btn" onclick="SetModal.stepSubset(${i}, 'weight', 0.5)">+</button>
|
||||
<button type="button" class="stepper-btn" onclick="SetModal.stepSubset(${i}, 'weight', -1)">−</button>
|
||||
<input type="number" id="m-sw-${i}" step="${wStep}" value="${s.weight || ''}" placeholder="Вес" inputmode="decimal"
|
||||
onfocus="ModalBase.focusInput(this)" oninput="SetModal.updateSubset(${i}, 'weight', this.value)">
|
||||
<button type="button" class="stepper-btn" onclick="SetModal.stepSubset(${i}, 'weight', 1)">+</button>
|
||||
</div>
|
||||
<div class="stepper-field">
|
||||
<button type="button" class="stepper-btn" onclick="SetModal.stepSubset(${i}, 'reps', -1)">−</button>
|
||||
<input type="number" id="m-sr-${i}" step="1" value="${s.reps || ''}" placeholder="Повт." inputmode="numeric" oninput="SetModal.updateSubset(${i}, 'reps', this.value)">
|
||||
<input type="number" id="m-sr-${i}" step="1" value="${s.reps || ''}" placeholder="Повт." inputmode="numeric"
|
||||
onfocus="ModalBase.focusInput(this)" oninput="SetModal.updateSubset(${i}, 'reps', this.value)">
|
||||
<button type="button" class="stepper-btn" onclick="SetModal.stepSubset(${i}, 'reps', 1)">+</button>
|
||||
</div>
|
||||
<button class="icon-btn danger" onclick="SetModal.removeSubset(${i})">✕</button>
|
||||
</div>
|
||||
`).join('');
|
||||
</div>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
export function updateSubset(i, field, value) {
|
||||
_data.subSets[i][field] = value;
|
||||
}
|
||||
|
||||
export function stepSubset(i, field, delta) {
|
||||
export function stepSubset(i, field, dir) {
|
||||
const current = parseFloat(_data.subSets[i][field]) || 0;
|
||||
const step = field === 'weight' ? 0.5 : 1;
|
||||
const newVal = Math.max(0, current + delta);
|
||||
// Вес в сбрасываниях — тоже адаптивный шаг
|
||||
const step = field === 'weight' ? weightStep(current) : 1;
|
||||
const newVal = Math.max(0, current + (dir > 0 ? step : -step));
|
||||
_data.subSets[i][field] = parseFloat((Math.round(newVal / step) * step).toFixed(4));
|
||||
renderSubsets(); // Перерисовываем, чтобы обновить значение в input
|
||||
renderSubsets(); // Перерисовываем, чтобы обновить значение и шаг в input
|
||||
}
|
||||
|
||||
export function removeSubset(i) {
|
||||
@@ -115,7 +143,8 @@ export function submit() {
|
||||
} else {
|
||||
const w = parseFloat(document.getElementById('m-set-weight').value);
|
||||
const r = parseInt(document.getElementById('m-set-reps').value);
|
||||
if (!w && !r) { alert('Укажите вес и повторения'); return; }
|
||||
// Пустой или нулевой должен быть и вес, и повторы — например «вес 0, 15 раз» с собой легитимен
|
||||
if (!(w > 0) && !(r > 0)) { alert('Укажите вес и повторения'); return; }
|
||||
closeModal(); _cb?.({ isDropset: false, weight: w||0, reps: r||0, rating: _data.rating });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Карточка сета (суперсета): подходы участников показываются по раундам —
|
||||
* 1-й подход каждого упражнения, отдых, 2-й подход каждого, и т.д.
|
||||
*/
|
||||
export function renderCircuit(w, group, members, isReadOnly) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'circuit-card';
|
||||
|
||||
const header = document.createElement('div');
|
||||
header.className = 'circuit-header';
|
||||
header.innerHTML = `
|
||||
<div>
|
||||
<span class="circuit-name"></span>
|
||||
<div class="circuit-members"></div>
|
||||
</div>
|
||||
`;
|
||||
// Состав сета можно править и в архивной тренировке — подходы не меняются
|
||||
if (!isReadOnly || w.endTime) {
|
||||
const controls = document.createElement('div');
|
||||
controls.className = 'circuit-controls';
|
||||
const editBtn = document.createElement('button');
|
||||
editBtn.className = 'btn btn-small btn-secondary';
|
||||
editBtn.textContent = '✎ состав';
|
||||
editBtn.onclick = () => window.GL.showGroupDialogFor(w.id, group.id);
|
||||
const unlinkBtn = document.createElement('button');
|
||||
unlinkBtn.className = 'btn btn-small btn-danger';
|
||||
unlinkBtn.textContent = '✕ разъединить';
|
||||
unlinkBtn.onclick = () => window.GL.removeGroup(w.id, group.id);
|
||||
controls.appendChild(editBtn);
|
||||
controls.appendChild(unlinkBtn);
|
||||
header.appendChild(controls);
|
||||
}
|
||||
// Текст — через textContent, чтобы кавычки и скобки в названиях ломали разметку
|
||||
header.querySelector('.circuit-name').textContent = '🔗 ' + group.name;
|
||||
header.querySelector('.circuit-members').textContent = members.map(m => m.name).join(' + ');
|
||||
card.appendChild(header);
|
||||
|
||||
const maxLen = Math.max(0, ...members.map(m => (m.sets || []).length));
|
||||
const roundsWrap = document.createElement('div');
|
||||
roundsWrap.className = 'circuit-rounds';
|
||||
|
||||
for (let k = 0; k < maxLen; k++) {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'circuit-round';
|
||||
const num = document.createElement('span');
|
||||
num.className = 'round-num';
|
||||
num.textContent = k + 1;
|
||||
row.appendChild(num);
|
||||
|
||||
members.forEach(ex => {
|
||||
const set = (ex.sets || [])[k];
|
||||
const chip = document.createElement('span');
|
||||
if (!set) {
|
||||
chip.className = 'circuit-chip empty';
|
||||
chip.textContent = ex.name + ': —';
|
||||
} else {
|
||||
chip.className = 'circuit-chip';
|
||||
chip.innerHTML = '<b></b> <span class="circuit-val"></span> <span class="circuit-stars"></span>';
|
||||
chip.querySelector('b').textContent = ex.name;
|
||||
chip.querySelector('.circuit-val').textContent =
|
||||
(set.isDropset && set.subSets && set.subSets.length)
|
||||
? '🔥' + set.subSets.map(s => `${s.weight}×${s.reps}`).join('→')
|
||||
: `${set.weight}×${set.reps}`;
|
||||
chip.querySelector('.circuit-stars').textContent = '★'.repeat(set.rating || 5);
|
||||
if (!isReadOnly) {
|
||||
chip.onclick = () => window.SL.editSet(w.id, ex.id, set.id);
|
||||
}
|
||||
}
|
||||
row.appendChild(chip);
|
||||
});
|
||||
roundsWrap.appendChild(row);
|
||||
}
|
||||
|
||||
if (maxLen === 0) {
|
||||
const p = document.createElement('p');
|
||||
p.className = 'text-muted text-small';
|
||||
p.style.padding = '10px 12px';
|
||||
p.textContent = 'Пока нет подходов';
|
||||
roundsWrap.appendChild(p);
|
||||
}
|
||||
card.appendChild(roundsWrap);
|
||||
|
||||
if (!isReadOnly || w.endTime) {
|
||||
const footRow = document.createElement('div');
|
||||
footRow.className = 'circuit-add';
|
||||
if (!w.endTime) {
|
||||
members.forEach(ex => {
|
||||
const b = document.createElement('button');
|
||||
b.className = 'btn btn-small btn-secondary';
|
||||
b.textContent = `+ ${ex.name}`;
|
||||
b.onclick = () => window.SL.addSet(w.id, ex.id);
|
||||
footRow.appendChild(b);
|
||||
});
|
||||
}
|
||||
const unlinkFoot = document.createElement('button');
|
||||
unlinkFoot.className = 'btn btn-small btn-ghost circuit-unlink-foot';
|
||||
unlinkFoot.textContent = '⛓️ Разъединить сет';
|
||||
unlinkFoot.onclick = () => window.GL.removeGroup(w.id, group.id);
|
||||
footRow.appendChild(unlinkFoot);
|
||||
card.appendChild(footRow);
|
||||
}
|
||||
|
||||
return card;
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// frontend/js/render/dashboard-screen.js
|
||||
|
||||
import { state } from '../state.js';
|
||||
import { escapeHtml } from '../utils.js';
|
||||
import { drawBodyMetricsGraph } from './dashboard.js';
|
||||
import { showExerciseSummary } from '../modals/exercise-summary.js';
|
||||
import { showChartDialog } from '../modals/chart-modal.js';
|
||||
|
||||
const CHART_EX_KEY = 'gym_dash_char…ise';
|
||||
|
||||
export function renderDashboard() {
|
||||
const app = document.getElementById('app');
|
||||
if (!app) return;
|
||||
|
||||
app.innerHTML = `
|
||||
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;">
|
||||
<h2>📊 Статистика</h2>
|
||||
<button class="btn btn-small btn-secondary" onclick="App.backToMain()">← Назад</button>
|
||||
</div>
|
||||
|
||||
<!-- Секция 1: Прогресс упражнений -->
|
||||
<div class="card mb-20">
|
||||
<h3>💪 Прогресс упражнения</h3>
|
||||
<div class="field-group">
|
||||
<label>Выберите упражнение</label>
|
||||
<select id="dash-ex-select" onchange="DashboardLogic.rememberExercise()">
|
||||
<option value="">— Выберите —</option>
|
||||
${getUniqueExercises().map(ex => `<option value="${escapeHtml(ex)}">${escapeHtml(ex)}</option>`).join('')}
|
||||
</select>
|
||||
</div>
|
||||
<div style="display:flex; gap:8px; flex-wrap:wrap">
|
||||
<button class="btn btn-primary" style="flex:1" onclick="DashboardLogic.openChart()">📈 Открыть график</button>
|
||||
<button class="btn btn-secondary" onclick="DashboardLogic.showExSummary()">📋 Сводка</button>
|
||||
</div>
|
||||
<p class="text-muted text-small mt-10">Главное — рабочий максимум «вес × повторы»: зелёный — прогресс (вес выше или тот же вес и больше повторов), красный — откат. Тусклые точки — остальные подходы, «×N» — их число.</p>
|
||||
</div>
|
||||
|
||||
<!-- Секция 2: Динамика тела -->
|
||||
<div class="card">
|
||||
<h3>⚖️ Динамика тела</h3>
|
||||
<div class="field-row">
|
||||
<div class="field-group">
|
||||
<label>Клиент (если тренер)</label>
|
||||
<select id="dash-client-select" onchange="DashboardLogic.updateBodyChart()">
|
||||
<option value="">Личные замеры</option>
|
||||
${state.clients.map(c => `<option value="${c.id}">${c.full_name}</option>`).join('')}
|
||||
</select>
|
||||
</div>
|
||||
<div class="field-group">
|
||||
<label>Тип замера</label>
|
||||
<select id="dash-metric-select" onchange="DashboardLogic.updateBodyChart()">
|
||||
${state.metricTypes.map(mt => `<option value="${mt.id}">${mt.name} (${mt.unit})</option>`).join('')}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<canvas id="chart-body" width="400" height="200" style="width:100%; background:#1e1e1e; border-radius:8px;"></canvas>
|
||||
</div>
|
||||
`;
|
||||
|
||||
window.DashboardLogic = {
|
||||
// Выбор упражнения запоминается и восстанавливается при следующем открытии
|
||||
rememberExercise: () => {
|
||||
localStorage.setItem(CHART_EX_KEY, document.getElementById('dash-ex-select').value);
|
||||
},
|
||||
openChart: () => {
|
||||
const select = document.getElementById('dash-ex-select');
|
||||
if (!select.value) { alert('Сначала выберите упражнение'); return; }
|
||||
localStorage.setItem(CHART_EX_KEY, select.value);
|
||||
showChartDialog(select.value);
|
||||
},
|
||||
showExSummary: () => {
|
||||
const select = document.getElementById('dash-ex-select');
|
||||
if (!select.value) { alert('Сначала выберите упражнение'); return; }
|
||||
showExerciseSummary(select.value);
|
||||
},
|
||||
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);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Первичная отрисовка: восстанавливаем закреплённый выбор упражнения
|
||||
const saved = localStorage.getItem(CHART_EX_KEY);
|
||||
const exSelect = document.getElementById('dash-ex-select');
|
||||
if (saved && Array.from(exSelect.options).some(o => o.value === saved)) exSelect.value = saved;
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,362 @@
|
||||
// frontend/js/render/dashboard.js
|
||||
|
||||
import { state } from '../state.js';
|
||||
import { formatDate } from '../utils.js';
|
||||
import { getExerciseChart } from '../logic/exercise.js';
|
||||
|
||||
/**
|
||||
* Рисует график прогресса упражнения: каждая точка — подход (вес по вертикали,
|
||||
* размер — повторения), фиолетовая линия — максимальный вес за тренировку
|
||||
* (силовая прогрессия), «×N» под осью — количество подходов (выносливость).
|
||||
* @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 days = getExerciseProgressData(exerciseName);
|
||||
|
||||
if (days.length === 0) {
|
||||
drawEmptyState(ctx, width, height, "Нет завершённых тренировок\nс этим упражнением");
|
||||
return;
|
||||
}
|
||||
|
||||
const maxWeight = Math.max(...days.map(d => d.max), 1);
|
||||
|
||||
const padding = { top: 14, right: 14, bottom: 58, left: 44 };
|
||||
const chartW = width - padding.left - padding.right;
|
||||
const chartH = height - padding.top - padding.bottom;
|
||||
|
||||
drawGridAndAxes(ctx, padding, chartW, chartH, maxWeight, 'Дата', 'Вес (кг)');
|
||||
|
||||
const n = days.length;
|
||||
const x = i => n === 1 ? padding.left + chartW / 2
|
||||
: padding.left + (chartW * i) / (n - 1);
|
||||
const y = v => padding.top + chartH - (v / maxWeight) * chartH;
|
||||
const maxReps = Math.max(1, ...days.flatMap(d => d.sets.map(s => s.reps)));
|
||||
|
||||
// Прогресс вершины относительно прошлой тренировки: вес выше — или тот же
|
||||
// вес и больше повторов => зелёный; меньше => красный; ровно => фиолетовый.
|
||||
const COLORS = { up: '#3ddc55', down: '#ff5a5a', flat: '#c792ff' };
|
||||
const cls = i => {
|
||||
if (i === 0) return 'flat';
|
||||
const a = days[i - 1], b = days[i];
|
||||
if (b.max > a.max) return 'up';
|
||||
if (b.max < a.max) return 'down';
|
||||
if ((b.topReps || 0) > (a.topReps || 0)) return 'up';
|
||||
if ((b.topReps || 0) < (a.topReps || 0)) return 'down';
|
||||
return 'flat';
|
||||
};
|
||||
const classes = days.map((_, i) => cls(i));
|
||||
|
||||
// Линия рабочего максимума: отрезки окрашены по прогрессу конца отрезка
|
||||
for (let i = 1; i < n; i++) {
|
||||
ctx.strokeStyle = COLORS[classes[i]];
|
||||
ctx.lineWidth = 4;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x(i - 1), y(days[i - 1].max));
|
||||
ctx.lineTo(x(i), y(days[i].max));
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
days.forEach((d, i) => {
|
||||
const px = x(i);
|
||||
|
||||
// Подходы дня ниже максимума — тусклые фоновые точки
|
||||
const below = d.sets.filter(s => s.weight !== d.max);
|
||||
const spread = below.length > 1 ? Math.min(11, chartW / (3 * n)) : 0;
|
||||
below.forEach((s, k) => {
|
||||
const dx = below.length > 1 ? -spread + (2 * spread * k) / (below.length - 1) : 0;
|
||||
const r = 2.2 + 2.8 * Math.min(1, s.reps / maxReps);
|
||||
ctx.beginPath();
|
||||
ctx.fillStyle = 'rgba(199, 146, 255, 0.55)';
|
||||
ctx.arc(px + dx, y(s.weight), r, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
});
|
||||
|
||||
// Вершина: рабочий максимум «вес × повторы» с цветом прогресса
|
||||
ctx.beginPath();
|
||||
ctx.fillStyle = COLORS[classes[i]];
|
||||
ctx.arc(px, y(d.max), 5.5, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
ctx.strokeStyle = '#ffffff';
|
||||
ctx.lineWidth = 1.2;
|
||||
ctx.stroke();
|
||||
if (n <= 10 || i >= n - 4 || classes[i] !== 'flat') {
|
||||
ctx.fillStyle = COLORS[classes[i]];
|
||||
ctx.font = 'bold 12px sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.fillText(`${d.max}×${d.topReps || ''}`, px, y(d.max) - 8);
|
||||
}
|
||||
|
||||
// Дата под каждой точкой оси X и количество подходов (выносливость)
|
||||
if (n <= 10 || i % 2 === 0) {
|
||||
ctx.fillStyle = '#d5d5d5';
|
||||
ctx.font = '10px sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.fillText(formatShortDate(d.date.toISOString()), px, height - padding.bottom + 15);
|
||||
ctx.fillStyle = '#b0b0b0';
|
||||
ctx.font = '10px sans-serif';
|
||||
ctx.fillText('×' + d.sets.length, px, height - padding.bottom + 29);
|
||||
}
|
||||
});
|
||||
|
||||
// Легенда — внизу, под датами
|
||||
drawLegend(ctx, width, [
|
||||
{ color: '#3ddc55', label: 'рабочий максимум: зелёный — прогресс, красный — откат' },
|
||||
{ color: 'rgba(199, 146, 255, 0.55)', label: 'тусклая точка = подход (размер = повторы)' },
|
||||
], height - 8);
|
||||
}
|
||||
|
||||
/**
|
||||
* Данные графика: по каждой завершённой тренировке — список подходов
|
||||
* (дроп-сеты развёрнуты) и максимальный вес. Варианты упражнения из одной
|
||||
* группы справочника объединяются в одну линию (общий источник —
|
||||
* getExerciseChart из logic/exercise.js).
|
||||
*/
|
||||
export function getExerciseProgressData(exerciseName, clientId = null) {
|
||||
return getExerciseChart(exerciseName, clientId)
|
||||
.map(p => ({ date: new Date(p.date), sets: p.sets, max: p.maxWeight, topReps: p.topReps }))
|
||||
.slice(-10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Рисует график динамики телесных замеров
|
||||
* @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 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 = '#c9c9c9';
|
||||
ctx.font = '11px 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 drawLegend(ctx, width, items, y) {
|
||||
// y — базовая линия текста (легенда внизу); квадрат чуть выше текста
|
||||
ctx.font = '11px sans-serif';
|
||||
ctx.textAlign = 'left';
|
||||
let xOffset = 10;
|
||||
items.forEach(item => {
|
||||
ctx.fillStyle = item.color;
|
||||
ctx.fillRect(xOffset, y - 9, 10, 10);
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.fillText(item.label, xOffset + 15, y);
|
||||
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' });
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { state } from '../state.js';
|
||||
import { escapeHtml } from '../utils.js';
|
||||
import { renderSetRow } from './set-row.js';
|
||||
|
||||
export function renderExercise(w, ex, isReadOnly = false) {
|
||||
@@ -15,6 +16,8 @@ export function renderExercise(w, ex, isReadOnly = false) {
|
||||
<span class="exercise-name">${ex.name}</span>
|
||||
<span class="exercise-summary">${summary}</span>
|
||||
</div>
|
||||
<button class="btn-icon chart-btn" data-ex="${escapeHtml(ex.name)}" title="График прогрессии"
|
||||
onclick="event.stopPropagation(); CM.showChartFromBtn(this)">📈</button>
|
||||
<span class="chevron ${isExpanded ? 'open' : ''}">›</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
@@ -8,14 +8,19 @@ export function renderSetRow(workoutId, exerciseId, set, index, isReadOnly = fal
|
||||
</div>
|
||||
`;
|
||||
|
||||
const setTime = set.timestamp
|
||||
? `<div class="set-time">${new Date(set.timestamp).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' })}</div>`
|
||||
: '<div class="set-time"></div>';
|
||||
|
||||
if (set.isDropset && set.subSets && set.subSets.length > 0) {
|
||||
row.className = 'dropset-group';
|
||||
const subsText = set.subSets.map(s => `${s.weight}×${s.reps}`).join(' → ');
|
||||
const ratingStars = '★'.repeat(set.rating || 3);
|
||||
const ratingStars = '★'.repeat(set.rating || 5);
|
||||
row.innerHTML = `
|
||||
<div class="set-row" style="grid-template-columns: 30px 1fr auto ${isReadOnly ? '0' : 'auto'};">
|
||||
<div class="set-row dropset-row">
|
||||
<div class="set-number">${index + 1}</div>
|
||||
<div class="set-cell dropset">🔥 ${subsText}</div>
|
||||
${setTime}
|
||||
<div class="set-rating">${ratingStars}</div>
|
||||
${actionsHtml}
|
||||
</div>
|
||||
@@ -26,7 +31,8 @@ export function renderSetRow(workoutId, exerciseId, set, index, isReadOnly = fal
|
||||
<div class="set-number">${index + 1}</div>
|
||||
<div class="set-cell">${set.weight || '—'} кг</div>
|
||||
<div class="set-cell">${set.reps || '—'}</div>
|
||||
<div class="set-rating">${'★'.repeat(set.rating || 3)}</div>
|
||||
${setTime}
|
||||
<div class="set-rating">${'★'.repeat(set.rating || 5)}</div>
|
||||
${actionsHtml}
|
||||
</div>
|
||||
`;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { state } from '../state.js';
|
||||
import { renderExercise } from './exercise-card.js';
|
||||
import { renderCircuit } from './circuit-card.js';
|
||||
import { renderCardioItem } from './cardio-card.js';
|
||||
import { formatDate } from '../utils.js';
|
||||
|
||||
@@ -115,6 +116,7 @@ export function renderWorkoutDetails(w) {
|
||||
addSection.innerHTML = `
|
||||
<button class="btn btn-secondary" onclick="EL.addExercise('${w.id}')">+ Упражнение</button>
|
||||
<button class="btn btn-secondary" onclick="CL.addCardio('${w.id}')">+ Кардио</button>
|
||||
${w.exercises.length >= 2 ? `<button class="btn btn-secondary" onclick="GL.showGroupDialogFor('${w.id}')">🔗 Сет</button>` : ''}
|
||||
`;
|
||||
wrap.appendChild(addSection);
|
||||
}
|
||||
@@ -131,11 +133,45 @@ export function renderWorkoutDetails(w) {
|
||||
cardioWarmup.forEach(c => wrap.appendChild(renderCardioItem(w.id, c, isReadOnly)));
|
||||
}
|
||||
|
||||
// Упражнения
|
||||
[...w.exercises].reverse().forEach(ex => {
|
||||
wrap.appendChild(renderExercise(w, ex, isReadOnly));
|
||||
// Упражнения: участники сетов выводятся одной карточкой по раундам
|
||||
const groups = (w.setGroups || [])
|
||||
.map(g => ({
|
||||
g,
|
||||
members: g.exerciseIds
|
||||
.map(id => w.exercises.find(e => e.id === id))
|
||||
.filter(Boolean),
|
||||
}))
|
||||
.filter(x => x.members.length >= 2);
|
||||
|
||||
const memberOf = new Map(); // exerciseId -> карточка сета
|
||||
groups.forEach(({ g, members }) => {
|
||||
members.forEach(m => { if (!memberOf.has(m.id)) memberOf.set(m.id, { g, members }); });
|
||||
});
|
||||
|
||||
const seenGroups = new Set();
|
||||
[...w.exercises].reverse().forEach(ex => {
|
||||
const inGroup = memberOf.get(ex.id);
|
||||
if (inGroup) {
|
||||
if (seenGroups.has(inGroup.g.id)) return; // карточка сета уже выведена
|
||||
seenGroups.add(inGroup.g.id);
|
||||
wrap.appendChild(renderCircuit(w, inGroup.g, inGroup.members, isReadOnly));
|
||||
} else {
|
||||
wrap.appendChild(renderExercise(w, ex, isReadOnly));
|
||||
}
|
||||
});
|
||||
|
||||
if (w.endTime && w.exercises.length >= 2) {
|
||||
// Тренировка завершена (в т.ч. уже в архиве) — сеты можно собрать
|
||||
// задним числом: состав сета не меняет подходы, а после правки
|
||||
// тренировка пометится «не сохранено» и уйдёт на сервер при синке
|
||||
const groupBtn = document.createElement('button');
|
||||
groupBtn.className = 'btn btn-ghost mt-10';
|
||||
groupBtn.style.width = '100%';
|
||||
groupBtn.textContent = '🔗 Объединить упражнения в сет';
|
||||
groupBtn.onclick = () => window.GL.showGroupDialogFor(w.id);
|
||||
wrap.appendChild(groupBtn);
|
||||
}
|
||||
|
||||
// Заминка внизу
|
||||
if (cardioCooldown.length > 0) {
|
||||
const title = document.createElement('h4');
|
||||
@@ -174,7 +210,8 @@ export function renderWorkoutDetails(w) {
|
||||
if (isReadOnly) {
|
||||
finishBlock.innerHTML = `
|
||||
<h3>🔒 Архив</h3>
|
||||
<p class="text-muted text-small">Тренировка синхронизирована и завершена. Редактирование недоступно.</p>`;
|
||||
<p class="text-muted text-small">Тренировка синхронизирована и завершена. Редактирование недоступно.</p>
|
||||
<button class="btn btn-danger mt-10" style="width:100%;" onclick="WL.deleteWorkout('${w.id}')">🗑 Удалить тренировку</button>`;
|
||||
} else if (isActive) {
|
||||
// Проверяем, есть ли уже данные в тренировке
|
||||
const hasData = (w.exercises && w.exercises.length > 0) || (w.cardio && w.cardio.length > 0);
|
||||
@@ -192,6 +229,7 @@ export function renderWorkoutDetails(w) {
|
||||
<div style="display: flex; flex-direction: column; gap: 10px; margin-top: 10px;">
|
||||
${cancelBtnHtml}
|
||||
<button class="btn btn-danger" onclick="WL.finishWorkout('${w.id}')">⏹ Закончить тренировку</button>
|
||||
<button class="btn btn-ghost" style="color: var(--danger); border-color: var(--danger);" onclick="WL.deleteWorkout('${w.id}')">🗑 Удалить тренировку</button>
|
||||
</div>
|
||||
`;
|
||||
} else {
|
||||
|
||||
+152
-57
@@ -1,88 +1,183 @@
|
||||
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,
|
||||
|
||||
goal: "strength",
|
||||
deletedWorkouts: [],
|
||||
};
|
||||
}
|
||||
|
||||
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";
|
||||
normalizeWorkouts();
|
||||
}
|
||||
|
||||
// Допиваем поля, которых может не быть в сохранении старой версии
|
||||
function normalizeWorkouts() {
|
||||
for (const w of state.workouts || []) {
|
||||
if (!Array.isArray(w.exercises)) w.exercises = [];
|
||||
if (!Array.isArray(w.cardio)) w.cardio = [];
|
||||
if (!Array.isArray(w.setGroups)) w.setGroups = [];
|
||||
for (const ex of w.exercises) {
|
||||
if (!Array.isArray(ex.sets)) ex.sets = [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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];
|
||||
|
||||
+778
-104
@@ -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,601 @@ 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 ?? 5,
|
||||
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,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Серверный состав сетов → локальные setGroups. Участники приходят как
|
||||
* sync_id упражнений тренировки; локальные id конвертируются из тех же
|
||||
* sync_id, поэтому ссылка восстанавливается по месту.
|
||||
*/
|
||||
function serverSetGroupsToLocal(w) {
|
||||
let sg = w.set_groups || [];
|
||||
if (typeof sg === "string") {
|
||||
try { sg = JSON.parse(sg); } catch { sg = []; }
|
||||
}
|
||||
if (!Array.isArray(sg)) return [];
|
||||
|
||||
const known = new Set(
|
||||
(w.workout_exercises || []).map((ex) => ex.sync_id).filter(Boolean)
|
||||
);
|
||||
|
||||
return sg
|
||||
.map((g) => ({
|
||||
id: g.sync_id || generateUUID(),
|
||||
name: g.name || "Сет",
|
||||
exerciseIds: (g.exercise_sync_ids || []).filter((sid) => known.has(sid)),
|
||||
}))
|
||||
.filter((g) => g.exerciseIds.length >= 2);
|
||||
}
|
||||
|
||||
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,
|
||||
setGroups: serverSetGroupsToLocal(w),
|
||||
|
||||
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 ?? 5,
|
||||
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 tombstones = new Set(Array.isArray(state.deletedWorkouts) ? state.deletedWorkouts : []);
|
||||
const serverWorkouts = (data.workouts || [])
|
||||
.map((w) => convertBackendWorkout(w, workoutTypeNameById))
|
||||
.filter((w) => !tombstones.has(w.sync_id));
|
||||
|
||||
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 +652,7 @@ function buildClientsPayload() {
|
||||
}
|
||||
|
||||
function buildExercisesPayload() {
|
||||
return state.exerciseRef.map((e) => {
|
||||
return (state.exerciseRef || []).map((e) => {
|
||||
ensureSyncId(e);
|
||||
|
||||
const wt = findWorkoutTypeByName(e.workoutType);
|
||||
@@ -91,18 +674,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) ?? 5,
|
||||
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 +703,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 +719,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 +739,179 @@ 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 || "",
|
||||
|
||||
// Состав сетов: участники ссылками на sync_id упражнений этой тренировки
|
||||
set_groups: (w.setGroups || []).map((g) => ({
|
||||
sync_id: g.id || null,
|
||||
name: g.name || "Сет",
|
||||
exercise_sync_ids: (g.exerciseIds || [])
|
||||
.map((id) => {
|
||||
const ex = (w.exercises || []).find((e) => e.id === id);
|
||||
return ex ? ensureSyncId(ex) : null;
|
||||
})
|
||||
.filter(Boolean),
|
||||
})),
|
||||
|
||||
workout_exercises: buildWorkoutExercisesPayload(w.exercises),
|
||||
cardio_sessions: buildCardioPayload(w.cardio),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// ... предыдущие импорты и хелперы остаются ...
|
||||
|
||||
export async function sync() {
|
||||
const dirty = getDirtyWorkouts();
|
||||
// Отправляем все тренировки: правки в уже синхронизированной тренировке
|
||||
// тоже должны уходить на сервер (upsert по sync_id идемпотентен)
|
||||
const dirtyWorkouts = state.workouts;
|
||||
const dirtyMetrics = getDirtyMetrics(); // Новая функция
|
||||
const tombstones = Array.isArray(state.deletedWorkouts) ? state.deletedWorkouts : [];
|
||||
|
||||
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 && tombstones.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), // Отправляем замеры
|
||||
deleted_sync_ids: tombstones.slice(), // удалённые тренировки
|
||||
};
|
||||
|
||||
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);
|
||||
// Надгробия снимаем только если сервер умеет удалять (в ответе есть
|
||||
// счётчик deleted). Со старым бэкендом ответ 200, но удаления он
|
||||
// проигнорировал — оставляем список, уйдёт в следующем синке.
|
||||
if (response.deleted) state.deletedWorkouts = [];
|
||||
|
||||
saveState();
|
||||
|
||||
if (typeof window.renderMainScreen === "function") {
|
||||
window.renderMainScreen();
|
||||
}
|
||||
|
||||
const createdW = response.created?.workouts || 0;
|
||||
const updatedW = response.updated?.workouts || 0;
|
||||
const deletedW = response.deleted?.workouts || 0;
|
||||
const createdM = response.created?.body_metrics || 0;
|
||||
|
||||
let message = `Синхронизировано:\nТренировок: ${createdW + updatedW}` +
|
||||
(updatedW ? ` (новых ${createdW}, обновлено ${updatedW})` : "") +
|
||||
(deletedW ? `\nУдалено: ${deletedW}` : "") +
|
||||
`\nЗамеров: ${createdM}`;
|
||||
|
||||
if (tombstones.length && !response.deleted) {
|
||||
message += "\n\n⚠️ Сервер не подтвердил удаления — на нём старый бэкенд. Пересоберите backend, удаления уйдут при следующем синке.";
|
||||
}
|
||||
|
||||
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
|
||||
}))
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name localhost;
|
||||
|
||||
# Статика фронтенда
|
||||
location / {
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
try_files $uri $uri/ /index.html;
|
||||
# no-cache: браузер каждый раз сверяется по ETag — после деплоя
|
||||
# сразу видно свежие файлы, а не прогретый кэш
|
||||
add_header Cache-Control "no-cache";
|
||||
}
|
||||
|
||||
# JS и CSS: отсутствующий файл — 404, а не index.html (иначе браузер
|
||||
# получает HTML под видом модуля и падает с непонятной ошибкой), + no-cache
|
||||
location ~* \.(js|css)$ {
|
||||
root /usr/share/nginx/html;
|
||||
try_files $uri =404;
|
||||
add_header Cache-Control "no-cache";
|
||||
}
|
||||
|
||||
# Проксирование 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";
|
||||
|
||||
# Убираем префикс /api, так как бэк ожидает пути вроде /auth/login
|
||||
rewrite ^/api/(.*)$ /$1 break;
|
||||
}
|
||||
}
|
||||
@@ -130,3 +130,103 @@ textarea { resize: vertical; min-height: 60px; }
|
||||
border-color: var(--text);
|
||||
box-shadow: 0 0 0 2px var(--bg), 0 0 0 4px var(--text);
|
||||
}
|
||||
|
||||
/* === Progress chart === */
|
||||
.chart-btn { flex: 0 0 auto; font-size: 0.95rem; opacity: 0.75; }
|
||||
.chart-svg { width: 100%; height: auto; display: block; margin: 8px 0 4px; }
|
||||
.chart-svg circle.chart-set { fill: var(--accent); fill-opacity: 0.38; stroke: none; }
|
||||
.chart-axis { stroke: var(--border); stroke-width: 1; }
|
||||
.chart-label { font-size: 12px; fill: var(--text-secondary, #888); }
|
||||
/* Линия рабочего максимума и её вершины: цвет = прогресс относительно прошлого раза */
|
||||
.chart-seg { stroke-width: 4; stroke-linecap: round; }
|
||||
.chart-svg circle.chart-vert { stroke: #fff; stroke-width: 2; }
|
||||
.chart-seg.chart-up, .chart-svg circle.chart-vert.chart-up { stroke: #3ddc55; }
|
||||
.chart-seg.chart-down, .chart-svg circle.chart-vert.chart-down { stroke: #ff5a5a; }
|
||||
.chart-seg.chart-flat, .chart-svg circle.chart-vert.chart-flat { stroke: #c792ff; }
|
||||
.chart-svg circle.chart-vert.chart-up { fill: #3ddc55; }
|
||||
.chart-svg circle.chart-vert.chart-down { fill: #ff5a5a; }
|
||||
.chart-svg circle.chart-vert.chart-flat { fill: #c792ff; }
|
||||
.chart-vert-label { font-weight: 700; font-size: 15px; }
|
||||
.chart-vert-label.chart-up { fill: #3ddc55; }
|
||||
.chart-vert-label.chart-down { fill: #ff5a5a; }
|
||||
.chart-vert-label.chart-flat { fill: #c792ff; }
|
||||
.chart-up { color: #3ddc55; }
|
||||
.chart-down { color: #ff5a5a; }
|
||||
.chart-sub { font-size: 0.72rem; color: var(--text-secondary, #888); }
|
||||
.chart-list { display: flex; flex-direction: column; gap: 2px; margin-top: 8px; }
|
||||
.chart-row { display: flex; justify-content: space-between; gap: 8px; font-size: 0.78rem; }
|
||||
.chart-date { color: var(--text-secondary, #888); flex: 0 0 auto; }
|
||||
.chart-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.chart-sets { flex: 1; min-width: 0; text-align: right; color: var(--text-secondary, #888); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.chart-val { font-weight: 600; flex: 0 0 auto; }
|
||||
.chart-count { fill: #c9c9c9; font-size: 12px; }
|
||||
.chart-date-lab { fill: #d5d5d5; font-size: 12.5px; font-weight: 600; }
|
||||
.chart-count-num { color: var(--accent); }
|
||||
/* Сводка по упражнению */
|
||||
.sum-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px; margin-top: 10px; }
|
||||
@media (min-width: 480px) { .sum-grid { grid-template-columns: repeat(3, 1fr); } }
|
||||
.sum-card { background: var(--card-bg, rgba(255,255,255,0.04)); border: 1px solid var(--border); border-radius: 10px; padding: 8px 10px; }
|
||||
.sum-value { font-size: 1.05rem; font-weight: 700; }
|
||||
.sum-label { font-size: 0.72rem; color: var(--text-secondary, #888); margin-top: 2px; }
|
||||
.sum-sub { font-size: 0.68rem; color: var(--text-secondary, #888); margin-top: 2px; }
|
||||
.chart-legend-bottom { margin-top: 2px; }
|
||||
|
||||
/* Крупные кнопки под графиками и сводками — попадание в зале после подхода */
|
||||
.modal-actions-row {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
.big-touch {
|
||||
flex: 1;
|
||||
min-height: 56px;
|
||||
font-size: 17px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.modal-fullscreen .btn-icon {
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
min-width: 52px;
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
/* Легенда графика — крупная, над графиком (статистика записей остаётся внизу) */
|
||||
.chart-legend-top {
|
||||
font-size: 15px;
|
||||
line-height: 1.45;
|
||||
margin: 2px 2px 10px;
|
||||
}
|
||||
|
||||
/* Броская легенда графика: три коротких чипа + ⓘ с пояснением */
|
||||
.chart-legend-big {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 14px;
|
||||
font-size: 19px;
|
||||
font-weight: 700;
|
||||
margin: 2px 2px 8px;
|
||||
}
|
||||
.lg-line { color: #fff; }
|
||||
.lg-up { color: #3ddc55; }
|
||||
.lg-down { color: #ff5a5a; }
|
||||
.lg-info {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 50%;
|
||||
border: 1.5px solid #777;
|
||||
background: transparent;
|
||||
color: #ccc;
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
}
|
||||
.chart-hint {
|
||||
font-size: 14.5px;
|
||||
line-height: 1.5;
|
||||
color: #d5d5d5;
|
||||
background: rgba(255, 255, 255, 0.07);
|
||||
border-radius: 12px;
|
||||
padding: 10px 14px;
|
||||
margin: 0 2px 10px;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/* === Modal === */
|
||||
body.modal-open { overflow: hidden; }
|
||||
.modal-overlay {
|
||||
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
|
||||
background: rgba(0,0,0,0.85); z-index: 100; display: flex;
|
||||
@@ -8,6 +9,12 @@
|
||||
background: var(--surface); padding: 20px; border-radius: 16px 16px 0 0;
|
||||
width: 100%; max-width: 500px; max-height: 85vh; overflow-y: auto; animation: slideUp 0.25s;
|
||||
}
|
||||
/* График на весь экран — крупно, как в демо */
|
||||
.modal-content.modal-fullscreen {
|
||||
max-width: 100%; width: 100%; height: 100%; max-height: 100%;
|
||||
border-radius: 0; padding: 16px 12px calc(16px + env(safe-area-inset-bottom));
|
||||
animation: fadeIn 0.2s;
|
||||
}
|
||||
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
|
||||
@keyframes slideUp { from { transform: translateY(100%); } to { transform: translateY(0); } }
|
||||
|
||||
@@ -23,3 +30,12 @@
|
||||
.autocomplete-item:last-child { border-bottom: none; }
|
||||
.autocomplete-item:active { background: var(--surface); }
|
||||
.autocomplete-item .freq { float: right; font-size: 0.75rem; color: var(--text-secondary); }
|
||||
|
||||
/* === Чекбоксы состава сета === */
|
||||
.group-check-list { display: flex; flex-direction: column; gap: 6px; max-height: 40vh; overflow-y: auto; }
|
||||
.group-check {
|
||||
display: flex; align-items: center; gap: 8px; padding: 10px 12px;
|
||||
background: var(--surface-2); border: 1px solid var(--border); border-radius: 8px;
|
||||
font-size: 0.95rem; cursor: pointer;
|
||||
}
|
||||
.group-check input { width: auto; }
|
||||
|
||||
@@ -16,3 +16,16 @@
|
||||
.metric-card .label { font-size: 0.75rem; color: var(--text-secondary); text-transform: uppercase; margin-bottom: 4px; }
|
||||
.metric-card .value { font-size: 1.3rem; font-weight: 700; color: var(--primary); }
|
||||
.metric-card .date { font-size: 0.7rem; color: var(--text-secondary); margin-top: 4px; }
|
||||
|
||||
/* === Справочник: типы и группы вариантов === */
|
||||
.ref-type-head {
|
||||
font-weight: 700; color: var(--text-secondary); text-transform: uppercase;
|
||||
font-size: 0.75rem; letter-spacing: 0.5px; margin: 14px 0 6px;
|
||||
}
|
||||
.ref-type-head:first-of-type { margin-top: 0; }
|
||||
.ref-group-head { color: var(--primary); font-size: 0.8rem; font-weight: 600; margin: 8px 0 4px 8px; }
|
||||
.exercise-ref-grouped { flex-direction: column; align-items: stretch; gap: 8px; margin-left: 8px; }
|
||||
.ref-item-top { display: flex; justify-content: space-between; align-items: center; }
|
||||
.ref-item-controls { display: flex; gap: 6px; }
|
||||
.ref-item-controls select { width: auto; min-width: 110px; padding: 6px; font-size: 0.8rem; }
|
||||
.ref-item-controls input { flex: 1; min-width: 0; padding: 6px 8px; font-size: 0.8rem; }
|
||||
|
||||
@@ -27,13 +27,14 @@
|
||||
/* === Sets === */
|
||||
.sets-table { margin-bottom: 12px; }
|
||||
.set-row {
|
||||
display: grid; grid-template-columns: 30px 1fr 1fr auto auto; gap: 6px;
|
||||
display: grid; grid-template-columns: 30px 1fr 1fr auto auto auto; gap: 6px;
|
||||
align-items: center; padding: 8px 0; border-bottom: 1px solid var(--border); font-size: 0.95rem;
|
||||
}
|
||||
.set-row:last-child { border-bottom: none; }
|
||||
.set-number { color: var(--text-secondary); font-size: 0.8rem; text-align: center; }
|
||||
.set-cell { text-align: center; font-weight: 600; }
|
||||
.set-cell.dropset { color: var(--warning); font-size: 0.85rem; }
|
||||
.set-time { color: var(--text-secondary); font-size: 0.72rem; white-space: nowrap; }
|
||||
.set-rating { color: var(--warning); font-size: 0.85rem; }
|
||||
.set-actions { display: flex; gap: 4px; }
|
||||
|
||||
@@ -55,6 +56,51 @@
|
||||
.history-hint-date { color: var(--text-secondary); font-size: 0.75rem; }
|
||||
.history-hint-sets { color: var(--text); font-weight: 500; }
|
||||
|
||||
/* === История подходов: номер подхода, вес, вариант === */
|
||||
.history-hint-sets { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 2px 12px; }
|
||||
.history-hint-set { white-space: nowrap; }
|
||||
.history-hint-name {
|
||||
width: 100%;
|
||||
text-align: right;
|
||||
color: var(--primary);
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
|
||||
/* === Сет (суперсет): подходы участников по раундам === */
|
||||
.circuit-card {
|
||||
background-color: var(--surface); border-radius: var(--radius); margin-bottom: 10px;
|
||||
border: 1px solid var(--primary); overflow: hidden;
|
||||
}
|
||||
.circuit-header {
|
||||
padding: 12px 14px; display: flex; justify-content: space-between; align-items: center;
|
||||
flex-wrap: wrap; gap: 8px; border-bottom: 1px solid var(--border);
|
||||
background: rgba(187, 134, 252, 0.07);
|
||||
}
|
||||
.circuit-name { font-weight: 700; color: var(--primary); }
|
||||
.circuit-members { font-size: 0.78rem; color: var(--text-secondary); margin-top: 2px; }
|
||||
.circuit-controls { display: flex; gap: 6px; }
|
||||
.circuit-rounds { padding: 8px 12px; }
|
||||
.circuit-round {
|
||||
display: flex; align-items: center; flex-wrap: wrap; gap: 6px;
|
||||
padding: 6px 0; border-bottom: 1px dotted var(--border);
|
||||
}
|
||||
.circuit-round:last-child { border-bottom: none; }
|
||||
.round-num {
|
||||
min-width: 22px; height: 22px; border-radius: 50%; background: var(--primary); color: #000;
|
||||
font-size: 0.75rem; font-weight: 700; display: inline-flex; align-items: center; justify-content: center;
|
||||
}
|
||||
.circuit-chip {
|
||||
background: var(--surface-2); border: 1px solid var(--border); border-radius: 8px;
|
||||
padding: 4px 8px; font-size: 0.82rem; cursor: pointer;
|
||||
}
|
||||
.circuit-chip b { color: var(--primary); font-weight: 600; }
|
||||
.circuit-chip .circuit-val { margin: 0 4px; }
|
||||
.circuit-chip .circuit-stars { color: var(--warning); font-size: 0.75rem; }
|
||||
.circuit-chip.empty { opacity: 0.45; cursor: default; }
|
||||
.circuit-add { display: flex; flex-wrap: wrap; gap: 6px; padding: 10px 12px; border-top: 1px solid var(--border); }
|
||||
.circuit-unlink-foot { margin-left: auto; color: var(--danger); border-color: var(--danger); }
|
||||
.dropset-row { grid-template-columns: 30px 1fr auto auto auto; }
|
||||
|
||||
/* === Finish block === */
|
||||
.finish-block { margin-top: 30px; padding: 16px; background: linear-gradient(to bottom, transparent, rgba(207, 102, 121, 0.1)); border-top: 2px solid var(--danger); }
|
||||
.finish-block h3 { color: var(--danger); margin-bottom: 10px; }
|
||||
|
||||
@@ -1,21 +1,112 @@
|
||||
# gym bro
|
||||
# Gym Bro 😈
|
||||
|
||||
``` text
|
||||
clients (ФИО, ДР, цель)
|
||||
│
|
||||
│ 1:N
|
||||
├──► workouts ──────► workout_types (справочник)
|
||||
│ │
|
||||
│ │ 1:N
|
||||
│ ├──► workout_exercises ──► exercises ──► workout_types
|
||||
│ │ │
|
||||
│ │ │ 1:N
|
||||
│ │ └──► sets ──► dropset_items
|
||||
│ │
|
||||
│ └──► cardio
|
||||
│
|
||||
└──► body_metrics
|
||||
│
|
||||
│ 1:N
|
||||
└──► body_metric_values ──► metric_types (справочник)
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
**Gym Bro** — легковесный self-hosted трекер тренировок с офлайн-режимом, синхронизацией и режимом тренера. Без лишнего веса, только мышцы. 💪
|
||||
|
||||
## Особенности
|
||||
|
||||
* **Offline First:** работает без интернета. Данные живут в `localStorage`, при появлении связи синхронизируются с сервером (уходят все тренировки, правки после синхронизации тоже).
|
||||
* **Multi-user:** разделение данных по пользователям (JWT + bcrypt). Каждый видит только своё.
|
||||
* **Trainer Mode:** ведение нескольких клиентов с цветовым разделением.
|
||||
* **Сеты и суперсеты:** объединение упражнений в круговые тренировки по раундам, расформирование без потери подходов.
|
||||
* **Группы вариантов упражнения:** «Жим гантелей 30» и «Жим гантелей 45» — один справочник, общая история и общий график прогрессии.
|
||||
* **История в момент подхода:** в модалке веса видны последние тренировки с датами, номерами подходов и дроп-сетами; шаг степпера подстраивается под рабочий вес.
|
||||
* **Дашборд и графики:** статистика по объёму, подходу за тренировку, 📈 график прогрессии по каждому упражнению.
|
||||
* **Body Metrics:** замеры тела (вес, объёмы) с типами и историей.
|
||||
* **Без сборки фронтенда:** чистый HTML/CSS/JS (ES-модули). Никакого Webpack/Vite.
|
||||
* **Docker Compose:** весь стек — API, статика и nginx-прокси — одной командой.
|
||||
|
||||
## Технологии
|
||||
|
||||
* **Backend:** Python 3.11+, FastAPI, SQLAlchemy, SQLite, PyJWT, bcrypt.
|
||||
* **Frontend:** Vanilla JavaScript (ES Modules), CSS Variables.
|
||||
* **Инфраструктура:** Docker, nginx (статика + реверс-прокси `/api` → backend).
|
||||
|
||||
## Быстрый старт (Docker)
|
||||
|
||||
Требования: Docker Engine + Compose plugin.
|
||||
|
||||
```bash
|
||||
git clone https://git.iovchinnikov.ru/ivan-igorevich/gym-bro.git
|
||||
cd gym-bro
|
||||
cp .env.example .env # заменить JWT_SECRET на длинную случайную строку (обязательно для прода)
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
Открыть `http://localhost` (или `http://<IP сервера>`), зарегистрироваться — и качаться.
|
||||
|
||||
* Если порт 80 на сервере занят существующим nginx: `APP_PORT=8080 docker compose up -d`.
|
||||
* База SQLite лежит в `./data/gym.db` (bind-mount, переживает пересоздание контейнеров). Есть рабочая база с другой установки — положить её в `data/gym.db` до первого запуска.
|
||||
* Фронтенд обращается к API относительно себя (`/api`), поэтому браузерная часть работает с любым хостом без правок. Для мобильного клиента адрес можно переопределить: `localStorage.setItem('gym_api_base', 'http://<сервер>/api')`.
|
||||
|
||||
## Локальная разработка (без Docker)
|
||||
|
||||
```bash
|
||||
python3 -m venv .venv && .venv/bin/pip install -r backend/requirements.txt
|
||||
cd backend && ../.venv/bin/uvicorn main:app --reload --port 8000
|
||||
```
|
||||
|
||||
Фронтенд — любой статический сервер:
|
||||
|
||||
```bash
|
||||
python3 -m http.server 8777 -d frontend
|
||||
```
|
||||
|
||||
Открыть `http://127.0.0.1:8777/demo.html` (готовый стенд с демо-данными и локальным адресом API) или `index.html`, предварительно указав API:
|
||||
|
||||
```js
|
||||
localStorage.setItem('gym_api_base', 'http://127.0.0.1:8000');
|
||||
```
|
||||
|
||||
Смоук-тест логики: `node smoke.test.mjs`.
|
||||
|
||||
## Структура проекта
|
||||
|
||||
```text
|
||||
gym-bro/
|
||||
├── backend/ # FastAPI приложение
|
||||
│ ├── routers/ # auth, workouts, exercises, metrics, sync, clients…
|
||||
│ ├── models.py # SQLAlchemy-модели
|
||||
│ ├── schemas.py # Pydantic-схемы
|
||||
│ ├── auth.py # JWT + bcrypt
|
||||
│ ├── requirements.txt
|
||||
│ └── Dockerfile
|
||||
├── frontend/ # статика (ES-модули, без сборки)
|
||||
│ ├── js/ # app.js, state.js, sync.js, logic/, modals/, render/
|
||||
│ ├── styles/
|
||||
│ ├── index.html # точка входа
|
||||
│ ├── demo.html # демо-страница для локального тестирования
|
||||
│ ├── nginx.conf # раздача статики + прокси /api
|
||||
│ └── Dockerfile
|
||||
├── sql/ # схема БД
|
||||
├── data/ # SQLite (не коммитится)
|
||||
├── docker-compose.yml
|
||||
└── .env.example # JWT_SECRET
|
||||
```
|
||||
|
||||
## Переменные окружения backend
|
||||
|
||||
| Переменная | По умолчанию | Назначение |
|
||||
|---|---|---|
|
||||
| `GYM_DB_PATH` | `./gym.db` | путь к SQLite; в compose — `/data/gym.db` |
|
||||
| `GYM_JWT_SECRET` | dev-заглушка | секрет подписи JWT, **обязательно сменить в проде** |
|
||||
| `GYM_JWT_EXPIRE_DAYS` | 30 | срок жизни токена |
|
||||
|
||||
## Безопасность
|
||||
|
||||
* Пароли — bcrypt-хэши, в БД только они.
|
||||
* Сессии — JWT (`Authorization: Bearer …`), изоляция данных по `owner_id` на уровне запросов.
|
||||
* Для продакшена обязательно задать длинный случайный `JWT_SECRET` (менее 32 байт — предупреждение от PyJWT) и закрыть HTTPS на внешнем nginx.
|
||||
|
||||
## Репозитории
|
||||
|
||||
* `iovi` — основной: <https://git.iovchinnikov.ru/ivan-igorevich/gym-bro>
|
||||
* `origin` — зеркало: <https://gitlab.com/ivan-igorevich/gym-bro>
|
||||
|
||||
---
|
||||
Made with ❤️ and heavy weights by ivan-igorevich
|
||||
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
// Смоук-тест портированной логики на реальных ES-модулях
|
||||
function mkEl() {
|
||||
const target = {
|
||||
style: {}, dataset: {}, classList: { add(){}, remove(){}, toggle(){}, contains(){ return false; } },
|
||||
innerHTML: '', textContent: '', value: '', scrollTop: 0, checked: false, disabled: false,
|
||||
appendChild(){}, removeChild(){}, setAttribute(){}, addEventListener(){}, focus(){}, select(){},
|
||||
querySelector(){ return mkEl(); }, querySelectorAll(){ return []; }, closest(){ return null; },
|
||||
getBoundingClientRect(){ return { top: 0, height: 100 }; }, dispatchEvent(){},
|
||||
};
|
||||
return new Proxy(target, {
|
||||
get(o, p) { if (p in o) return o[p]; return () => mkEl(); },
|
||||
set(o, p, v) { o[p] = v; return true; },
|
||||
});
|
||||
}
|
||||
globalThis.window = globalThis;
|
||||
const _store = {};
|
||||
globalThis.localStorage = {
|
||||
getItem: (k) => _store[k] ?? null,
|
||||
setItem: (k, v) => { _store[k] = v; },
|
||||
removeItem: (k) => { delete _store[k]; },
|
||||
clear: () => { for (const k of Object.keys(_store)) delete _store[k]; },
|
||||
};
|
||||
globalThis.document = {
|
||||
getElementById: () => mkEl(),
|
||||
createElement: () => mkEl(),
|
||||
querySelector: () => mkEl(),
|
||||
querySelectorAll: () => [],
|
||||
body: mkEl(),
|
||||
addEventListener(){},
|
||||
};
|
||||
globalThis.alert = (m) => console.log('ALERT:', m);
|
||||
globalThis.confirm = () => true;
|
||||
|
||||
const { state, loadState, saveState } = await import('./frontend/js/state.js');
|
||||
const { getExerciseHistory } = await import('./frontend/js/logic/exercise.js');
|
||||
await import('./frontend/js/logic/group.js');
|
||||
const { renderCircuit } = await import('./frontend/js/render/circuit-card.js');
|
||||
const { renderSetRow } = await import('./frontend/js/render/set-row.js');
|
||||
const { showSetDialog } = await import('./frontend/js/modals/set-modal.js');
|
||||
const { showCardioDialog } = await import('./frontend/js/modals/cardio-modal.js');
|
||||
|
||||
// ---- данные
|
||||
state.exerciseRef = [
|
||||
{ id: 'r1', name: 'Жим гантелей на лавке 30', workoutType: 'грудь-руки', group: 'жим гантелей на лавке' },
|
||||
{ id: 'r2', name: 'Жим гантелей на лавке 45', workoutType: 'грудь-руки', group: 'жим гантелей на лавке' },
|
||||
{ id: 'r3', name: 'Косичка', workoutType: 'спина-плечи', group: '' },
|
||||
];
|
||||
state.workouts = [
|
||||
{ id: '1', client_id: null, startTime: '2026-11-18T10:00:00Z', endTime: null, type: 'грудь-руки',
|
||||
exercises: [
|
||||
{ id: 'e1', name: 'Жим гантелей на лавке 30', sets: [{ id: 's1', weight: 22, reps: 12, rating: 5 }] },
|
||||
{ id: 'e2', name: 'Жим гантелей на лавке 45', sets: [{ id: 's2', weight: 24, reps: 10 }] },
|
||||
],
|
||||
cardio: [], setGroups: [], notes: '', synced: false },
|
||||
{ id: '2', client_id: null, startTime: '2026-11-10T10:00:00Z', endTime: 'x', type: 'грудь-руки',
|
||||
exercises: [{ id: 'e3', name: 'Жим гантелей на лавке 45', sets: [{ id: 's3', weight: 20, reps: 12 }] }],
|
||||
cardio: [], setGroups: [], notes: '', synced: true },
|
||||
];
|
||||
|
||||
// 1. История с группой вариантов, без текущего клиента-фильтра
|
||||
const h = getExerciseHistory('Жим гантелей на лавке 30', null, '1');
|
||||
console.log('1. история «лавка 30» (исключая тренировку 1):', h.map(x => `${x.name}@${x.date.slice(5,10)}`));
|
||||
console.assert(h.length === 1 && h[0].name.includes('45'), 'FAIL варианты не объединились');
|
||||
|
||||
// 2. Сет: создание через GL, рендер по раундам
|
||||
window.GL.showGroupDialogFor('1'); // диалог не открыть без DOM-значений — проверим напрямую
|
||||
state.workouts[0].setGroups.push({ id: 'g1', name: 'суперсет', exerciseIds: ['e1', 'e2'] });
|
||||
const w = state.workouts[0];
|
||||
const g = w.setGroups[0];
|
||||
const members = g.exerciseIds.map(id => w.exercises.find(e => e.id === id));
|
||||
const card = renderCircuit(w, g, members, false);
|
||||
console.log('2. renderCircuit ok, класс карточки:', card.className);
|
||||
|
||||
// 3. Расформирование
|
||||
window.GL.removeGroup('1', 'g1');
|
||||
console.assert(w.setGroups.length === 0, 'FAIL сет не распущен');
|
||||
console.log('3. removeGroup ok');
|
||||
|
||||
// 4. set-row: время и звёзды по умолчанию
|
||||
const row = renderSetRow('1', 'e1', { id: 'z', weight: 10, reps: 5, timestamp: '2026-11-19T08:30:00Z' }, 0, false);
|
||||
const html = row.innerHTML;
|
||||
console.assert(html.includes('11:30'), 'FAIL время не показалось');
|
||||
console.assert(html.includes('★★★★★'), 'FAIL рейтинг по умолчанию не 5');
|
||||
console.log('4. renderSetRow: время+5 звёзд ok');
|
||||
|
||||
// 5. Диалог подхода с prefill и историей не падает
|
||||
showSetDialog(null, [{ date: '2026-11-10T10:00:00Z', name: 'Жим гантелей на лавке 45', sets: [{ weight: 20, reps: 12 }] }], () => {},
|
||||
{ prefill: { weight: 22, reps: 12 }, historyLabel: 'Жим гантелей на лавке 30' });
|
||||
console.log('5. showSetDialog с prefill/вариантом ok');
|
||||
|
||||
// 6. Кардио-диалог с сортировкой не падает
|
||||
state.workouts[0].cardio.push({ type: 'бег', purpose: 'warmup' });
|
||||
showCardioDialog(null, () => {});
|
||||
console.log('6. showCardioDialog ok');
|
||||
|
||||
// 7. normalizeWorkouts через loadState
|
||||
localStorage.setItem = (() => { const s = JSON.stringify({ workouts: [{ id: '9', startTime: 'x', exercises: [{ name: 'а' }] }] }); return () => s; })();
|
||||
globalThis.localStorage = { getItem: () => JSON.stringify({ workouts: [{ id: '9', startTime: 'x', exercises: [{ name: 'а' }] }] }) };
|
||||
loadState();
|
||||
const w9 = state.workouts.find(x => x.id === '9');
|
||||
console.assert(Array.isArray(w9.setGroups) && Array.isArray(w9.exercises[0].sets), 'FAIL normalize');
|
||||
console.log('7. normalizeWorkouts ok');
|
||||
|
||||
console.log('SMOKE DONE');
|
||||
Reference in New Issue
Block a user