12 Commits

Author SHA1 Message Date
ivan-igorevich 9a987baa5c lots of work done, dashboards added 2026-11-20 01:03:35 +03:00
ivan-igorevich 2a5c9709e0 minor merge fixes 2026-10-08 21:30:21 +03:00
ivan-igorevich 459e5ff136 Merge branch 'master' of https://git.iovchinnikov.ru/ivan-igorevich/gym-bro 2026-10-08 21:23:49 +03:00
ivan-igorevich 728d342a89 docker composed 2026-10-08 00:26:42 +03:00
ivan-igorevich ea21db141a possibly auth 2026-10-03 09:44:11 +03:00
ivan-igorevich 86bcd5b141 auth begin 2026-10-03 07:51:44 +03:00
ivan-igorevich 3e966c9ff6 integrated front and back 2026-10-01 23:52:12 +03:00
ivan-igorevich 1f81632083 front-back integrated 2026-09-30 02:25:03 +03:00
ivan-igorevich 93ca76c6e1 massive frontend refactoring (works good) 2026-09-30 01:54:17 +03:00
ivan-igorevich 9203884f53 gitignore update 2026-09-30 00:21:52 +03:00
ivan-igorevich 06715f952b backend on fastapi 2026-09-30 00:21:17 +03:00
ivan-igorevich fe9221a4dd sql 2026-09-29 01:46:16 +03:00
64 changed files with 7799 additions and 2500 deletions
+9
View File
@@ -0,0 +1,9 @@
.git
__pycache__
*.pyc
node_modules
.env
data/
*.md
.vscode
.idea
+1
View File
@@ -0,0 +1 @@
JWT_SECRET=my-very-long-random-string-for-production
+2
View File
@@ -0,0 +1,2 @@
__pycache__/
*.pyc
-5
View File
@@ -1,5 +0,0 @@
A habit tracker that actually sticks.
- A handful of daily checkboxes
- Streaks without guilt
- A calm weekly review
-1100
View File
File diff suppressed because it is too large Load Diff
+18
View File
@@ -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"]
+76
View File
@@ -0,0 +1,76 @@
import os
from datetime import datetime, timedelta, timezone
from typing import Optional
import bcrypt
import jwt
from jwt.exceptions import PyJWTError
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
import database
import models
SECRET = os.getenv("GYM_JWT_SECRET", "dev-secret-change-me")
ALGORITHM = "HS256"
EXPIRE_DAYS = int(os.getenv("GYM_JWT_EXPIRE_DAYS", "30"))
bearer_scheme = HTTPBearer(auto_error=False)
def hash_password(password: str) -> str:
# 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:
# bcrypt.checkpw ожидает байты
return bcrypt.checkpw(password.encode('utf-8'), hashed.encode('utf-8'))
except ValueError:
return False
def create_access_token(user: models.User) -> str:
now = datetime.now(timezone.utc)
payload = {
"sub": str(user.id),
"username": user.username,
"iat": int(now.timestamp()),
"exp": int((now + timedelta(days=EXPIRE_DAYS)).timestamp()),
}
return jwt.encode(payload, SECRET, algorithm=ALGORITHM)
def get_current_user(
credentials: Optional[HTTPAuthorizationCredentials] = Depends(bearer_scheme),
db: Session = Depends(database.get_db),
) -> models.User:
if credentials is None or not credentials.credentials:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
)
try:
payload = jwt.decode(credentials.credentials, SECRET, algorithms=[ALGORITHM])
user_id = int(payload["sub"])
except (PyJWTError, KeyError, ValueError):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token",
)
user = db.query(models.User).filter(models.User.id == user_id).first()
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User not found",
)
return user
+22
View File
@@ -0,0 +1,22 @@
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base
# По умолчанию используем локальный файл, но в 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}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
+63
View File
@@ -0,0 +1,63 @@
#!/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
import routers.workouts
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)
app = FastAPI(
title="Gym Bro API",
description="API для трекера тренировок с офлайн-синхронизацией и авторизацией",
version="1.2.0",
)
# Для локальной разработки. В проде замени на конкретный домен фронта.
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=False,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(routers.auth.router)
app.include_router(routers.clients.router)
app.include_router(routers.workout_types.router)
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("/")
def root():
return {
"message": "Gym Bro API",
"docs": "/docs",
"version": "1.2.0",
}
@app.get("/health")
def health_check():
return {"status": "ok"}
+294
View File
@@ -0,0 +1,294 @@
from sqlalchemy import (
Column,
Integer,
String,
Float,
ForeignKey,
CheckConstraint,
UniqueConstraint,
)
from sqlalchemy.orm import relationship
from database import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
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")
created_at = Column(String)
class WorkoutType(Base):
__tablename__ = "workout_types"
id = Column(Integer, primary_key=True, index=True)
sync_id = Column(String, unique=True, nullable=False, index=True)
name = Column(String, unique=True, nullable=False)
sort_order = Column(Integer, default=0)
created_at = Column(String)
# ВАЖНО: Эта строка должна быть здесь!
exercises = relationship("Exercise", back_populates="workout_type")
# Если есть другие отношения, они тоже должны быть прописаны
workouts = relationship("Workout", back_populates="workout_type")
class Exercise(Base):
__tablename__ = "exercises"
id = Column(Integer, primary_key=True, index=True)
sync_id = Column(String, unique=True, nullable=False, index=True)
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)
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")
class Client(Base):
__tablename__ = "clients"
id = Column(Integer, primary_key=True, index=True)
sync_id = Column(String, unique=True, nullable=False, index=True)
owner_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), index=True)
full_name = Column(String, nullable=False)
birth_date = Column(String)
goal = Column(String, default="")
notes = Column(String, default="")
color = Column(String)
is_active = Column(Integer, default=1)
created_at = Column(String, default=lambda: datetime.utcnow().isoformat())
updated_at = Column(String)
workouts = relationship("Workout", back_populates="client")
body_metrics = relationship("BodyMetric", back_populates="client")
class Workout(Base):
__tablename__ = "workouts"
id = Column(Integer, primary_key=True, index=True)
sync_id = Column(String, unique=True, nullable=False, index=True)
owner_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), index=True)
client_id = Column(Integer, ForeignKey("clients.id", ondelete="SET NULL"), index=True)
workout_type_id = Column(
Integer,
ForeignKey("workout_types.id", ondelete="SET NULL"),
index=True,
)
start_time = Column(String, nullable=False)
end_time = Column(String)
notes = Column(String, default="")
synced = Column(Integer, default=0)
created_at = Column(String)
updated_at = Column(String)
client = relationship("Client", back_populates="workouts")
workout_type = relationship("WorkoutType", back_populates="workouts")
workout_exercises = relationship(
"WorkoutExercise",
back_populates="workout",
cascade="all, delete-orphan",
)
cardio_sessions = relationship(
"Cardio",
back_populates="workout",
cascade="all, delete-orphan",
)
class WorkoutExercise(Base):
__tablename__ = "workout_exercises"
id = Column(Integer, primary_key=True, index=True)
sync_id = Column(String, unique=True, nullable=False, index=True)
workout_id = Column(Integer, ForeignKey("workouts.id", ondelete="CASCADE"), index=True)
exercise_id = Column(Integer, ForeignKey("exercises.id", ondelete="SET NULL"), index=True)
exercise_name = Column(String, nullable=False, index=True)
sort_order = Column(Integer, default=0)
created_at = Column(String)
workout = relationship("Workout", back_populates="workout_exercises")
exercise = relationship("Exercise", back_populates="workout_exercises")
sets = relationship(
"Set",
back_populates="workout_exercise",
cascade="all, delete-orphan",
)
class Set(Base):
__tablename__ = "sets"
id = Column(Integer, primary_key=True, index=True)
sync_id = Column(String, unique=True, nullable=False, index=True)
workout_exercise_id = Column(
Integer,
ForeignKey("workout_exercises.id", ondelete="CASCADE"),
index=True,
)
is_dropset = Column(Integer, default=0)
weight = Column(Float)
reps = Column(Integer)
rating = Column(Integer)
notes = Column(String, default="")
sort_order = Column(Integer, default=0)
timestamp = Column(String, nullable=False)
created_at = Column(String)
workout_exercise = relationship("WorkoutExercise", back_populates="sets")
dropset_items = relationship(
"DropsetItem",
back_populates="set",
cascade="all, delete-orphan",
)
__table_args__ = (
CheckConstraint(
"(is_dropset = 0 AND weight IS NOT NULL AND reps IS NOT NULL) OR "
"(is_dropset = 1 AND weight IS NULL AND reps IS NULL)",
name="ck_sets_dropset_shape",
),
CheckConstraint(
"rating IS NULL OR (rating >= 1 AND rating <= 5)",
name="ck_sets_rating",
),
)
class DropsetItem(Base):
__tablename__ = "dropset_items"
id = Column(Integer, primary_key=True, index=True)
set_id = Column(Integer, ForeignKey("sets.id", ondelete="CASCADE"), index=True)
weight = Column(Float, nullable=False)
reps = Column(Integer, nullable=False)
sort_order = Column(Integer, default=0)
set = relationship("Set", back_populates="dropset_items")
__table_args__ = (
CheckConstraint("weight > 0", name="ck_dropset_weight_positive"),
CheckConstraint("reps > 0", name="ck_dropset_reps_positive"),
)
class Cardio(Base):
__tablename__ = "cardio"
id = Column(Integer, primary_key=True, index=True)
sync_id = Column(String, unique=True, nullable=False, index=True)
workout_id = Column(Integer, ForeignKey("workouts.id", ondelete="CASCADE"), index=True)
cardio_type = Column(String, nullable=False)
purpose = Column(String, nullable=False) # warmup | cooldown | separate | другое
duration = Column(Integer)
distance = Column(Float)
speed = Column(Float)
incline = Column(Float)
resistance = Column(Integer)
notes = Column(String, default="")
sort_order = Column(Integer, default=0)
created_at = Column(String)
workout = relationship("Workout", back_populates="cardio_sessions")
class MetricType(Base):
__tablename__ = "metric_types"
id = Column(Integer, primary_key=True, index=True)
sync_id = Column(String, unique=True, nullable=False, index=True)
name = Column(String, unique=True, nullable=False)
unit = Column(String, default="см")
category = Column(String, default="body")
sort_order = Column(Integer, default=0)
created_at = Column(String, default=lambda: datetime.utcnow().isoformat())
metric_values = relationship("BodyMetricValue", back_populates="metric_type")
class BodyMetric(Base):
__tablename__ = "body_metrics"
id = Column(Integer, primary_key=True, index=True)
sync_id = Column(String, unique=True, nullable=False, index=True)
owner_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), index=True)
client_id = Column(Integer, ForeignKey("clients.id", ondelete="SET NULL"), index=True)
metric_date = Column(String, nullable=False)
notes = Column(String, default="")
created_at = Column(String, default=lambda: datetime.utcnow().isoformat())
client = relationship("Client", back_populates="body_metrics")
values = relationship(
"BodyMetricValue",
back_populates="body_metric",
cascade="all, delete-orphan",
)
class BodyMetricValue(Base):
__tablename__ = "body_metric_values"
id = Column(Integer, primary_key=True, index=True)
body_metric_id = Column(
Integer,
ForeignKey("body_metrics.id", ondelete="CASCADE"),
index=True,
)
metric_type_id = Column(
Integer,
ForeignKey("metric_types.id", ondelete="CASCADE"),
index=True,
)
value = Column(Float, nullable=False)
body_metric = relationship("BodyMetric", back_populates="values")
metric_type = relationship("MetricType", back_populates="metric_values")
__table_args__ = (
UniqueConstraint(
"body_metric_id",
"metric_type_id",
name="uq_body_metric_value_type",
),
)
class SyncLog(Base):
__tablename__ = "sync_log"
device_id = Column(String, primary_key=True)
last_sync = Column(String, nullable=False)
updated_at = Column(String)
+7
View File
@@ -0,0 +1,7 @@
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
+106
View File
@@ -0,0 +1,106 @@
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
import auth
import database
import models
import schemas
router = APIRouter(prefix="/auth", tags=["auth"])
def get_current_timestamp() -> str:
return datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%fZ")
def user_to_out(user: models.User) -> schemas.UserOut:
return schemas.UserOut(
id=user.id,
username=user.username,
display_name=user.display_name or user.username,
role=user.role or "personal",
created_at=user.created_at or get_current_timestamp(),
)
@router.post("/register", response_model=schemas.Token)
def register(
data: schemas.UserCreate,
db: Session = Depends(database.get_db),
):
username = (data.username or "").strip().lower()
password = data.password or ""
role = data.role or "personal"
if len(username) < 3:
raise HTTPException(
status_code=400,
detail="Username must be at least 3 characters",
)
if len(password) < 6:
raise HTTPException(
status_code=400,
detail="Password must be at least 6 characters",
)
if role not in ("personal", "trainer"):
role = "personal"
exists = db.query(models.User).filter(models.User.username == username).first()
if exists:
raise HTTPException(status_code=400, detail="Username already exists")
user = models.User(
username=username,
password_hash=auth.hash_password(password),
display_name=(data.display_name or username).strip(),
role=role,
created_at=get_current_timestamp(),
)
db.add(user)
db.commit()
db.refresh(user)
token = auth.create_access_token(user)
return schemas.Token(
access_token=token,
token_type="bearer",
user=user_to_out(user),
)
@router.post("/login", response_model=schemas.Token)
def login(
data: schemas.UserLogin,
db: Session = Depends(database.get_db),
):
username = (data.username or "").strip().lower()
password = data.password or ""
user = db.query(models.User).filter(models.User.username == username).first()
if not user:
raise HTTPException(status_code=401, detail="Invalid username or password")
if not auth.verify_password(password, user.password_hash):
raise HTTPException(status_code=401, detail="Invalid username or password")
token = auth.create_access_token(user)
return schemas.Token(
access_token=token,
token_type="bearer",
user=user_to_out(user),
)
@router.get("/me", response_model=schemas.UserOut)
def me(
current_user: models.User = Depends(auth.get_current_user),
):
return user_to_out(current_user)
+157
View File
@@ -0,0 +1,157 @@
# backend/routers/bootstrap.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session, joinedload
from sqlalchemy import or_
import auth
import database
import models
import schemas
router = APIRouter(
prefix="/bootstrap",
tags=["bootstrap"],
dependencies=[Depends(auth.get_current_user)],
)
@router.get("/")
def get_bootstrap_data(
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
"""
Возвращает ВСЕ данные пользователя для инициализации фронтенда.
Безопасная версия с проверкой NULL-связей.
"""
try:
# 1. Типы тренировок (глобальные)
workout_types = db.query(models.WorkoutType).order_by(models.WorkoutType.sort_order).all()
# 2. Типы замеров (глобальные)
metric_types = db.query(models.MetricType).order_by(models.MetricType.sort_order).all()
# 3. Клиенты пользователя
clients = db.query(models.Client).filter(models.Client.owner_id == current_user.id).all()
# 4. Упражнения пользователя + глобальные
exercises = db.query(models.Exercise).filter(
or_(
models.Exercise.owner_id == current_user.id,
models.Exercise.owner_id.is_(None)
)
).all()
# 5. Тренировки пользователя (полные, с подходами и кардио)
workouts = db.query(models.Workout).options(
joinedload(models.Workout.workout_exercises).joinedload(models.WorkoutExercise.sets).joinedload(models.Set.dropset_items),
joinedload(models.Workout.cardio_sessions),
joinedload(models.Workout.client), # Загружаем клиента, если есть
joinedload(models.Workout.workout_type) # Загружаем тип тренировки
).filter(
models.Workout.owner_id == current_user.id
).order_by(models.Workout.start_time.desc()).all()
# 6. Замеры пользователя
body_metrics = db.query(models.BodyMetric).options(
joinedload(models.BodyMetric.values),
joinedload(models.BodyMetric.client) # Если нужно имя клиента в замерах
).filter(
models.BodyMetric.owner_id == current_user.id
).order_by(models.BodyMetric.metric_date.desc()).all()
# --- Ручная конвертация в словари, чтобы избежать ошибок Pydantic/SQLAlchemy lazy-loading ---
def serialize_workout(w):
wt_name = w.workout_type.name if w.workout_type else ""
client_name = w.client.full_name if w.client else None
return {
"id": w.id,
"sync_id": w.sync_id,
"owner_id": w.owner_id,
"client_id": w.client_id,
"workout_type_id": w.workout_type_id,
"start_time": w.start_time,
"end_time": w.end_time,
"notes": w.notes,
"synced": w.synced,
"created_at": w.created_at,
"updated_at": w.updated_at,
# Дополнительные поля для фронта
"workout_type_name": wt_name,
"client_full_name": client_name,
"workout_exercises": [
{
"id": ex.id,
"sync_id": ex.sync_id,
"exercise_name": ex.exercise_name,
"sort_order": ex.sort_order,
"sets": [
{
"id": s.id,
"sync_id": s.sync_id,
"is_dropset": s.is_dropset,
"weight": s.weight,
"reps": s.reps,
"rating": s.rating,
"notes": s.notes,
"timestamp": s.timestamp,
"dropset_items": [
{
"id": di.id,
"weight": di.weight,
"reps": di.reps,
"sort_order": di.sort_order
} for di in (s.dropset_items or [])
]
} for s in (ex.sets or [])
]
} for ex in (w.workout_exercises or [])
],
"cardio_sessions": [
{
"id": c.id,
"sync_id": c.sync_id,
"cardio_type": c.cardio_type,
"purpose": c.purpose,
"duration": c.duration,
"distance": c.distance,
"speed": c.speed,
"incline": c.incline,
"resistance": c.resistance,
"notes": c.notes,
"sort_order": c.sort_order
} for c in (w.cardio_sessions or [])
]
}
def serialize_metric(m):
return {
"id": m.id,
"sync_id": m.sync_id,
"client_id": m.client_id,
"metric_date": m.metric_date,
"notes": m.notes,
"values": [
{
"id": v.id,
"metric_type_id": v.metric_type_id,
"value": v.value
} for v in (m.values or [])
]
}
return {
"workout_types": [{"id": t.id, "sync_id": t.sync_id, "name": t.name, "sort_order": t.sort_order} for t in workout_types],
"metric_types": [{"id": t.id, "sync_id": t.sync_id, "name": t.name, "unit": t.unit, "category": t.category, "sort_order": t.sort_order} for t in metric_types],
"clients": [{"id": c.id, "sync_id": c.sync_id, "full_name": c.full_name, "birth_date": c.birth_date, "goal": c.goal, "color": c.color} for c in clients],
"exercises": [{"id": e.id, "sync_id": e.sync_id, "name": e.name, "workout_type_id": e.workout_type_id} for e in exercises],
"workouts": [serialize_workout(w) for w in workouts],
"body_metrics": [serialize_metric(m) for m in body_metrics],
}
except Exception as e:
print(f"❌ CRITICAL ERROR IN BOOTSTRAP: {e}")
raise HTTPException(status_code=500, detail=str(e))
+149
View File
@@ -0,0 +1,149 @@
import uuid
from datetime import datetime
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
import auth
import database
import models
import schemas
router = APIRouter(
prefix="/clients",
tags=["clients"],
dependencies=[Depends(auth.get_current_user)],
)
DEFAULT_CLIENT_COLOR = "#bb86fc"
def get_current_timestamp() -> str:
return datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%fZ")
def new_sync_id() -> str:
return uuid.uuid4().hex
def get_owned_client(
db: Session,
client_id: int,
user: models.User,
) -> models.Client:
client = (
db.query(models.Client)
.filter(
models.Client.id == client_id,
models.Client.owner_id == user.id,
)
.first()
)
if not client:
raise HTTPException(status_code=404, detail="Client not found")
return client
@router.post("/", response_model=schemas.ClientOut)
def create_client(
client: schemas.ClientCreate,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
sync_id = client.sync_id or new_sync_id()
timestamp = get_current_timestamp()
existing = db.query(models.Client).filter(models.Client.sync_id == sync_id).first()
if existing:
if existing.owner_id != current_user.id:
raise HTTPException(status_code=409, detail="Client sync_id belongs to another user")
existing.full_name = client.full_name
existing.birth_date = client.birth_date
existing.goal = client.goal or ""
existing.notes = client.notes or ""
existing.color = client.color or existing.color or DEFAULT_CLIENT_COLOR
existing.is_active = client.is_active if client.is_active is not None else existing.is_active
existing.updated_at = timestamp
db.commit()
db.refresh(existing)
return existing
db_client = models.Client(
sync_id=sync_id,
owner_id=current_user.id,
full_name=client.full_name,
birth_date=client.birth_date,
goal=client.goal or "",
notes=client.notes or "",
color=client.color or DEFAULT_CLIENT_COLOR,
is_active=client.is_active if client.is_active is not None else 1,
created_at=timestamp,
updated_at=timestamp,
)
db.add(db_client)
db.commit()
db.refresh(db_client)
return db_client
@router.get("/", response_model=List[schemas.ClientOut])
def list_clients(
skip: int = 0,
limit: int = 100,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
return (
db.query(models.Client)
.filter(models.Client.owner_id == current_user.id)
.order_by(models.Client.full_name)
.offset(skip)
.limit(limit)
.all()
)
@router.get("/{client_id}", response_model=schemas.ClientOut)
def get_client(
client_id: int,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
return get_owned_client(db, client_id, current_user)
@router.put("/{client_id}", response_model=schemas.ClientOut)
def update_client(
client_id: int,
client: schemas.ClientUpdate,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
db_client = get_owned_client(db, client_id, current_user)
update_data = client.dict(exclude_unset=True)
for key, value in update_data.items():
setattr(db_client, key, value)
db_client.updated_at = get_current_timestamp()
db.commit()
db.refresh(db_client)
return db_client
@router.delete("/{client_id}")
def delete_client(
client_id: int,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
db_client = get_owned_client(db, client_id, current_user)
db.delete(db_client)
db.commit()
return {"status": "deleted"}
+305
View File
@@ -0,0 +1,305 @@
import uuid
from datetime import datetime
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import func, or_
from sqlalchemy.orm import Session, joinedload
import auth
import database
import models
import schemas
router = APIRouter(
prefix="/exercises",
tags=["exercises"],
dependencies=[Depends(auth.get_current_user)],
)
def get_current_timestamp() -> str:
return datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%fZ")
def new_sync_id() -> str:
return uuid.uuid4().hex
def normalize_name(name: str) -> str:
return (name or "").strip().lower()
def find_exercise_by_name(
db: Session,
user: models.User,
name: str,
) -> Optional[models.Exercise]:
n = normalize_name(name)
if not n:
return None
owned = (
db.query(models.Exercise)
.filter(
models.Exercise.owner_id == user.id,
func.lower(models.Exercise.name) == n,
)
.first()
)
if owned:
return owned
return (
db.query(models.Exercise)
.filter(
models.Exercise.owner_id.is_(None),
func.lower(models.Exercise.name) == n,
)
.first()
)
def get_owned_exercise(
db: Session,
exercise_id: int,
user: models.User,
) -> models.Exercise:
exercise = (
db.query(models.Exercise)
.filter(
models.Exercise.id == exercise_id,
models.Exercise.owner_id == user.id,
)
.first()
)
if not exercise:
raise HTTPException(status_code=404, detail="Exercise not found")
return exercise
@router.post("/", response_model=schemas.ExerciseOut)
def create_exercise(
exercise: schemas.ExerciseCreate,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
sync_id = exercise.sync_id or new_sync_id()
timestamp = get_current_timestamp()
existing = db.query(models.Exercise).filter(models.Exercise.sync_id == sync_id).first()
if existing:
if existing.owner_id is not None and existing.owner_id != current_user.id:
raise HTTPException(status_code=409, detail="Exercise sync_id belongs to another user")
if existing.owner_id == current_user.id:
existing.name = exercise.name
existing.workout_type_id = exercise.workout_type_id
existing.updated_at = timestamp
db.commit()
db.refresh(existing)
return existing
# Глобальное упражнение — не даём пользователю его менять, просто возвращаем
return existing
by_name = find_exercise_by_name(db, current_user, exercise.name)
if by_name:
if by_name.owner_id == current_user.id:
by_name.sync_id = by_name.sync_id or sync_id
by_name.workout_type_id = exercise.workout_type_id
by_name.updated_at = timestamp
db.commit()
db.refresh(by_name)
return by_name
# Нашли глобальное с таким же именем — используем его
return by_name
db_exercise = models.Exercise(
sync_id=sync_id,
owner_id=current_user.id,
name=exercise.name.strip(),
workout_type_id=exercise.workout_type_id,
created_at=timestamp,
updated_at=timestamp,
)
db.add(db_exercise)
db.commit()
db.refresh(db_exercise)
return db_exercise
@router.get("/", response_model=List[schemas.ExerciseOut])
def list_exercises(
workout_type_id: Optional[int] = None,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
query = db.query(models.Exercise).filter(
or_(
models.Exercise.owner_id == current_user.id,
models.Exercise.owner_id.is_(None),
)
)
if workout_type_id:
query = query.filter(models.Exercise.workout_type_id == workout_type_id)
return query.order_by(models.Exercise.name).all()
@router.get("/history/{exercise_name}")
def get_exercise_history(
exercise_name: str,
client_id: Optional[int] = None,
limit: int = 10,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
"""
Возвращает историю упражнения для текущего пользователя.
Если указан client_id — только тренировки этого клиента.
"""
normalized = normalize_name(exercise_name)
workout_query = (
db.query(models.Workout.id)
.join(models.WorkoutExercise, models.WorkoutExercise.workout_id == models.Workout.id)
.filter(
models.Workout.owner_id == current_user.id,
models.Workout.end_time.isnot(None),
func.lower(models.WorkoutExercise.exercise_name) == normalized,
)
)
if client_id:
client = (
db.query(models.Client)
.filter(
models.Client.id == client_id,
models.Client.owner_id == current_user.id,
)
.first()
)
if not client:
raise HTTPException(status_code=404, detail="Client not found")
workout_query = workout_query.filter(models.Workout.client_id == client_id)
workout_ids = [
row[0]
for row in workout_query.order_by(models.Workout.start_time.desc()).limit(limit).all()
]
if not workout_ids:
return []
workouts = (
db.query(models.Workout)
.options(
joinedload(models.Workout.workout_exercises)
.joinedload(models.WorkoutExercise.sets)
.joinedload(models.Set.dropset_items)
)
.filter(models.Workout.id.in_(workout_ids))
.order_by(models.Workout.start_time.desc())
.all()
)
result = []
for workout in workouts:
for we in workout.workout_exercises or []:
if normalize_name(we.exercise_name) != normalized:
continue
sets_payload = []
for s in we.sets or []:
sets_payload.append(
{
"is_dropset": bool(s.is_dropset),
"weight": s.weight,
"reps": s.reps,
"rating": s.rating,
"notes": s.notes or "",
"timestamp": s.timestamp,
"dropset_items": [
{
"weight": di.weight,
"reps": di.reps,
"sort_order": di.sort_order,
}
for di in (s.dropset_items or [])
],
}
)
if sets_payload:
result.append(
{
"workout_sync_id": workout.sync_id,
"date": workout.start_time,
"client_id": workout.client_id,
"exercise_name": we.exercise_name,
"sets": sets_payload,
}
)
return result
@router.get("/{exercise_id}", response_model=schemas.ExerciseOut)
def get_exercise(
exercise_id: int,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
exercise = (
db.query(models.Exercise)
.filter(
or_(
models.Exercise.id == exercise_id,
),
or_(
models.Exercise.owner_id == current_user.id,
models.Exercise.owner_id.is_(None),
),
)
.first()
)
if not exercise:
raise HTTPException(status_code=404, detail="Exercise not found")
return exercise
@router.put("/{exercise_id}", response_model=schemas.ExerciseOut)
def update_exercise(
exercise_id: int,
exercise: schemas.ExerciseUpdate,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
db_exercise = get_owned_exercise(db, exercise_id, current_user)
update_data = exercise.dict(exclude_unset=True)
for key, value in update_data.items():
setattr(db_exercise, key, value)
db_exercise.updated_at = get_current_timestamp()
db.commit()
db.refresh(db_exercise)
return db_exercise
@router.delete("/{exercise_id}")
def delete_exercise(
exercise_id: int,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
db_exercise = get_owned_exercise(db, exercise_id, current_user)
db.delete(db_exercise)
db.commit()
return {"status": "deleted"}
+284
View File
@@ -0,0 +1,284 @@
import uuid
from datetime import datetime
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session, joinedload
import auth
import database
import models
import schemas
router = APIRouter(
tags=["metrics"],
dependencies=[Depends(auth.get_current_user)],
)
def get_current_timestamp() -> str:
return datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%fZ")
def new_sync_id() -> str:
return uuid.uuid4().hex
def get_owned_client(
db: Session,
client_id: int,
user: models.User,
) -> models.Client:
client = (
db.query(models.Client)
.filter(
models.Client.id == client_id,
models.Client.owner_id == user.id,
)
.first()
)
if not client:
raise HTTPException(status_code=404, detail="Client not found")
return client
def resolve_metric_type(
db: Session,
value: schemas.BodyMetricValueCreate,
) -> Optional[models.MetricType]:
if value.metric_type_id:
return db.get(models.MetricType, value.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()
)
return None
# ============================================================
# METRIC TYPES
# ============================================================
@router.post("/metric-types/", response_model=schemas.MetricTypeOut)
def create_metric_type(
metric_type: schemas.MetricTypeCreate,
db: Session = Depends(database.get_db),
):
sync_id = metric_type.sync_id or new_sync_id()
existing = db.query(models.MetricType).filter(models.MetricType.sync_id == sync_id).first()
if existing:
existing.name = metric_type.name
existing.unit = metric_type.unit or existing.unit
existing.category = metric_type.category or existing.category
existing.sort_order = metric_type.sort_order if metric_type.sort_order is not None else existing.sort_order
db.commit()
db.refresh(existing)
return existing
db_mt = models.MetricType(
sync_id=sync_id,
name=metric_type.name,
unit=metric_type.unit or "см",
category=metric_type.category or "body",
sort_order=metric_type.sort_order or 0,
created_at=get_current_timestamp(),
)
db.add(db_mt)
db.commit()
db.refresh(db_mt)
return db_mt
@router.get("/metric-types/", response_model=List[schemas.MetricTypeOut])
def list_metric_types(db: Session = Depends(database.get_db)):
return db.query(models.MetricType).order_by(
models.MetricType.sort_order,
models.MetricType.name,
).all()
# ============================================================
# BODY METRICS
# ============================================================
@router.post("/body-metrics/", response_model=schemas.BodyMetricOut)
def create_body_metric(
metric: schemas.BodyMetricCreate,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
sync_id = metric.sync_id or new_sync_id()
timestamp = get_current_timestamp()
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.metric_date
existing.notes = metric.notes or ""
existing.client_id = metric.client_id
db.query(models.BodyMetricValue).filter(
models.BodyMetricValue.body_metric_id == existing.id
).delete()
for value in metric.values or []:
mt = resolve_metric_type(db, value)
if not mt:
raise HTTPException(status_code=422, detail="Metric type not found")
db.add(
models.BodyMetricValue(
body_metric_id=existing.id,
metric_type_id=mt.id,
value=value.value,
)
)
db.commit()
db.refresh(existing)
return existing
client_id = metric.client_id
if client_id:
get_owned_client(db, client_id, current_user)
db_metric = models.BodyMetric(
sync_id=sync_id,
owner_id=current_user.id,
client_id=client_id,
metric_date=metric.metric_date,
notes=metric.notes or "",
created_at=timestamp,
)
db.add(db_metric)
db.flush()
for value in metric.values or []:
mt = resolve_metric_type(db, value)
if not mt:
raise HTTPException(status_code=422, detail="Metric type not found")
db.add(
models.BodyMetricValue(
body_metric_id=db_metric.id,
metric_type_id=mt.id,
value=value.value,
)
)
db.commit()
db.refresh(db_metric)
return db_metric
@router.get("/body-metrics/", response_model=List[schemas.BodyMetricOut])
def list_body_metrics(
client_id: Optional[int] = None,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
query = db.query(models.BodyMetric).options(
joinedload(models.BodyMetric.values)
).filter(
models.BodyMetric.owner_id == current_user.id
)
if client_id:
get_owned_client(db, client_id, current_user)
query = query.filter(models.BodyMetric.client_id == client_id)
return query.order_by(models.BodyMetric.metric_date.desc()).all()
@router.get("/body-metrics/history")
def get_metric_history(
client_id: int,
metric_type_id: int,
limit: int = 50,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
get_owned_client(db, client_id, current_user)
metric_type = db.get(models.MetricType, metric_type_id)
if not metric_type:
raise HTTPException(status_code=404, detail="Metric type not found")
results = (
db.query(
models.BodyMetric.metric_date,
models.BodyMetricValue.value,
)
.join(
models.BodyMetricValue,
models.BodyMetricValue.body_metric_id == models.BodyMetric.id,
)
.filter(
models.BodyMetric.owner_id == current_user.id,
models.BodyMetric.client_id == client_id,
models.BodyMetricValue.metric_type_id == metric_type_id,
)
.order_by(models.BodyMetric.metric_date.desc())
.limit(limit)
.all()
)
return [
{
"date": r.metric_date,
"value": r.value,
"metric_type_id": metric_type_id,
"metric_type_name": metric_type.name,
"unit": metric_type.unit,
}
for r in results
]
@router.get("/body-metrics/{metric_id}", response_model=schemas.BodyMetricOut)
def get_body_metric(
metric_id: int,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
metric = (
db.query(models.BodyMetric)
.options(joinedload(models.BodyMetric.values))
.filter(
models.BodyMetric.id == metric_id,
models.BodyMetric.owner_id == current_user.id,
)
.first()
)
if not metric:
raise HTTPException(status_code=404, detail="Body metric not found")
return metric
@router.delete("/body-metrics/{metric_id}")
def delete_body_metric(
metric_id: int,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
metric = (
db.query(models.BodyMetric)
.filter(
models.BodyMetric.id == metric_id,
models.BodyMetric.owner_id == current_user.id,
)
.first()
)
if not metric:
raise HTTPException(status_code=404, detail="Body metric not found")
db.delete(metric)
db.commit()
return {"status": "deleted"}
+561
View File
@@ -0,0 +1,561 @@
import uuid
from datetime import datetime
from typing import Dict, Optional, Tuple
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import func
from sqlalchemy.orm import Session
import auth
import database
import models
import schemas
router = APIRouter(
prefix="/sync",
tags=["sync"],
dependencies=[Depends(auth.get_current_user)],
)
DEFAULT_CLIENT_COLOR = "#bb86fc"
def get_current_timestamp() -> str:
return datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%fZ")
def new_sync_id() -> str:
return uuid.uuid4().hex
def normalize_name(name: str) -> str:
return (name or "").strip().lower()
def resolve_workout_type_id(
db: Session,
workout_type_id: Optional[int],
) -> Optional[int]:
if not workout_type_id:
return None
wt = db.get(models.WorkoutType, workout_type_id)
return wt.id if wt else None
def upsert_client(
db: Session,
user: models.User,
data: schemas.ClientCreate,
timestamp: str,
) -> Tuple[models.Client, str]:
sync_id = data.sync_id or new_sync_id()
existing = db.query(models.Client).filter(models.Client.sync_id == sync_id).first()
if existing:
if existing.owner_id != user.id:
raise HTTPException(status_code=409, detail="Client sync_id belongs to another user")
existing.full_name = data.full_name
existing.birth_date = data.birth_date
existing.goal = data.goal or ""
existing.notes = data.notes or ""
existing.color = data.color or existing.color or DEFAULT_CLIENT_COLOR
existing.is_active = data.is_active if data.is_active is not None else existing.is_active
existing.updated_at = timestamp
db.flush()
return existing, "updated"
obj = models.Client(
sync_id=sync_id,
owner_id=user.id,
full_name=data.full_name,
birth_date=data.birth_date,
goal=data.goal or "",
notes=data.notes or "",
color=data.color or DEFAULT_CLIENT_COLOR,
is_active=data.is_active if data.is_active is not None else 1,
created_at=timestamp,
updated_at=timestamp,
)
db.add(obj)
db.flush()
return obj, "created"
def find_exercise_by_name(
db: Session,
user: models.User,
name: str,
) -> Optional[models.Exercise]:
n = normalize_name(name)
if not n:
return None
owned = (
db.query(models.Exercise)
.filter(
models.Exercise.owner_id == user.id,
func.lower(models.Exercise.name) == n,
)
.first()
)
if owned:
return owned
return (
db.query(models.Exercise)
.filter(
models.Exercise.owner_id.is_(None),
func.lower(models.Exercise.name) == n,
)
.first()
)
def upsert_exercise(
db: Session,
user: models.User,
data: schemas.ExerciseCreate,
timestamp: str,
) -> Tuple[models.Exercise, str]:
sync_id = data.sync_id or new_sync_id()
workout_type_id = resolve_workout_type_id(db, data.workout_type_id)
existing = db.query(models.Exercise).filter(models.Exercise.sync_id == sync_id).first()
if existing:
if existing.owner_id is not None and existing.owner_id != user.id:
raise HTTPException(status_code=409, detail="Exercise sync_id belongs to another user")
if existing.owner_id == user.id:
existing.name = (data.name or existing.name).strip()
existing.workout_type_id = workout_type_id
existing.updated_at = timestamp
db.flush()
return existing, "updated"
# Глобальное упражнение: не обновляем, просто переиспользуем
return existing, "global"
by_name = find_exercise_by_name(db, user, data.name)
if by_name:
if by_name.owner_id == user.id:
by_name.sync_id = by_name.sync_id or sync_id
by_name.name = (data.name or by_name.name).strip()
by_name.workout_type_id = workout_type_id
by_name.updated_at = timestamp
db.flush()
return by_name, "updated"
# Нашли глобальное с тем же именем
return by_name, "global"
obj = models.Exercise(
sync_id=sync_id,
owner_id=user.id,
name=(data.name or "Без названия").strip(),
workout_type_id=workout_type_id,
created_at=timestamp,
updated_at=timestamp,
)
db.add(obj)
db.flush()
return obj, "created"
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]
# 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
def resolve_exercise_id(
db: Session,
user: models.User,
exercise_sync_id: Optional[str],
exercise_name: Optional[str],
exercise_map: Dict[str, int],
) -> Optional[int]:
if exercise_sync_id:
if exercise_sync_id in exercise_map:
return exercise_map[exercise_sync_id]
ex = db.query(models.Exercise).filter(models.Exercise.sync_id == exercise_sync_id).first()
if ex and (ex.owner_id is None or ex.owner_id == user.id):
return ex.id
if exercise_name:
ex = find_exercise_by_name(db, user, exercise_name)
if ex:
return ex.id
return None
def create_set_from_payload(
db: Session,
workout_exercise_id: int,
data: schemas.SetCreate,
timestamp: str,
warnings: list,
) -> models.Set:
is_dropset = 1 if data.is_dropset else 0
if is_dropset:
if data.weight is not None or data.reps is not None:
warnings.append("Dropset top-level weight/reps ignored")
data.weight = None
data.reps = None
if not data.dropset_items:
raise HTTPException(status_code=422, detail="Dropset must have items")
else:
if data.weight is None or data.reps is None:
raise HTTPException(status_code=422, detail="Regular set must have weight and reps")
db_set = models.Set(
sync_id=data.sync_id or new_sync_id(),
workout_exercise_id=workout_exercise_id,
is_dropset=is_dropset,
weight=None if is_dropset else float(data.weight),
reps=None if is_dropset else int(data.reps),
rating=data.rating or 3,
notes=data.notes or "",
sort_order=data.sort_order or 0,
timestamp=data.timestamp or timestamp,
created_at=timestamp,
)
db.add(db_set)
db.flush()
if is_dropset:
for idx, item in enumerate(data.dropset_items or []):
db.add(
models.DropsetItem(
set_id=db_set.id,
weight=float(item.weight),
reps=int(item.reps),
sort_order=item.sort_order if item.sort_order is not None else idx,
)
)
return db_set
def create_cardio_from_payload(
db: Session,
workout_id: int,
data: schemas.CardioCreate,
timestamp: str,
) -> models.Cardio:
db_cardio = models.Cardio(
sync_id=data.sync_id or new_sync_id(),
workout_id=workout_id,
cardio_type=data.cardio_type,
purpose=data.purpose,
duration=data.duration,
distance=data.distance,
speed=data.speed,
incline=data.incline,
resistance=data.resistance,
notes=data.notes or "",
sort_order=data.sort_order or 0,
created_at=timestamp,
)
db.add(db_cardio)
return db_cardio
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_data.metric_type_sync_id:
return db.query(models.MetricType).filter(
models.MetricType.sync_id == value_data.metric_type_sync_id
).first()
return None
@router.post("/", response_model=schemas.SyncResponse)
def sync_data(
payload: schemas.SyncPayload,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
timestamp = get_current_timestamp()
warnings = []
created = {
"clients": 0,
"exercises": 0,
"workouts": 0,
"body_metrics": 0,
}
updated = {
"clients": 0,
"exercises": 0,
"workouts": 0,
"body_metrics": 0,
}
client_map: Dict[str, int] = {}
exercise_map: Dict[str, int] = {}
# ========================================================
# 1. Clients
# ========================================================
for client_data in payload.clients or []:
obj, status = upsert_client(db, current_user, client_data, timestamp)
client_map[obj.sync_id] = obj.id
if status == "created":
created["clients"] += 1
elif status == "updated":
updated["clients"] += 1
# ========================================================
# 2. Exercises
# ========================================================
for exercise_data in payload.exercises or []:
obj, status = upsert_exercise(db, current_user, exercise_data, timestamp)
exercise_map[obj.sync_id] = obj.id
if status == "created":
created["exercises"] += 1
elif status == "updated":
updated["exercises"] += 1
# ========================================================
# 3. Workouts
# ========================================================
for workout_data in payload.workouts or []:
sync_id = workout_data.sync_id or new_sync_id()
existing = db.query(models.Workout).filter(models.Workout.sync_id == sync_id).first()
if existing:
if existing.owner_id != current_user.id:
raise HTTPException(status_code=409, detail="Workout sync_id belongs to another user")
existing.start_time = workout_data.start_time or existing.start_time
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)
existing.synced = 1
existing.updated_at = timestamp
updated["workouts"] += 1
continue
client_id = resolve_client_id_from_sync_id(
db,
current_user,
workout_data.client_sync_id,
client_map,
)
if workout_data.client_id and not client_id:
client = (
db.query(models.Client)
.filter(
models.Client.id == workout_data.client_id,
models.Client.owner_id == current_user.id,
)
.first()
)
client_id = client.id if client else None
if workout_data.client_sync_id and not client_id:
warnings.append(
f"Client sync_id {workout_data.client_sync_id} not found for workout {sync_id}"
)
db_workout = models.Workout(
sync_id=sync_id,
owner_id=current_user.id,
client_id=client_id,
workout_type_id=resolve_workout_type_id(db, workout_data.workout_type_id),
start_time=workout_data.start_time,
end_time=workout_data.end_time,
notes=workout_data.notes or "",
synced=1,
created_at=timestamp,
updated_at=timestamp,
)
db.add(db_workout)
db.flush()
created["workouts"] += 1
for we_data in workout_data.workout_exercises or []:
exercise_id = resolve_exercise_id(
db,
current_user,
we_data.exercise_sync_id,
we_data.exercise_name,
exercise_map,
)
db_we = models.WorkoutExercise(
sync_id=we_data.sync_id or new_sync_id(),
workout_id=db_workout.id,
exercise_id=exercise_id,
exercise_name=we_data.exercise_name,
sort_order=we_data.sort_order or 0,
created_at=timestamp,
)
db.add(db_we)
db.flush()
for set_data in we_data.sets or []:
create_set_from_payload(db, db_we.id, set_data, timestamp, warnings)
for cardio_data in workout_data.cardio_sessions or []:
create_cardio_from_payload(db, db_workout.id, cardio_data, timestamp)
# ========================================================
# 4. Body metrics
# ========================================================
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
)
# Если client_id не найден по sync_id, пробуем по числовому ID из payload
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
existing.client_id = client_id
# Удаляем старые значения перед добавлением новых
db.query(models.BodyMetricValue).filter(
models.BodyMetricValue.body_metric_id == existing.id
).delete(synchronize_session=False)
# Добавляем новые значения
for value_data in metric_data.values or []:
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),
)
)
except Exception as e:
warnings.append(f"BodyMetric {sync_id}: Error adding value - {str(e)}")
updated["body_metrics"] += 1
continue
else:
# --- СОЗДАНИЕ НОВОГО ЗАМЕРА ---
# Резолвим 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,
warnings=warnings,
)
+62
View File
@@ -0,0 +1,62 @@
import uuid
from datetime import datetime
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
import auth
import database
import models
import schemas
router = APIRouter(
prefix="/workout-types",
tags=["workout-types"],
dependencies=[Depends(auth.get_current_user)],
)
def get_current_timestamp() -> str:
return datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%fZ")
def new_sync_id() -> str:
return uuid.uuid4().hex
@router.post("/", response_model=schemas.WorkoutTypeOut)
def create_workout_type(
wt: schemas.WorkoutTypeCreate,
db: Session = Depends(database.get_db),
):
sync_id = wt.sync_id or new_sync_id()
existing = db.query(models.WorkoutType).filter(models.WorkoutType.sync_id == sync_id).first()
if existing:
existing.name = wt.name
existing.sort_order = wt.sort_order if wt.sort_order is not None else existing.sort_order
db.commit()
db.refresh(existing)
return existing
db_wt = models.WorkoutType(
sync_id=sync_id,
name=wt.name,
sort_order=wt.sort_order or 0,
created_at=get_current_timestamp(),
)
db.add(db_wt)
db.commit()
db.refresh(db_wt)
return db_wt
@router.get("/", response_model=List[schemas.WorkoutTypeOut])
def list_workout_types(db: Session = Depends(database.get_db)):
return db.query(models.WorkoutType).order_by(
models.WorkoutType.sort_order,
models.WorkoutType.name,
).all()
+294
View File
@@ -0,0 +1,294 @@
import uuid
from datetime import datetime
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session, joinedload
import auth
import database
import models
import schemas
router = APIRouter(
prefix="/workouts",
tags=["workouts"],
dependencies=[Depends(auth.get_current_user)],
)
def get_current_timestamp() -> str:
return datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%fZ")
def new_sync_id() -> str:
return uuid.uuid4().hex
def get_owned_workout(
db: Session,
workout_id: int,
user: models.User,
) -> models.Workout:
workout = (
db.query(models.Workout)
.filter(
models.Workout.id == workout_id,
models.Workout.owner_id == user.id,
)
.first()
)
if not workout:
raise HTTPException(status_code=404, detail="Workout not found")
return workout
def validate_client(
db: Session,
client_id: Optional[int],
user: models.User,
) -> Optional[int]:
if not client_id:
return None
client = (
db.query(models.Client)
.filter(
models.Client.id == client_id,
models.Client.owner_id == user.id,
)
.first()
)
if not client:
raise HTTPException(status_code=404, detail="Client not found")
return client.id
def validate_workout_type(
db: Session,
workout_type_id: Optional[int],
) -> Optional[int]:
if not workout_type_id:
return None
wt = db.get(models.WorkoutType, workout_type_id)
if not wt:
raise HTTPException(status_code=422, detail="Workout type not found")
return wt.id
def create_set_record(
db: Session,
workout_exercise_id: int,
set_data: schemas.SetCreate,
timestamp: str,
) -> models.Set:
is_dropset = 1 if set_data.is_dropset else 0
if is_dropset:
if set_data.weight is not None or set_data.reps is not None:
raise HTTPException(
status_code=422,
detail="Dropset must not have top-level weight/reps",
)
if not set_data.dropset_items:
raise HTTPException(
status_code=422,
detail="Dropset must have at least one dropset item",
)
else:
if set_data.weight is None or set_data.reps is None:
raise HTTPException(
status_code=422,
detail="Regular set must have weight and reps",
)
db_set = models.Set(
sync_id=set_data.sync_id or new_sync_id(),
workout_exercise_id=workout_exercise_id,
is_dropset=is_dropset,
weight=None if is_dropset else float(set_data.weight),
reps=None if is_dropset else int(set_data.reps),
rating=set_data.rating or 3,
notes=set_data.notes or "",
sort_order=set_data.sort_order or 0,
timestamp=set_data.timestamp or timestamp,
created_at=timestamp,
)
db.add(db_set)
db.flush()
if is_dropset:
for idx, item in enumerate(set_data.dropset_items or []):
db.add(
models.DropsetItem(
set_id=db_set.id,
weight=float(item.weight),
reps=int(item.reps),
sort_order=item.sort_order if item.sort_order is not None else idx,
)
)
return db_set
@router.post("/", response_model=schemas.WorkoutOut)
def create_workout(
workout: schemas.WorkoutCreate,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
timestamp = get_current_timestamp()
sync_id = workout.sync_id or new_sync_id()
existing = db.query(models.Workout).filter(models.Workout.sync_id == sync_id).first()
if existing:
if existing.owner_id != current_user.id:
raise HTTPException(status_code=409, detail="Workout sync_id belongs to another user")
return existing
client_id = validate_client(db, workout.client_id, current_user)
workout_type_id = validate_workout_type(db, workout.workout_type_id)
db_workout = models.Workout(
sync_id=sync_id,
owner_id=current_user.id,
client_id=client_id,
workout_type_id=workout_type_id,
start_time=workout.start_time,
end_time=workout.end_time,
notes=workout.notes or "",
synced=1,
created_at=timestamp,
updated_at=timestamp,
)
db.add(db_workout)
db.flush()
for we_data in workout.workout_exercises or []:
db_we = models.WorkoutExercise(
sync_id=we_data.sync_id or new_sync_id(),
workout_id=db_workout.id,
exercise_id=we_data.exercise_id,
exercise_name=we_data.exercise_name,
sort_order=we_data.sort_order or 0,
created_at=timestamp,
)
db.add(db_we)
db.flush()
for set_data in we_data.sets or []:
create_set_record(db, db_we.id, set_data, timestamp)
for cardio_data in workout.cardio_sessions or []:
db_cardio = models.Cardio(
sync_id=cardio_data.sync_id or new_sync_id(),
workout_id=db_workout.id,
cardio_type=cardio_data.cardio_type,
purpose=cardio_data.purpose,
duration=cardio_data.duration,
distance=cardio_data.distance,
speed=cardio_data.speed,
incline=cardio_data.incline,
resistance=cardio_data.resistance,
notes=cardio_data.notes or "",
sort_order=cardio_data.sort_order or 0,
created_at=timestamp,
)
db.add(db_cardio)
db.commit()
db.refresh(db_workout)
return db_workout
@router.get("/", response_model=List[schemas.WorkoutOut])
def list_workouts(
client_id: Optional[int] = None,
skip: int = 0,
limit: int = 100,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
query = db.query(models.Workout).options(
joinedload(models.Workout.workout_exercises)
.joinedload(models.WorkoutExercise.sets)
.joinedload(models.Set.dropset_items),
joinedload(models.Workout.cardio_sessions),
).filter(
models.Workout.owner_id == current_user.id
)
if client_id:
validate_client(db, client_id, current_user)
query = query.filter(models.Workout.client_id == client_id)
return query.order_by(models.Workout.start_time.desc()).offset(skip).limit(limit).all()
@router.get("/{workout_id}", response_model=schemas.WorkoutOut)
def get_workout(
workout_id: int,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
db_workout = (
db.query(models.Workout)
.options(
joinedload(models.Workout.workout_exercises)
.joinedload(models.WorkoutExercise.sets)
.joinedload(models.Set.dropset_items),
joinedload(models.Workout.cardio_sessions),
)
.filter(
models.Workout.id == workout_id,
models.Workout.owner_id == current_user.id,
)
.first()
)
if not db_workout:
raise HTTPException(status_code=404, detail="Workout not found")
return db_workout
@router.put("/{workout_id}", response_model=schemas.WorkoutOut)
def update_workout(
workout_id: int,
workout: schemas.WorkoutUpdate,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
db_workout = get_owned_workout(db, workout_id, current_user)
update_data = workout.dict(exclude_unset=True)
if "workout_type_id" in update_data:
update_data["workout_type_id"] = validate_workout_type(
db,
update_data["workout_type_id"],
)
for key, value in update_data.items():
setattr(db_workout, key, value)
db_workout.updated_at = get_current_timestamp()
db.commit()
db.refresh(db_workout)
return db_workout
@router.delete("/{workout_id}")
def delete_workout(
workout_id: int,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(database.get_db),
):
db_workout = get_owned_workout(db, workout_id, current_user)
db.delete(db_workout)
db.commit()
return {"status": "deleted"}
+346
View File
@@ -0,0 +1,346 @@
from pydantic import BaseModel, Field
from typing import Optional, List, Dict, Any
# ============================================================
# AUTH / USERS
# ============================================================
class UserCreate(BaseModel):
username: str
password: str
display_name: Optional[str] = ""
role: Optional[str] = "personal"
class UserLogin(BaseModel):
username: str
password: str
class UserOut(BaseModel):
id: int
username: str
display_name: str
role: str
created_at: str
class Config:
from_attributes = True
class Token(BaseModel):
access_token: str
token_type: str = "bearer"
user: UserOut
# ============================================================
# WORKOUT TYPES
# ============================================================
class WorkoutTypeBase(BaseModel):
name: str
sort_order: Optional[int] = 0
class WorkoutTypeCreate(WorkoutTypeBase):
sync_id: Optional[str] = None
class WorkoutTypeOut(WorkoutTypeBase):
id: int
sync_id: str
created_at: str
class Config:
from_attributes = True
# ============================================================
# METRIC TYPES
# ============================================================
class MetricTypeBase(BaseModel):
name: str
unit: Optional[str] = "см"
category: Optional[str] = "body"
sort_order: Optional[int] = 0
class MetricTypeCreate(MetricTypeBase):
sync_id: Optional[str] = None
class MetricTypeOut(MetricTypeBase):
id: int
sync_id: str
created_at: str
class Config:
from_attributes = True
# ============================================================
# CLIENTS
# ============================================================
class ClientBase(BaseModel):
full_name: str
birth_date: Optional[str] = None
goal: Optional[str] = ""
notes: Optional[str] = ""
color: Optional[str] = None
is_active: Optional[int] = 1
class ClientCreate(ClientBase):
sync_id: Optional[str] = None
class ClientUpdate(BaseModel):
full_name: Optional[str] = None
birth_date: Optional[str] = None
goal: Optional[str] = None
notes: Optional[str] = None
color: Optional[str] = None
is_active: Optional[int] = None
class ClientOut(ClientBase):
id: int
sync_id: str
owner_id: Optional[int] = None
created_at: str
updated_at: str
class Config:
from_attributes = True
# ============================================================
# EXERCISES
# ============================================================
class ExerciseBase(BaseModel):
name: str
workout_type_id: Optional[int] = None
class ExerciseCreate(ExerciseBase):
sync_id: Optional[str] = None
class ExerciseUpdate(BaseModel):
name: Optional[str] = None
workout_type_id: Optional[int] = None
class ExerciseOut(ExerciseBase):
id: int
sync_id: str
owner_id: Optional[int] = None
created_at: str
updated_at: str
class Config:
from_attributes = True
# ============================================================
# DROPSET ITEMS
# ============================================================
class DropsetItemBase(BaseModel):
weight: float = Field(gt=0)
reps: int = Field(gt=0)
sort_order: int = 0
class DropsetItemCreate(DropsetItemBase):
pass
class DropsetItemOut(DropsetItemBase):
id: int
class Config:
from_attributes = True
# ============================================================
# SETS
# ============================================================
class SetBase(BaseModel):
is_dropset: int = 0
weight: Optional[float] = None
reps: Optional[int] = None
rating: Optional[int] = Field(None, ge=1, le=5)
notes: Optional[str] = ""
sort_order: int = 0
timestamp: str
class SetCreate(SetBase):
sync_id: Optional[str] = None
dropset_items: List[DropsetItemCreate] = Field(default_factory=list)
class SetOut(SetBase):
id: int
sync_id: str
created_at: str
dropset_items: List[DropsetItemOut] = Field(default_factory=list)
class Config:
from_attributes = True
# ============================================================
# WORKOUT EXERCISES
# ============================================================
class WorkoutExerciseBase(BaseModel):
exercise_name: str
exercise_id: Optional[int] = None
exercise_sync_id: Optional[str] = None
sort_order: int = 0
class WorkoutExerciseCreate(WorkoutExerciseBase):
sync_id: Optional[str] = None
sets: List[SetCreate] = Field(default_factory=list)
class WorkoutExerciseOut(WorkoutExerciseBase):
id: int
sync_id: str
created_at: str
sets: List[SetOut] = Field(default_factory=list)
class Config:
from_attributes = True
# ============================================================
# CARDIO
# ============================================================
class CardioBase(BaseModel):
cardio_type: str
purpose: str
duration: Optional[int] = None
distance: Optional[float] = None
speed: Optional[float] = None
incline: Optional[float] = None
resistance: Optional[int] = None
notes: Optional[str] = ""
sort_order: int = 0
class CardioCreate(CardioBase):
sync_id: Optional[str] = None
class CardioOut(CardioBase):
id: int
sync_id: str
created_at: str
class Config:
from_attributes = True
# ============================================================
# WORKOUTS
# ============================================================
class WorkoutBase(BaseModel):
start_time: str
end_time: Optional[str] = None
notes: Optional[str] = ""
workout_type_id: Optional[int] = None
class WorkoutCreate(WorkoutBase):
sync_id: Optional[str] = None
client_id: Optional[int] = None
client_sync_id: Optional[str] = None
workout_exercises: List[WorkoutExerciseCreate] = Field(default_factory=list)
cardio_sessions: List[CardioCreate] = Field(default_factory=list)
class WorkoutUpdate(BaseModel):
workout_type_id: Optional[int] = None
end_time: Optional[str] = None
notes: Optional[str] = None
synced: Optional[int] = None
class WorkoutOut(WorkoutBase):
id: int
sync_id: str
owner_id: Optional[int] = None
client_id: Optional[int] = None
synced: int
created_at: str
updated_at: str
workout_exercises: List[WorkoutExerciseOut] = Field(default_factory=list)
cardio_sessions: List[CardioOut] = Field(default_factory=list)
class Config:
from_attributes = True
# ============================================================
# BODY METRIC VALUES
# ============================================================
class BodyMetricValueBase(BaseModel):
value: float
class BodyMetricValueCreate(BodyMetricValueBase):
metric_type_id: Optional[int] = None
metric_type_sync_id: Optional[str] = None
class BodyMetricValueOut(BodyMetricValueBase):
id: int
metric_type_id: int
class Config:
from_attributes = True
# ============================================================
# BODY METRICS
# ============================================================
class BodyMetricBase(BaseModel):
metric_date: str
notes: Optional[str] = ""
class BodyMetricCreate(BodyMetricBase):
sync_id: Optional[str] = None
client_id: Optional[int] = None
client_sync_id: Optional[str] = None
values: List[BodyMetricValueCreate] = Field(default_factory=list)
class BodyMetricOut(BodyMetricBase):
id: int
sync_id: str
owner_id: Optional[int] = None
client_id: Optional[int] = None
created_at: str
values: List[BodyMetricValueOut] = Field(default_factory=list)
class Config:
from_attributes = True
# ============================================================
# SYNC
# ============================================================
class SyncPayload(BaseModel):
clients: List[ClientCreate] = Field(default_factory=list)
exercises: List[ExerciseCreate] = Field(default_factory=list)
workouts: List[WorkoutCreate] = Field(default_factory=list)
body_metrics: List[BodyMetricCreate] = Field(default_factory=list)
class SyncResponse(BaseModel):
status: str
created: Dict[str, int]
updated: Dict[str, int]
warnings: List[str] = Field(default_factory=list)
+37
View File
@@ -0,0 +1,37 @@
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:80"
depends_on:
backend:
condition: service_healthy
restart: unless-stopped
networks:
- gym-net
networks:
gym-net:
driver: bridge
+9
View File
@@ -0,0 +1,9 @@
FROM nginx:alpine
# Копируем конфиг
COPY nginx.conf /etc/nginx/conf.d/default.conf
# Копируем статику
COPY . /usr/share/nginx/html
EXPOSE 80
+19
View File
@@ -0,0 +1,19 @@
<!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 type="module" src="js/app.js"></script>
</body>
</html>
+69
View File
@@ -0,0 +1,69 @@
// 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 apiFetch("/workout-types/");
return jsonOrThrow(res, "Failed to fetch workout types");
}
export async function fetchMetricTypes() {
const res = await apiFetch("/metric-types/");
return jsonOrThrow(res, "Failed to fetch metric types");
}
export async function fetchClients() {
const res = await apiFetch("/clients/");
return jsonOrThrow(res, "Failed to fetch clients");
}
export async function fetchExerciseHistory(exerciseName, clientId = null) {
let path = `/exercises/history/${encodeURIComponent(exerciseName)}?limit=10`;
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 apiFetch("/sync/", {
method: "POST",
body: JSON.stringify(payload),
});
return jsonOrThrow(res, "Sync failed");
}
+239
View File
@@ -0,0 +1,239 @@
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 "./modals/modal-base.js";
import "./modals/exercise-modal.js";
import "./modals/set-modal.js";
import "./modals/cardio-modal.js";
import "./modals/metrics-modal.js";
import "./modals/edit-exercise-modal.js";
import "./modals/edit-workout-date-modal.js";
import "./modals/client-select-modal.js";
function renderHeader() {
const 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>
`;
}
function renderAuthScreen(message = "") {
const header = document.getElementById("app-header");
const app = document.getElementById("app");
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();
},
showDashboard: () => {
import('./render/dashboard-screen.js').then(mod => mod.renderDashboard());
},
backToMain: () => renderMainScreen(),
};
window.AppSync = { sync };
window.renderMainScreen = renderMainScreen;
window.state = state;
document.addEventListener("DOMContentLoaded", bootstrap);
+137
View File
@@ -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;
}
}
+5
View File
@@ -0,0 +1,5 @@
// frontend/js/config.js
export const API_BASE =
window.GYM_API_BASE ||
localStorage.getItem("gym_api_base") ||
"/api";
+35
View File
@@ -0,0 +1,35 @@
import { state, saveState, genId } from '../state.js';
import { renderMainScreen } from '../render/main-screen.js';
import { showCardioDialog } from '../modals/cardio-modal.js';
export function addCardio(workoutId) {
showCardioDialog(null, (cardio) => {
if (!cardio) return;
const w = state.workouts.find(x => x.id === workoutId);
cardio.id = genId();
w.cardio.push(cardio);
saveState();
renderMainScreen();
});
}
export function editCardio(workoutId, cardioId) {
const w = state.workouts.find(x => x.id === workoutId);
const cardio = w.cardio.find(c => c.id === cardioId);
showCardioDialog(cardio, (newData) => {
if (!newData) return;
Object.assign(cardio, newData);
saveState();
renderMainScreen();
});
}
export function deleteCardio(workoutId, cardioId) {
if (!confirm('Удалить кардио?')) return;
const w = state.workouts.find(x => x.id === workoutId);
w.cardio = w.cardio.filter(c => c.id !== cardioId);
saveState();
renderMainScreen();
}
window.CL = { addCardio, editCardio, deleteCardio };
+126
View File
@@ -0,0 +1,126 @@
import { state, saveState, genId } from '../state.js';
import { renderMainScreen } from '../render/main-screen.js';
import { showExerciseDialog } from '../modals/exercise-modal.js';
function normalizeName(name) {
return String(name || '').trim().toLowerCase();
}
function normalizeClientId(id) {
if (id === undefined || id === null || id === '') return null;
return String(id);
}
function isSameClient(a, b) {
return normalizeClientId(a) === normalizeClientId(b);
}
export function addExercise(workoutId) {
const w = state.workouts.find(x => x.id === workoutId);
if (!w) return;
showExerciseDialog(w.type, (name) => {
if (!name) return;
const ex = {
id: genId(),
name,
sets: [],
};
w.exercises.push(ex);
addToRef(name, w.type);
state.expandedExerciseId = ex.id;
saveState();
renderMainScreen();
});
}
export function addToRef(name, workoutType = '') {
const normalizedName = normalizeName(name);
const exists = state.exerciseRef.find(
e => normalizeName(e.name) === normalizedName
);
if (!exists) {
state.exerciseRef.push({
id: genId(),
name: String(name).trim(),
workoutType,
});
} else if (!exists.workoutType && workoutType) {
exists.workoutType = workoutType;
}
}
export function toggleExercise(exerciseId) {
state.expandedExerciseId =
state.expandedExerciseId === exerciseId ? null : exerciseId;
renderMainScreen();
}
export function deleteExercise(workoutId, exerciseId) {
if (!confirm('Удалить упражнение?')) return;
const w = state.workouts.find(x => x.id === workoutId);
if (!w) return;
w.exercises = w.exercises.filter(e => e.id !== exerciseId);
saveState();
renderMainScreen();
}
/**
* Локальная история упражнения.
*
* @param {string} exerciseName
* @param {string|number|null} clientId - если тренировка принадлежит клиенту, история берётся только для этого клиента
* @param {string|number|null} excludeWorkoutId - чтобы не показывать текущую тренировку как "прошлую"
*/
export function getExerciseHistory(exerciseName, clientId = null, excludeWorkoutId = null) {
const normalizedName = normalizeName(exerciseName);
const targetClient = normalizeClientId(clientId);
const history = [];
for (const w of state.workouts) {
// Не показываем текущую тренировку в истории
if (excludeWorkoutId && String(w.id) === String(excludeWorkoutId)) {
continue;
}
// Если у тренировки есть клиент — сравниваем клиентов
// Если клиента нет — показываем только личные тренировки без клиента
if (!isSameClient(w.client_id, targetClient)) {
continue;
}
for (const ex of w.exercises || []) {
if (
normalizeName(ex.name) === normalizedName &&
Array.isArray(ex.sets) &&
ex.sets.length > 0
) {
history.push({
date: w.startTime,
sets: ex.sets,
});
}
}
}
history.sort((a, b) => new Date(b.date) - new Date(a.date));
return history.slice(0, 3);
}
window.EL = {
addExercise,
toggleExercise,
deleteExercise,
};
+90
View File
@@ -0,0 +1,90 @@
// 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, (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('Замер сохранен локально. Нажмите 🔄 для синхронизации.');
});
}
/**
* Редактирование конкретного замера
*/
export function editBodyMetric(metricId) {
const metric = state.bodyMetrics.find(m => m.id === metricId);
if (!metric) return;
// Передаем данные в диалог. Диалог должен вернуть объект с теми же ID/sync_id, но новыми значениями
showBodyMetricsDialog([metric], (updatedData, isEdit) => {
if (!updatedData) return;
// Обновляем поля
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();
renderMainScreen();
alert('Изменения сохранены. Нажмите 🔄 для синхронизации.');
}, metric);
}
/**
* Удаление замера
*/
export function deleteMetric(id) {
if (!confirm('Удалить этот замер?')) return;
// Для простоты MVP удаляем локально.
// На сервере удаление через API /body-metrics/{id} можно добавить позже.
// Сейчас просто убираем из стейта.
state.bodyMetrics = state.bodyMetrics.filter(m => m.id !== id);
saveState();
renderMainScreen();
}
window.ML = {
showBodyMetrics,
editBodyMetric,
deleteMetric
};
+91
View File
@@ -0,0 +1,91 @@
import { state, saveState, genId } from '../state.js';
import { renderMainScreen } from '../render/main-screen.js';
import { showSetDialog } from '../modals/set-modal.js';
import { getExerciseHistory } from './exercise.js';
export function addSet(workoutId, exerciseId) {
const w = state.workouts.find(x => x.id === workoutId);
if (!w) return;
const ex = w.exercises.find(e => e.id === exerciseId);
if (!ex) return;
if (!Array.isArray(ex.sets)) {
ex.sets = [];
}
const lastSet = ex.sets[ex.sets.length - 1];
const history = getExerciseHistory(
ex.name,
w.client_id ?? null,
w.id
);
showSetDialog(lastSet, history, (setData) => {
if (!setData) return;
setData.id = genId();
setData.timestamp = new Date().toISOString();
ex.sets.push(setData);
saveState();
renderMainScreen();
});
}
export function editSet(workoutId, exerciseId, setId) {
const w = state.workouts.find(x => x.id === workoutId);
if (!w) return;
const ex = w.exercises.find(e => e.id === exerciseId);
if (!ex) return;
if (!Array.isArray(ex.sets)) {
ex.sets = [];
}
const set = ex.sets.find(s => s.id === setId);
if (!set) return;
const history = getExerciseHistory(
ex.name,
w.client_id ?? null,
w.id
);
showSetDialog(set, history, (setData) => {
if (!setData) return;
Object.assign(set, setData);
saveState();
renderMainScreen();
});
}
export function deleteSet(workoutId, exerciseId, setId) {
if (!confirm('Удалить подход?')) return;
const w = state.workouts.find(x => x.id === workoutId);
if (!w) return;
const ex = w.exercises.find(e => e.id === exerciseId);
if (!ex) return;
if (!Array.isArray(ex.sets)) {
ex.sets = [];
}
ex.sets = ex.sets.filter(s => s.id !== setId);
saveState();
renderMainScreen();
}
window.SL = {
addSet,
editSet,
deleteSet,
};
+739
View File
@@ -0,0 +1,739 @@
// frontend/js/logic/settings.js
import { state, saveState, CLIENT_COLORS, DEFAULT_COLOR, genId, generateUUID } from '../state.js';
import { showEditExerciseDialog } from '../modals/edit-exercise-modal.js';
import { showBodyMetricsDialog } from '../modals/metrics-modal.js';
import { apiFetch } from '../auth.js'; // Используем защищенный fetch
import { getToken } from '../auth.js';
import { fetchMetricTypes, fetchWorkoutTypes } from '../api.js';
// ============================================================
// ГЛАВНЫЙ ЭКРАН НАСТРОЕК
// ============================================================
export function showSettings() {
const app = document.getElementById('app');
if (!app) return;
app.innerHTML = '';
const screen = document.createElement('div');
screen.className = 'settings-screen';
// Генерируем опции типов тренировок из state.workoutTypes
const workoutTypeOptions = state.workoutTypes.length > 0
? state.workoutTypes.map(wt => `<option value="${wt.name}">${wt.name}</option>`).join('')
: '<option value="">(нет типов)</option>';
screen.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>
<!-- КНОПКА ОБНОВЛЕНИЯ СПРАВОЧНИКОВ -->
<div class="card mb-10" style="background: rgba(187, 134, 252, 0.1); border-color: var(--primary);">
<div style="display:flex; justify-content:space-between; align-items:center;">
<span class="text-muted text-small">Справочники загружены из базы данных.</span>
<button class="btn btn-small btn-secondary" onclick="SettingsLogic.refreshDicts()">🔄 Обновить</button>
</div>
</div>
<!-- 1. ТИПЫ ЗАМЕРОВ -->
<div class="settings-section">
<h3>📏 Типы замеров (${state.metricTypes.length})</h3>
<p class="text-muted text-small mb-10">
Какие метрики вы хотите отслеживать? Они появятся в форме добавления замера.
</p>
<button class="btn btn-small mb-10" onclick="SettingsLogic.showAddMetricTypeModal()">+ Добавить тип</button>
<div id="metric-types-list"></div>
</div>
<!-- 2. КЛИЕНТЫ -->
<div class="settings-section">
<h3>👥 Клиенты (${state.clients.length})</h3>
<p class="text-muted text-small mb-10">
Список подопечных. Цвет используется для подсветки их тренировок на главном экране.
</p>
<button class="btn btn-small mb-10" onclick="SettingsLogic.showAddClientModal()">+ Добавить клиента</button>
<div id="clients-list"></div>
</div>
<!-- 3. СПРАВОЧНИК УПРАЖНЕНИЙ -->
<div class="settings-section">
<h3>📋 Справочник упражнений (${state.exerciseRef.length})</h3>
<p class="text-muted text-small mb-10">
Ваши любимые упражнения. Привязка к типу тренировки помогает фильтровать список при выборе.
</p>
<div class="field-group">
<div style="display:flex; gap:6px;">
<input type="text" id="new-ref-exercise" placeholder="Новое упражнение...">
<select id="new-ref-type" style="width: auto; min-width: 120px;">
<option value="">тип...</option>
${workoutTypeOptions}
</select>
<button class="btn btn-small" style="width:auto; padding: 0 20px;" onclick="SettingsLogic.addRefExercise()">+</button>
</div>
</div>
<div id="ref-exercises-list"></div>
</div>
<!-- 4. ЛИЧНЫЕ ЗАМЕРЫ -->
<div class="settings-section">
<h3>📊 Личные замеры (${state.bodyMetrics.filter(m => !m.client_id).length})</h3>
<p class="text-muted text-small mb-10">
История ваших собственных измерений тела.
</p>
<button class="btn btn-small mb-10" onclick="ML.showBodyMetrics()">+ Добавить замер</button>
<div id="body-metrics-list"></div>
</div>
<!-- 5. ОПАСНАЯ ЗОНА -->
<div class="settings-section">
<h3>🗑 Данные</h3>
<button class="btn btn-danger" onclick="SettingsLogic.clearAllData()">Очистить все локальные данные</button>
</div>
`;
app.appendChild(screen);
// Вызываем рендеры всех списков
_renderMetricTypesList();
_renderClientsList();
_renderRefExercises();
_renderPersonalMetricsList();
}
export async function refreshDicts() {
const btn = document.querySelector('.btn-secondary[onclick*="refreshDicts"]'); // Ищем кнопку по onclick, если она есть
if (btn) btn.textContent = '⏳ Загрузка...';
try {
console.log("Проверка токена...", getToken());
// Если токена нет — сразу выходим и просим логин
if (!getToken()) {
alert("❌ Нет активной сессии. Пожалуйста, войдите снова.");
window.AuthUI.logout(); // Принудительно сбрасываем состояние
return;
}
// Загружаем типы замеров
const mtRes = await fetchMetricTypes();
state.metricTypes = Array.isArray(mtRes) ? mtRes : [];
// Загружаем типы тренировок
const wtRes = await fetchWorkoutTypes();
state.workoutTypes = Array.isArray(wtRes) ? wtRes : [];
saveState();
// Перерисовываем текущий экран настроек
showSettings();
alert(`✅ Справочники обновлены.\nТипов замеров: ${state.metricTypes.length}\nТипов тренировок: ${state.workoutTypes.length}`);
} catch (e) {
console.error(e);
// Специальная обработка 401
if (e.message.includes('401') || e.message.includes('Unauthorized')) {
alert("❌ Сессия истекла или неверна. Войдите заново.");
window.AuthUI.logout();
} else {
alert("❌ Ошибка обновления справочников: " + e.message);
}
} finally {
if (btn) btn.textContent = '🔄 Обновить';
}
}
// ============================================================
// ЛОГИКА: ТИПЫ ЗАМЕРОВ
// ============================================================
export function addClientMetric(clientId) {
const clientMetrics = state.bodyMetrics.filter(m => m.client_id == clientId);
showBodyMetricsDialog(clientMetrics, (newMetricData, isEdit) => {
if (!newMetricData) return;
if (isEdit && newMetricData.id) {
const existing = state.bodyMetrics.find(m => m.id === newMetricData.id);
if (existing) {
Object.assign(existing, newMetricData);
existing.synced = false;
}
} else {
const metric = {
id: generateUUID(),
sync_id: generateUUID(),
date: newMetricData.date,
notes: newMetricData.notes || "",
values: newMetricData.values || [],
client_id: parseInt(clientId), // Привязка к клиенту
synced: false,
};
state.bodyMetrics.unshift(metric);
}
state.bodyMetrics.sort((a, b) => new Date(b.date) - new Date(a.date));
saveState();
// Перерисовываем список замеров клиента в модалке настроек
showClientMetrics(clientId);
window.renderMainScreen();
});
}
export function showAddMetricTypeModal() {
const html = `
<div class="modal-content">
<h3 class="modal-title">➕ Новый тип замера</h3>
<div class="field-group">
<label>Название</label>
<input type="text" id="m-mt-name" placeholder="Например: Шея, Жир%, Икра">
</div>
<div class="field-group">
<label>Единица измерения</label>
<select id="m-mt-unit">
<option value="см">см</option>
<option value="кг">кг</option>
<option value="%">%</option>
<option value="мин">мин</option>
<option value="км">км</option>
<option value="шт">шт</option>
</select>
</div>
<div class="field-group">
<label>Порядок сортировки (меньше = выше)</label>
<input type="number" id="m-mt-order" value="99">
</div>
<div class="btn-row">
<button class="btn btn-secondary" onclick="ModalBase.closeModal()">Отмена</button>
<button class="btn btn-success" onclick="SettingsLogic.submitMetricType()">Сохранить</button>
</div>
</div>
`;
window.ModalBase.showModal(html);
}
export async function submitMetricType() {
const nameInput = document.getElementById('m-mt-name');
const unitSelect = document.getElementById('m-mt-unit');
const orderInput = document.getElementById('m-mt-order');
const name = nameInput.value.trim();
const unit = unitSelect.value;
const sort_order = parseInt(orderInput.value) || 99;
if (!name) {
alert('Введите название типа замера');
return;
}
try {
const res = await apiFetch('/metric-types/', {
method: 'POST',
body: JSON.stringify({
sync_id: generateUUID(),
name: name,
unit: unit,
category: 'body',
sort_order: sort_order
})
});
if (!res.ok) {
const errText = await res.text();
throw new Error(errText || 'Failed to create metric type');
}
const created = await res.json();
// Обновляем локальный стейт
if (!Array.isArray(state.metricTypes)) state.metricTypes = [];
state.metricTypes.push(created);
state.metricTypes.sort((a,b) => a.sort_order - b.sort_order);
saveState();
window.ModalBase.closeModal();
_renderMetricTypesList(); // Перерисовываем список
// Сообщаем об успехе
console.log('✅ Тип замера создан:', created.name);
} catch (e) {
console.error('❌ Error creating metric type:', e);
alert('Ошибка создания типа: ' + e.message);
}
}
export async function deleteMetricType(id) {
if(!confirm('Удалить этот тип замера?\nДанные в прошлых замерах останутся, но поле исчезнет из формы.')) return;
try {
// TODO: Реализовать DELETE endpoint на бэкенде, если нужно удалять глобально
// Пока просто удаляем локально из view-списка, чтобы UI обновился
// Если бэк поддерживает удаление:
// const res = await apiFetch(`/metric-types/${id}`, { method: 'DELETE' });
// if(res.ok) { ... }
// Для MVP просто скрываем из локального состояния, пока не будет полного CRUD
state.metricTypes = state.metricTypes.filter(t => t.id != id);
saveState();
_renderMetricTypesList();
} catch (e) {
console.error(e);
alert('Не удалось удалить тип.');
}
}
export function _renderMetricTypesList() {
const list = document.getElementById('metric-types-list');
if (!list) return;
// Если массив пустой или undefined
if (!Array.isArray(state.metricTypes) || state.metricTypes.length === 0) {
list.innerHTML = `
<div class="empty-state" style="padding: 20px;">
<p class="text-muted">Нет активных типов замеров.</p>
<p class="text-small text-muted">Нажмите "🔄 Обновить" сверху или добавьте новый тип.</p>
</div>
`;
return;
}
list.innerHTML = state.metricTypes.map(mt => `
<div class="exercise-ref-item">
<div>
<span class="name">${mt.name}</span>
<span class="count">(${mt.unit}) • Порядок: ${mt.sort_order}</span>
</div>
<button class="icon-btn danger" onclick="SettingsLogic.deleteMetricType('${mt.id}')">✕</button>
</div>
`).join('');
}
// ============================================================
// ЛОГИКА: КЛИЕНТЫ
// ============================================================
export function showAddClientModal(editingClient = null) {
const isEdit = !!editingClient;
const client = editingClient || { full_name: '', birth_date: '', goal: '', color: DEFAULT_COLOR };
// Палитра цветов
const paletteHtml = CLIENT_COLORS.map(color => `
<div class="color-swatch ${client.color === color ? 'selected' : ''}"
style="background:${color};"
data-color="${color}"
onclick="SettingsLogic.selectClientColor('${color}')"></div>
`).join('');
const html = `
<div class="modal-content">
<h3 class="modal-title">${isEdit ? '✎ Редактировать' : '👤 Новый'} клиент</h3>
<div class="field-group">
<label>ФИО</label>
<input type="text" id="m-client-name" value="${client.full_name}" placeholder="Иванов Иван Иванович">
</div>
<div class="field-group">
<label>Дата рождения</label>
<input type="date" id="m-client-dob" value="${client.birth_date || ''}">
</div>
<div class="field-group">
<label>Цель тренировок</label>
<input type="text" id="m-client-goal" value="${client.goal || ''}" placeholder="Набор массы, похудение...">
</div>
<div class="field-group">
<label>Цвет клиента (для визуального разделения)</label>
<div class="color-palette" id="m-client-palette">
${paletteHtml}
</div>
</div>
<div class="btn-row">
<button class="btn btn-secondary" onclick="ModalBase.closeModal()">Отмена</button>
<button class="btn btn-success" onclick="SettingsLogic.submitClient('${editingClient?.id || ''}')">Сохранить</button>
</div>
</div>
`;
window.ModalBase.showModal(html);
window._tempClientColor = client.color || DEFAULT_COLOR;
}
export function selectClientColor(color) {
window._tempClientColor = color;
// Визуально выделяем выбранный цвет
document.querySelectorAll('#m-client-palette .color-swatch').forEach(el => {
el.classList.toggle('selected', el.dataset.color === color);
});
}
export async function submitClient(editingId) {
const nameInput = document.getElementById('m-client-name');
const dobInput = document.getElementById('m-client-dob');
const goalInput = document.getElementById('m-client-goal');
const name = nameInput.value.trim();
if (!name) {
alert('Введите ФИО клиента');
return;
}
const color = window._tempClientColor || DEFAULT_COLOR;
const birthDate = dobInput.value || null;
const goal = goalInput.value.trim();
const payload = {
sync_id: editingId ? undefined : generateUUID(), // При редактировании sync_id не меняем
full_name: name,
birth_date: birthDate,
goal: goal,
notes: "",
color: color,
is_active: 1
};
try {
let res;
if (editingId) {
// PUT /clients/{id}
res = await apiFetch(`/clients/${editingId}`, {
method: 'PUT',
body: JSON.stringify(payload)
});
} else {
// POST /clients/
res = await apiFetch('/clients/', {
method: 'POST',
body: JSON.stringify(payload)
});
}
if (!res.ok) {
const errText = await res.text();
throw new Error(errText || 'Failed to save client');
}
const savedClient = await res.json();
// Обновляем локальный стейт
if (!Array.isArray(state.clients)) state.clients = [];
if (editingId) {
const idx = state.clients.findIndex(c => c.id == editingId);
if (idx !== -1) {
state.clients[idx] = savedClient;
}
} else {
state.clients.push(savedClient);
}
// Сортируем по имени
state.clients.sort((a, b) => a.full_name.localeCompare(b.full_name));
saveState();
window.ModalBase.closeModal();
_renderClientsList();
// Если мы в режиме тренера и выбрали этого клиента автоматически (если был пуст)
if (state.mode === 'trainer' && !state.currentClientId && !editingId) {
// Можно автовыбрать первого нового, но лучше оставить выбор пользователю
}
window.renderMainScreen(); // Обновляем цвета на главном экране
} catch (e) {
console.error('❌ Error saving client:', e);
alert('Ошибка сохранения клиента: ' + e.message);
}
}
export async function deleteClient(id) {
if (!confirm('Удалить клиента?\nЕго тренировки останутся, но потеряют привязку и цвет.')) return;
try {
const res = await apiFetch(`/clients/${id}`, { method: 'DELETE' });
if (!res.ok) throw new Error(await res.text());
// Удаляем локально
state.clients = state.clients.filter(c => c.id != id);
// Отвязываем тренировки и замеры локально (на сервере они тоже отвязались через ON DELETE SET NULL)
state.workouts.forEach(w => {
if (w.client_id == id) w.client_id = null;
});
state.bodyMetrics.forEach(m => {
if (m.client_id == id) m.client_id = null;
});
saveState();
_renderClientsList();
window.renderMainScreen();
} catch (e) {
console.error(e);
alert('Не удалось удалить клиента.');
}
}
export function _renderClientsList() {
const list = document.getElementById('clients-list');
if (!list) return;
if (!state.clients || state.clients.length === 0) {
list.innerHTML = '<p class="text-muted text-small">Нет клиентов. Добавьте первого!</p>';
return;
}
list.innerHTML = state.clients.map(c => {
// Статистика
const clientWorkouts = state.workouts.filter(w => w.client_id == c.id);
const clientMetrics = state.bodyMetrics.filter(m => m.client_id == c.id);
return `
<div class="exercise-ref-item" style="border-left: 4px solid ${c.color || DEFAULT_COLOR}; padding-left: 10px;">
<div style="flex:1;">
<div style="font-weight:600;">${c.full_name}</div>
<div class="text-small text-muted">${c.goal || 'Цель не указана'}</div>
<div class="text-small text-muted" style="margin-top:4px;">
🏋️ ${clientWorkouts.length} трен. • 📏 ${clientMetrics.length} замеров
</div>
</div>
<div style="display:flex; gap:4px;">
<button class="icon-btn" onclick="SettingsLogic.showAddClientModal(state.clients.find(x => x.id == '${c.id}'))" title="Редактировать">✎</button>
<button class="icon-btn danger" onclick="SettingsLogic.deleteClient('${c.id}')" title="Удалить">✕</button>
</div>
</div>
`;
}).join('');
}
// ============================================================
// ЛОГИКА: УПРАЖНЕНИЯ (СПРАВОЧНИК)
// ============================================================
export function addRefExercise() {
const input = document.getElementById('new-ref-exercise');
const typeSelect = document.getElementById('new-ref-type');
const name = input.value.trim();
if (!name) return;
const normalizedName = name.toLowerCase();
const exists = state.exerciseRef.find(e => e.name.toLowerCase() === normalizedName);
if (exists) {
alert('Такого упражнения уже нет в справочнике? Оно есть!');
return;
}
// Добавляем локально
const newEx = {
id: genId(),
sync_id: generateUUID(),
name: name,
workoutType: typeSelect.value || '',
};
state.exerciseRef.push(newEx);
saveState();
input.value = '';
typeSelect.value = '';
_renderRefExercises();
}
export function deleteRefExercise(id) {
if (!confirm('Удалить из справочника? (в тренировках останется как текст)')) return;
state.exerciseRef = state.exerciseRef.filter(e => e.id !== id);
saveState();
_renderRefExercises();
}
export function updateRefExerciseType(id, newType) {
const ex = state.exerciseRef.find(e => e.id === id);
if (ex) {
ex.workoutType = newType;
saveState();
// Не перерисовываем весь список, чтобы не сбросить фокус,
// но можно обновить badge визуально, если нужно
}
}
export function editRefExercise(id) {
const ex = state.exerciseRef.find(e => e.id === id);
if (!ex) return;
showEditExerciseDialog(ex, (updatedData) => {
if (!updatedData) return;
Object.assign(ex, updatedData);
saveState();
_renderRefExercises();
});
}
export function _renderRefExercises() {
const list = document.getElementById('ref-exercises-list');
if (!list) return;
if (state.exerciseRef.length === 0) {
list.innerHTML = '<p class="text-muted text-small">Справочник пуст</p>';
return;
}
// Сортировка: сначала по типу, потом по алфавиту
const sorted = [...state.exerciseRef].sort((a, b) => {
const typeA = a.workoutType || '';
const typeB = b.workoutType || '';
if (typeA !== typeB) return typeA.localeCompare(typeB);
return a.name.localeCompare(b.name);
});
// Опции для селекта внутри карточки
const typeOptionsHtml = state.workoutTypes.map(wt =>
`<option value="${wt.name}">${wt.name}</option>`
).join('');
list.innerHTML = sorted.map(ex => {
let count = 0;
state.workouts.forEach(w => {
w.exercises.forEach(e => {
if (e.name.trim().toLowerCase() === ex.name.trim().toLowerCase()) count++;
});
});
return `
<div class="exercise-ref-item">
<div style="flex:1;">
<span class="name">${ex.name}</span>
<span class="count">(${count}×)</span>
${ex.workoutType ? `<span class="type-badge">${ex.workoutType}</span>` : ''}
</div>
<div style="display:flex; gap:4px; align-items:center;">
<select onchange="SettingsLogic.updateRefExerciseType('${ex.id}', this.value)"
style="width:auto; min-width:100px; padding:6px; font-size:0.8rem;">
<option value="">тип...</option>
${typeOptionsHtml.split('</option>').map(opt => {
const val = opt.match(/value="(.*?)"/)?.[1] || '';
const selected = ex.workoutType === val ? 'selected' : '';
return `${opt}${val === ex.workoutType ? ' selected' : ''}`;
}).join('')}
</select>
<button class="icon-btn" onclick="SettingsLogic.editRefExercise('${ex.id}')">✎</button>
<button class="icon-btn danger" onclick="SettingsLogic.deleteRefExercise('${ex.id}')">✕</button>
</div>
</div>
`;
}).join('');
}
// ============================================================
// ЛОГИКА: ЛИЧНЫЕ ЗАМЕРЫ
// ============================================================
export function _renderPersonalMetricsList() {
const list = document.getElementById('body-metrics-list');
if (!list) return;
// Фильтруем только личные (без client_id)
const personalMetrics = state.bodyMetrics.filter(m => !m.client_id);
if (personalMetrics.length === 0) {
list.innerHTML = '<p class="text-muted text-small">Нет личных замеров</p>';
return;
}
// Сортируем по дате (новые сверху)
const sorted = [...personalMetrics].sort((a, b) => new Date(b.date) - new Date(a.date));
list.innerHTML = sorted.map(m => {
const dateStr = new Date(m.date).toLocaleDateString('ru-RU') + ' ' +
new Date(m.date).toLocaleTimeString('ru-RU', {hour:'2-digit', minute:'2-digit'});
// Форматируем значения динамически
let valuesStr = '—';
if (Array.isArray(m.values) && m.values.length > 0) {
const parts = m.values.map(v => {
const mt = state.metricTypes.find(t => t.id == v.metric_type_id);
const name = mt ? mt.name : '?';
const unit = mt ? mt.unit : '';
return `${name}: ${v.value}${unit}`;
});
valuesStr = parts.join(' • ');
} else {
// Legacy support
const legacyParts = [];
if (m.weight) legacyParts.push(`Вес: ${m.weight} кг`);
if (m.chest) legacyParts.push(`Грудь: ${m.chest} см`);
if (legacyParts.length) valuesStr = legacyParts.join(' • ');
}
return `
<div class="exercise-ref-item">
<div>
<div style="font-weight:500;">${dateStr}</div>
<div class="text-small text-muted">${valuesStr}</div>
</div>
<div style="display:flex; gap:4px;">
<button class="icon-btn" onclick="ML.editBodyMetric('${m.id}')">✎</button>
<button class="icon-btn danger" onclick="ML.deleteMetric('${m.id}')">✕</button>
</div>
</div>
`;
}).join('');
}
// ============================================================
// ПРОЧИЕ
// ============================================================
export function clearAllData() {
if (!confirm('Удалить ВСЕ локальные данные? Это действие необратимо!\n(Данные на сервере останутся)')) return;
if (!confirm('Точно уверены?')) return;
localStorage.clear();
location.reload();
}
// Экспорт всего объекта SettingsLogic
window.SettingsLogic = {
show: showSettings,
refreshDicts, // <-- ДОБАВИЛИ В ЭКСПОРТ
// Metric Types
showAddMetricTypeModal,
submitMetricType,
deleteMetricType,
_renderMetricTypesList,
// Clients
showAddClientModal,
selectClientColor,
submitClient,
deleteClient,
_renderClientsList,
// Exercises Ref
addRefExercise,
deleteRefExercise,
updateRefExerciseType,
editRefExercise,
_renderRefExercises,
// Personal Metrics
_renderPersonalMetricsList,
// Danger Zone
clearAllData,
};
+88
View File
@@ -0,0 +1,88 @@
import { state, saveState, genId } from '../state.js';
import { renderMainScreen } from '../render/main-screen.js';
import { showEditWorkoutDateDialog } from '../modals/edit-workout-date-modal.js';
import { showClientSelectModal } from '../modals/client-select-modal.js';
export function startWorkout() {
// В режиме тренера — сначала выбираем клиента
if (state.mode === 'trainer') {
showClientSelectModal((clientId) => {
_createWorkout(clientId);
});
} else {
_createWorkout(null);
}
}
function _createWorkout(clientId) {
const w = {
id: genId(),
client_id: clientId,
startTime: new Date().toISOString(),
endTime: null,
type: '',
exercises: [],
cardio: [],
notes: '',
synced: false,
};
state.workouts.unshift(w);
state.expandedWorkoutId = w.id;
saveState();
renderMainScreen();
}
export function finishWorkout(workoutId) {
if (!confirm('Завершить тренировку?')) return;
const w = getWorkout(workoutId);
w.endTime = new Date().toISOString();
saveState();
renderMainScreen();
}
export function deleteWorkout(workoutId) {
if (!confirm('Удалить тренировку полностью?')) return;
state.workouts = state.workouts.filter(w => w.id !== workoutId);
saveState();
renderMainScreen();
}
export function toggleWorkout(workoutId) {
state.expandedWorkoutId =
state.expandedWorkoutId === workoutId ? null : workoutId;
renderMainScreen();
}
export function getWorkout(id) {
return state.workouts.find(w => w.id === id);
}
export function getActiveWorkout() {
return state.workouts.find(w => !w.endTime);
}
export function editWorkoutDate(workoutId) {
const w = getWorkout(workoutId);
if (!w) return;
showEditWorkoutDateDialog(w, (newDates) => {
if (!newDates) return;
w.startTime = newDates.startTime;
w.endTime = newDates.endTime;
saveState();
renderMainScreen();
});
}
export function cancelEmptyWorkout(workoutId) {
if (!confirm('Отменить эту тренировку? Все данные будут удалены.')) return;
deleteWorkout(workoutId);
}
window.WL = {
startWorkout,
finishWorkout,
deleteWorkout,
toggleWorkout,
editWorkoutDate,
cancelEmptyWorkout
};
+57
View File
@@ -0,0 +1,57 @@
import { showModal, closeModal, stepperHtml } from './modal-base.js';
let _cb = null;
export function showCardioDialog(existing, callback) {
_cb = callback;
const e = existing || {};
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>
</select></div>
<div class="field-group"><label>Назначение</label><select id="m-cp">
<option value="warmup" ${e.purpose==='warmup'?'selected':''}>🔥 Разминка</option>
<option value="cooldown" ${e.purpose==='cooldown'?'selected':''}>🧘 Заминка</option>
<option value="separate" ${e.purpose==='separate'?'selected':''}>➕ Отдельная</option>
</select></div></div>
<div class="field-row-3">
<div class="field-group"><label>Минут</label>${stepperHtml('m-cd', e.duration??'', 1, 'мин', 'numeric')}</div>
<div class="field-group"><label>Дист.</label>${stepperHtml('m-cdi', e.distance??'', 0.1, 'км')}</div>
<div class="field-group"><label>Скор.</label>${stepperHtml('m-cs', e.speed??'', 0.5, 'км/ч')}</div></div>
<div class="field-row">
<div class="field-group"><label>Наклон</label>${stepperHtml('m-ci', e.incline??'', 0.5, '—')}</div>
<div class="field-group"><label>Сопр.</label>${stepperHtml('m-cr', e.resistance??'', 1, '—', 'numeric')}</div></div>
<div class="field-group"><label>Заметка</label><input type="text" id="m-cn" value="${e.notes||''}"></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="CardioModal.submit()">Сохранить</button></div>
</div>`);
}
export function submit() {
// 1. Сначала считываем все значения, пока модалка ещё в DOM
const result = {
type: document.getElementById('m-ct').value,
purpose: document.getElementById('m-cp').value,
duration: parseInt(document.getElementById('m-cd').value) || 0,
distance: parseFloat(document.getElementById('m-cdi').value) || 0,
speed: parseFloat(document.getElementById('m-cs').value) || 0,
incline: parseFloat(document.getElementById('m-ci').value) || 0,
resistance: parseInt(document.getElementById('m-cr').value) || 0,
notes: document.getElementById('m-cn').value.trim(),
};
// 2. Только теперь закрываем модалку
closeModal();
// 3. Отдаём результат
_cb?.(result);
}
window.CardioModal = { submit };
+58
View File
@@ -0,0 +1,58 @@
import { showModal, closeModal } from './modal-base.js';
import { state, CLIENT_COLORS, DEFAULT_COLOR, genId, generateUUID } from '../state.js';
let _cb = null;
export function showClientSelectModal(callback) {
_cb = callback;
if (state.clients.length === 0) {
// Нет клиентов — предлагаем создать
showModal(`
<div class="modal-content">
<h3 class="modal-title">👤 Нет клиентов</h3>
<p class="text-muted">Сначала добавьте клиента в настройках.</p>
<div class="btn-row">
<button class="btn btn-secondary" onclick="ModalBase.closeModal()">Отмена</button>
<button class="btn" onclick="ClientSelectModal.goToSettings()">⚙️ В настройки</button>
</div>
</div>
`);
return;
}
const clientsHtml = state.clients.map(c => `
<div class="client-select-item" onclick="ClientSelectModal.select('${c.id}')"
style="border-left: 4px solid ${c.color || DEFAULT_COLOR};">
<div style="flex:1;">
<div style="font-weight:600;">${c.full_name}</div>
<div class="text-small text-muted">${c.goal || '—'}</div>
</div>
<span style="color:var(--text-secondary);">›</span>
</div>
`).join('');
showModal(`
<div class="modal-content">
<h3 class="modal-title">👤 Для кого тренировка?</h3>
<div class="client-select-list">
${clientsHtml}
</div>
<div class="btn-row" style="margin-top:16px;">
<button class="btn btn-secondary" onclick="ModalBase.closeModal()">Отмена</button>
</div>
</div>
`);
}
export function select(clientId) {
closeModal();
if (_cb) _cb(parseInt(clientId));
}
export function goToSettings() {
closeModal();
window.SettingsLogic.show();
}
window.ClientSelectModal = { select, goToSettings };
+42
View File
@@ -0,0 +1,42 @@
import { showModal, closeModal } from './modal-base.js';
let _cb = null;
export function showEditExerciseDialog(exercise, callback) {
_cb = callback;
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}">
</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>
</select>
</div>
<div class="btn-row">
<button class="btn btn-secondary" onclick="ModalBase.close()">Отмена</button>
<button class="btn btn-success" onclick="EditExModal.submit()">Сохранить</button>
</div>
</div>
`);
}
export function submit() {
const name = document.getElementById('m-edit-ex-name').value.trim();
const type = document.getElementById('m-edit-ex-type').value;
if (!name) { alert('Название не может быть пустым'); return; }
closeModal();
if (_cb) _cb({ name, workoutType: type });
}
window.EditExModal = { submit };
@@ -0,0 +1,41 @@
import { showModal, closeModal } from './modal-base.js';
import { toDatetimeLocal } from '../utils.js';
let _cb = null;
export function showEditWorkoutDateDialog(workout, callback) {
_cb = callback;
const startValue = toDatetimeLocal(workout.startTime);
const endValue = workout.endTime ? toDatetimeLocal(workout.endTime) : '';
showModal(`
<div class="modal-content">
<h3 class="modal-title">📅 Дата тренировки</h3>
<div class="field-group">
<label>Начало</label>
<input type="datetime-local" id="m-w-start" value="${startValue}">
</div>
<div class="field-group">
<label>Окончание</label>
<input type="datetime-local" id="m-w-end" value="${endValue}">
</div>
<div class="btn-row">
<button class="btn btn-secondary" onclick="ModalBase.closeModal()">Отмена</button>
<button class="btn btn-success" onclick="EditDateModal.submit()">Сохранить</button>
</div>
</div>
`);
}
export function submit() {
const startStr = document.getElementById('m-w-start').value;
const endStr = document.getElementById('m-w-end').value;
if (!startStr) { alert('Укажите дату начала'); return; }
closeModal();
if (_cb) _cb({
startTime: new Date(startStr).toISOString(),
endTime: endStr ? new Date(endStr).toISOString() : null,
});
}
window.EditDateModal = { submit };
+60
View File
@@ -0,0 +1,60 @@
import { showModal, closeModal } from './modal-base.js';
import { state } from '../state.js';
let _cb = null;
let _names = [];
export function showExerciseDialog(workoutType, callback) {
_cb = callback;
const nameCount = {};
state.exerciseRef.forEach(ex => {
const bonus = (workoutType && ex.workoutType === workoutType) ? 100 : 10;
nameCount[ex.name] = (nameCount[ex.name] || 0) + bonus;
});
state.workouts.forEach(w => w.exercises.forEach(ex => {
nameCount[ex.name] = (nameCount[ex.name] || 0) + 1;
}));
_names = Object.keys(nameCount).sort((a, b) => {
const d = nameCount[b] - nameCount[a];
return d !== 0 ? d : a.localeCompare(b);
});
showModal(`<div class="modal-content">
<h3 class="modal-title">Добавить упражнение</h3>
<div class="field-group">
<label>Название</label>
<input type="text" id="m-ex-name" placeholder="Начните вводить..." oninput="ExerciseModal.filter()" autocomplete="off">
<div id="m-ex-autocomplete" class="autocomplete-list"></div>
</div>
<div class="btn-row">
<button class="btn btn-secondary" onclick="ModalBase.closeOnBg({target:document.querySelector('.modal-overlay')})">Отмена</button>
<button class="btn" onclick="ExerciseModal.submit()">Добавить</button>
</div>
</div>`);
setTimeout(() => { document.getElementById('m-ex-name').focus(); filter(); }, 50);
}
export function filter() {
const q = document.getElementById('m-ex-name').value.trim().toLowerCase();
const list = document.getElementById('m-ex-autocomplete');
let f = _names;
if (q) f = f.filter(n => n.toLowerCase().includes(q));
if (!f.length) { list.innerHTML = '<div class="autocomplete-item text-muted">Нет совпадений</div>'; return; }
list.innerHTML = f.slice(0, 15).map(name => {
const count = state.workouts.reduce((s, w) => s + w.exercises.filter(e => e.name === name).length, 0);
return `<div class="autocomplete-item" onclick="ExerciseModal.select('${name.replace(/'/g, "\\'")}')">${name}${count ? `<span class="freq">${count}×</span>` : ''}</div>`;
}).join('');
}
export function select(name) {
document.getElementById('m-ex-name').value = name;
document.getElementById('m-ex-autocomplete').innerHTML = '';
}
export function submit() {
const name = document.getElementById('m-ex-name').value.trim();
closeModal();
if (name && _cb) _cb(name);
}
window.ExerciseModal = { filter, select, submit };
+143
View File
@@ -0,0 +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;
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 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}
};
closeModal();
if (_cb) _cb(result, _isEdit);
}
window.MetricsModal = { submit };
+39
View File
@@ -0,0 +1,39 @@
const container = () => document.getElementById('modal-container');
export function showModal(html) {
container().innerHTML = `<div class="modal-overlay" onclick="ModalBase.closeOnBg(event)">${html}</div>`;
}
export function closeModal() {
container().innerHTML = '';
}
export function closeOnBg(e) {
if (e.target.classList.contains('modal-overlay')) closeModal();
}
export function stepperHtml(id, value, step, placeholder, inputmode = 'decimal') {
const v = value !== '' && value != null ? value : '';
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>
</div>`;
}
export function stepValue(id, delta) {
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);
input.value = parseFloat((Math.round(newVal / step) * step).toFixed(4));
}
window.ModalBase = {
showModal,
closeModal,
close: closeModal,
closeOnBg,
stepValue
};
+127
View File
@@ -0,0 +1,127 @@
import { showModal, closeModal, stepperHtml } from './modal-base.js';
import { formatShortDate, formatSet } from '../utils.js';
let _data = {};
let _cb = null;
export function showSetDialog(existingSet, history, callback) {
_cb = callback;
const isEdit = !!existingSet;
const isDropset = existingSet?.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('');
historyHtml = `<div class="history-hint"><div class="history-hint-title">📊 Прошлые тренировки</div>${rows}</div>`;
}
showModal(`<div class="modal-content">
<h3 class="modal-title">${isEdit ? 'Редактировать' : 'Новый'} подход</h3>
${historyHtml}
<div class="field-group"><label style="display:flex;align-items:center;gap:8px;">
<input type="checkbox" id="m-set-dropset" ${isDropset ? 'checked' : ''} onchange="SetModal.toggleDropset()" style="width:auto;">
Это дроп-сет</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></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('')}
</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="SetModal.submit()">Сохранить</button></div>
</div>`);
_data = {
isDropset, rating: existingSet?.rating || 3,
subSets: existingSet?.subSets ? JSON.parse(JSON.stringify(existingSet.subSets)) : [],
};
if (isDropset) { if (!_data.subSets.length) addSubset(); else renderSubsets(); }
rating(_data.rating);
}
export function toggleDropset() {
_data.isDropset = document.getElementById('m-set-dropset').checked;
document.getElementById('m-set-normal').classList.toggle('hidden', _data.isDropset);
document.getElementById('m-set-dropset-block').classList.toggle('hidden', !_data.isDropset);
if (_data.isDropset && !_data.subSets.length) addSubset();
else if (_data.isDropset) renderSubsets();
}
export function addSubset() {
const last = _data.subSets[_data.subSets.length - 1];
_data.subSets.push({ weight: last?.weight || '', reps: last?.reps || '' });
renderSubsets();
}
export function renderSubsets() {
document.getElementById('m-subsets-list').innerHTML = _data.subSets.map((s, i) => `
<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>
</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)">
<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('');
}
export function updateSubset(i, field, value) {
_data.subSets[i][field] = value;
}
export function stepSubset(i, field, delta) {
const current = parseFloat(_data.subSets[i][field]) || 0;
const step = field === 'weight' ? 0.5 : 1;
const newVal = Math.max(0, current + delta);
_data.subSets[i][field] = parseFloat((Math.round(newVal / step) * step).toFixed(4));
renderSubsets(); // Перерисовываем, чтобы обновить значение в input
}
export function removeSubset(i) {
_data.subSets.splice(i, 1);
renderSubsets();
}
export function rating(r) {
_data.rating = r;
document.querySelectorAll('#m-rating-grid .rating-btn').forEach(b => b.classList.toggle('active', +b.dataset.rating === r));
}
export function submit() {
if (_data.isDropset) {
_data.subSets.forEach((s, i) => {
const w = document.getElementById(`m-sw-${i}`);
const r = document.getElementById(`m-sr-${i}`);
if (w) s.weight = w.value; if (r) s.reps = r.value;
});
if (!_data.subSets.length) { alert('Добавьте сбрасывание'); return; }
closeModal(); _cb?.({ isDropset: true, subSets: _data.subSets.map(s => ({ weight: parseFloat(s.weight)||0, reps: parseInt(s.reps)||0 })), rating: _data.rating });
} else {
const w = parseFloat(document.getElementById('m-set-weight').value);
const r = parseInt(document.getElementById('m-set-reps').value);
if (!w && !r) { alert('Укажите вес и повторения'); return; }
closeModal(); _cb?.({ isDropset: false, weight: w||0, reps: r||0, rating: _data.rating });
}
}
// Обновляем экспорт в window
window.SetModal = {
toggleDropset, addSubset, removeSubset, rating, submit,
updateSubset, stepSubset
};
+30
View File
@@ -0,0 +1,30 @@
export function renderCardioItem(workoutId, c, isReadOnly = false) {
const card = document.createElement('div');
card.className = 'card';
const purposeLabels = { warmup: '🔥 Разминка', cooldown: '🧘 Заминка', separate: '➕ Отдельная' };
const metrics = [];
if (c.duration) metrics.push(`${c.duration} мин`);
if (c.distance) metrics.push(`${c.distance} км`);
if (c.speed) metrics.push(`${c.speed} км/ч`);
if (c.incline) metrics.push(`наклон ${c.incline}`);
if (c.resistance) metrics.push(`сопр. ${c.resistance}`);
const actionsHtml = isReadOnly ? '' : `
<div class="set-actions">
<button class="icon-btn" onclick="CL.editCardio('${workoutId}', '${c.id}')">✎</button>
<button class="icon-btn danger" onclick="CL.deleteCardio('${workoutId}', '${c.id}')">✕</button>
</div>
`;
card.innerHTML = `
<div style="display:flex; justify-content:space-between; align-items:flex-start;">
<div>
<div style="font-weight:600;">${c.type || '—'} ${purposeLabels[c.purpose] || ''}</div>
<div class="text-small text-muted">${metrics.join(' • ') || '—'}</div>
${c.notes ? `<div class="text-small" style="margin-top:4px;">"${c.notes}"</div>` : ''}
</div>
${actionsHtml}
</div>
`;
return card;
}
+96
View File
@@ -0,0 +1,96 @@
// frontend/js/render/dashboard-screen.js
import { state } from '../state.js';
import { drawExerciseProgress, drawBodyMetricsGraph } from './dashboard.js';
export function renderDashboard() {
const app = document.getElementById('app');
if (!app) return;
app.innerHTML = `
<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.updateExerciseChart()">
<option value="">— Выберите —</option>
${getUniqueExercises().map(ex => `<option value="${ex}">${ex}</option>`).join('')}
</select>
</div>
<canvas id="chart-exercise" width="400" height="200" style="width:100%; background:#1e1e1e; border-radius:8px;"></canvas>
<p class="text-muted text-small mt-10">Показаны макс. вес и повторения за последние 10 тренировок.</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 = {
updateExerciseChart: () => {
const select = document.getElementById('dash-ex-select');
const canvas = document.getElementById('chart-exercise');
if (select.value) {
drawExerciseProgress(canvas, select.value);
} else {
const ctx = canvas.getContext('2d');
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle='#666';
ctx.textAlign='center';
ctx.fillText('Выберите упражнение выше', canvas.width/2, canvas.height/2);
}
},
updateBodyChart: () => {
const clientSel = document.getElementById('dash-client-select');
const metricSel = document.getElementById('dash-metric-select');
const canvas = document.getElementById('chart-body');
const clientId = clientSel.value ? parseInt(clientSel.value) : null;
const metricId = metricSel.value ? parseInt(metricSel.value) : null;
if (metricId) {
drawBodyMetricsGraph(canvas, clientId, metricId);
}
}
};
// Первичная отрисовка (пустые состояния)
DashboardLogic.updateExerciseChart();
if(state.metricTypes.length > 0) {
document.getElementById('dash-metric-select').value = state.metricTypes[0].id;
DashboardLogic.updateBodyChart();
}
}
function getUniqueExercises() {
const set = new Set();
state.workouts.forEach(w => {
w.exercises.forEach(ex => {
set.add(ex.name);
});
});
return Array.from(set).sort();
}
+381
View File
@@ -0,0 +1,381 @@
// frontend/js/render/dashboard.js
import { state } from '../state.js';
import { formatDate } from '../utils.js';
/**
* Рисует линейный график прогресса упражнения
* @param {HTMLCanvasElement} canvas
* @param {string} exerciseName
*/
export function drawExerciseProgress(canvas, exerciseName) {
const ctx = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;
ctx.clearRect(0, 0, width, height);
const history = getCumulativeExerciseHistory(exerciseName);
if (history.length < 2) {
drawEmptyState(ctx, width, height, "Недостаточно данных\nНужно минимум 2 тренировки");
return;
}
// Находим максимальный ИТОГОВЫЙ объем для масштабирования оси Y
const maxVolume = Math.max(...history.map(h => h.totalVolume));
const padding = { top: 20, right: 20, bottom: 30, left: 40 };
const chartW = width - padding.left - padding.right;
const chartH = height - padding.top - padding.bottom;
// Рисуем сетку (используем maxVolume для оси Y)
drawGridAndAxes(ctx, padding, chartW, chartH, maxVolume, 'Дата', 'Общий вес (кг)');
// Рисуем новый график со стеком
drawCumulativeVolumeChart(ctx, history, padding, chartW, chartH, maxVolume);
// Легенда (обновленная)
drawLegend(ctx, width, [
{ color: '#bb86fc', label: 'Итоговый объем' },
{ color: 'rgba(187, 134, 252, 0.4)', label: 'Накопление по подходам' }
]);
}
/**
* Рисует график динамики телесных замеров
* @param {HTMLCanvasElement} canvas
* @param {number|null} clientId - null для личных замеров
* @param {number} metricTypeId - ID типа замера (например, вес)
*/
export function drawBodyMetricsGraph(canvas, clientId, metricTypeId) {
const ctx = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;
ctx.clearRect(0, 0, width, height);
// Фильтруем замеры
const metrics = state.bodyMetrics
.filter(m => m.client_id == clientId)
.sort((a, b) => new Date(a.date) - new Date(b.date));
// Извлекаем значения конкретного типа
const dataPoints = [];
metrics.forEach(m => {
const valObj = m.values?.find(v => v.metric_type_id == metricTypeId);
if (valObj && valObj.value !== undefined && valObj.value !== null) {
dataPoints.push({ date: new Date(m.date), value: parseFloat(valObj.value) });
}
});
if (dataPoints.length < 2) {
drawEmptyState(ctx, width, height, "Недостаточно данных\nНужно минимум 2 замера");
return;
}
const minVal = Math.min(...dataPoints.map(p => p.value));
const maxVal = Math.max(...dataPoints.map(p => p.value));
const range = maxVal - minVal || 1; // Защита от деления на ноль
const padding = { top: 20, right: 20, bottom: 30, left: 40 };
const chartW = width - padding.left - padding.right;
const chartH = height - padding.top - padding.bottom;
// Простая ось Y (значения)
ctx.strokeStyle = '#333';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(padding.left, padding.top);
ctx.lineTo(padding.left, height - padding.bottom);
ctx.stroke();
// Подписи осей Y
ctx.fillStyle = '#b0b0b0';
ctx.font = '10px sans-serif';
ctx.textAlign = 'right';
for (let i = 0; i <= 4; i++) {
const y = height - padding.bottom - (i / 4) * chartH;
const val = minVal + (range * i / 4);
ctx.fillText(val.toFixed(1), padding.left - 5, y + 3);
// Горизонтальная линия сетки
ctx.strokeStyle = '#2c2c2c';
ctx.beginPath();
ctx.moveTo(padding.left, y);
ctx.lineTo(width - padding.right, y);
ctx.stroke();
}
// Рисуем точку начала и конца по X (дата)
const firstDate = dataPoints[0].date.getTime();
const lastDate = dataPoints[dataPoints.length - 1].date.getTime();
const timeRange = lastDate - firstDate || 1;
ctx.strokeStyle = '#bb86fc'; // Цвет линии графика
ctx.lineWidth = 2;
ctx.beginPath();
dataPoints.forEach((p, index) => {
const x = padding.left + ((p.date.getTime() - firstDate) / timeRange) * chartW;
const y = height - padding.bottom - ((p.value - minVal) / range) * chartH;
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
// Точки
ctx.fillStyle = '#fff';
ctx.fillRect(x - 2, y - 2, 4, 4);
});
ctx.stroke();
// Подпись даты слева и справа
ctx.fillStyle = '#b0b0b0';
ctx.textAlign = 'left';
ctx.fillText(formatShortDate(dataPoints[0].date.toISOString()), padding.left, height - 10);
ctx.textAlign = 'right';
ctx.fillText(formatShortDate(dataPoints[dataPoints.length-1].date.toISOString()), width - padding.right, height - 10);
}
/**
* Собирает историю с накопительным весом по каждому подходу
*/
function getCumulativeExerciseHistory(name) {
const normalized = name.trim().toLowerCase();
const history = [];
state.workouts.forEach(w => {
w.exercises.forEach(ex => {
if (ex.name.trim().toLowerCase() === normalized && ex.sets.length > 0) {
let currentCumulativeWeight = 0;
const cumulativePoints = [];
ex.sets.forEach(s => {
// Учитываем вес подхода (для дроп-сетов можно брать средний или максимальный, здесь берем основной)
const setWeight = s.isDropset && s.subSets
? Math.max(...s.subSets.map(ss => ss.weight))
: s.weight;
// Объем подхода = вес * повторения (или просто вес, если вы считаете тоннаж)
// В вашем примере (15, 30, 45, 60) вы суммируете именно вес подходов.
// Если нужно суммировать тоннаж (вес * повторы), замените на: setWeight * s.reps
const volume = setWeight * s.reps;
currentCumulativeWeight += volume;
cumulativePoints.push(currentCumulativeWeight);
});
history.push({
date: new Date(w.startTime),
cumulativePoints: cumulativePoints, // [15, 30, 45, 60]
totalVolume: currentCumulativeWeight // 60
});
}
});
});
history.sort((a, b) => a.date - b.date);
return history.slice(-10); // Последние 10 тренировок
}
// --- Вспомогательные функции ---
function getExerciseHistoryData(name) {
const normalized = name.trim().toLowerCase();
const history = [];
// Собираем из всех тренировок текущего пользователя (или клиента, если режим тренера реализован глобально)
// Здесь упрощение: берем все тренировки из state.workouts
state.workouts.forEach(w => {
w.exercises.forEach(ex => {
if (ex.name.trim().toLowerCase() === normalized && ex.sets.length > 0) {
history.push({
date: new Date(w.startTime),
sets: ex.sets
});
}
});
});
// Сортируем по дате
history.sort((a, b) => a.date - b.date);
return history.slice(-10); // Берем последние 10 тренировок для читаемости
}
function getMaxWeightInSet(historyItem) {
let max = 0;
historyItem.sets.forEach(s => {
if (s.isDropset && s.subSets) {
s.subSets.forEach(ss => { if (ss.weight > max) max = ss.weight; });
} else if (s.weight > max) {
max = s.weight;
}
});
return max;
}
function getMaxRepsInSet(historyItem) {
let max = 0;
historyItem.sets.forEach(s => {
if (s.isDropset && s.subSets) {
s.subSets.forEach(ss => { if (ss.reps > max) max = ss.reps; });
} else if (s.reps > max) {
max = s.reps;
}
});
return max;
}
function drawGridAndAxes(ctx, pad, cw, ch, maxY, maxXAxisLabel, yAxisLabel) {
ctx.strokeStyle = '#333';
ctx.lineWidth = 1;
// Ось Y
ctx.beginPath();
ctx.moveTo(pad.left, pad.top);
ctx.lineTo(pad.left, ch + pad.top);
ctx.stroke();
// Ось X
ctx.beginPath();
ctx.moveTo(pad.left, ch + pad.top);
ctx.lineTo(cw + pad.left, ch + pad.top);
ctx.stroke();
// Подписи Y
ctx.fillStyle = '#b0b0b0';
ctx.font = '10px sans-serif';
ctx.textAlign = 'right';
for(let i=0; i<=4; i++) {
const val = (maxY * i / 4).toFixed(0);
const y = ch + pad.top - (ch * i / 4);
ctx.fillText(val, pad.left - 5, y + 3);
// Сетка
ctx.strokeStyle = '#2c2c2c';
ctx.beginPath();
ctx.moveTo(pad.left, y);
ctx.lineTo(cw + pad.left, y);
ctx.stroke();
}
// Заголовок оси Y
ctx.save();
ctx.translate(15, ch/2 + pad.top);
ctx.rotate(-Math.PI/2);
ctx.textAlign = 'center';
ctx.fillText(yAxisLabel, 0, 0);
ctx.restore();
}
function drawLineChart(ctx, data, pad, cw, ch, maxY, getValueFn, color, lineWidth) {
if (!data.length) return;
ctx.strokeStyle = color;
ctx.lineWidth = lineWidth;
ctx.beginPath();
data.forEach((item, index) => {
const val = getValueFn(item);
const x = pad.left + (index / (data.length - 1)) * cw;
const y = pad.top + ch - (val / maxY) * ch;
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
// Точка
ctx.fillStyle = '#fff';
ctx.fillRect(x-2, y-2, 4, 4);
});
ctx.stroke();
}
/**
* Рисует график прогресса с вертикальным стеком накопительного веса
*/
function drawCumulativeVolumeChart(ctx, data, pad, cw, ch, maxY) {
if (!data.length) return;
// 1. Сначала рисуем соединительную линию для ОБЩИХ итогов (тренд)
ctx.strokeStyle = '#bb86fc'; // Основной цвет (например, фиолетовый)
ctx.lineWidth = 2;
ctx.beginPath();
data.forEach((item, index) => {
const x = pad.left + (index / (data.length - 1 || 1)) * cw;
const y = pad.top + ch - (item.totalVolume / maxY) * ch;
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
// 2. Рисуем вертикальные стеки точек для каждой даты
data.forEach((item, index) => {
const x = pad.left + (index / (data.length - 1 || 1)) * cw;
item.cumulativePoints.forEach((cumWeight, pointIndex) => {
const isLast = pointIndex === item.cumulativePoints.length - 1;
const y = pad.top + ch - (cumWeight / maxY) * ch;
ctx.beginPath();
if (isLast) {
// Финальная точка: крупная, непрозрачная, с белой обводкой для контраста
ctx.fillStyle = '#bb86fc';
ctx.arc(x, y, 5, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = '#ffffff';
ctx.lineWidth = 1.5;
ctx.stroke();
} else {
// Промежуточные точки: полупрозрачные, поменьше
ctx.fillStyle = 'rgba(187, 134, 252, 0.4)'; // Тот же цвет, но 40% непрозрачности
ctx.arc(x, y, 3, 0, Math.PI * 2);
ctx.fill();
}
});
// Опционально: провести бледную вертикальную линию от 0 до итоговой точки,
// чтобы визуально связать подходы в один "столбик"
if (item.cumulativePoints.length > 1) {
const bottomY = pad.top + ch; // Ось X
const topY = pad.top + ch - (item.totalVolume / maxY) * ch;
ctx.strokeStyle = 'rgba(187, 134, 252, 0.15)';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(x, bottomY);
ctx.lineTo(x, topY);
ctx.stroke();
}
});
}
function drawLegend(ctx, width, items) {
ctx.font = '10px sans-serif';
ctx.textAlign = 'left';
let xOffset = 10;
items.forEach(item => {
ctx.fillStyle = item.color;
ctx.fillRect(xOffset, 10, 10, 10);
ctx.fillStyle = '#fff';
ctx.fillText(item.label, xOffset + 15, 19);
xOffset += ctx.measureText(item.label).width + 30;
});
}
function drawEmptyState(ctx, w, h, text) {
ctx.fillStyle = '#666';
ctx.font = '14px sans-serif';
ctx.textAlign = 'center';
const lines = text.split('\n');
lines.forEach((line, i) => {
ctx.fillText(line, w/2, h/2 + (i * 20) - (lines.length*10)/2);
});
}
function formatShortDate(isoString) {
return new Date(isoString).toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit' });
}
+60
View File
@@ -0,0 +1,60 @@
import { state } from '../state.js';
import { renderSetRow } from './set-row.js';
export function renderExercise(w, ex, isReadOnly = false) {
const isExpanded = state.expandedExerciseId === ex.id;
const totalSets = ex.sets.length;
const summary = totalSets > 0 ? `${totalSets} подх.` : '';
const card = document.createElement('div');
card.className = 'exercise-card';
card.innerHTML = `
<div class="exercise-header ${isExpanded ? 'expanded' : ''}" onclick="EL.toggleExercise('${ex.id}')">
<div>
<span class="exercise-name">${ex.name}</span>
<span class="exercise-summary">${summary}</span>
</div>
<span class="chevron ${isExpanded ? 'open' : ''}">›</span>
</div>
`;
const body = document.createElement('div');
body.className = `exercise-body ${isExpanded ? 'expanded' : ''}`;
if (isExpanded) {
if (ex.sets.length > 0) {
const table = document.createElement('div');
table.className = 'sets-table';
[...ex.sets].reverse().forEach((set, idx) => {
const realIdx = ex.sets.length - 1 - idx;
table.appendChild(renderSetRow(w.id, ex.id, set, realIdx, isReadOnly));
});
body.appendChild(table);
} else {
body.innerHTML += `<p class="text-muted text-small">Пока нет подходов</p>`;
}
if (!isReadOnly) {
if (!w.endTime) {
const addBtn = document.createElement('button');
addBtn.className = 'btn mt-10';
addBtn.textContent = '+ Добавить подход';
addBtn.onclick = () => window.SL.addSet(w.id, ex.id);
body.appendChild(addBtn);
}
const delBtn = document.createElement('button');
delBtn.className = 'btn btn-ghost mt-10';
delBtn.style.width = '100%';
delBtn.textContent = 'Удалить упражнение';
delBtn.onclick = (e) => {
e.stopPropagation();
window.EL.deleteExercise(w.id, ex.id);
};
body.appendChild(delBtn);
}
}
card.appendChild(body);
return card;
}
+59
View File
@@ -0,0 +1,59 @@
import { state, DEFAULT_COLOR } from '../state.js';
import { renderWorkoutCard } from './workout-card.js';
export function renderMainScreen() {
const app = document.getElementById('app');
if (!app) return;
app.innerHTML = '';
// В режиме тренера — подсказка сверху
if (state.mode === 'trainer') {
const hint = document.createElement('div');
hint.className = 'card mb-10';
hint.style.background = 'rgba(187, 134, 252, 0.1)';
hint.style.borderColor = 'var(--primary)';
hint.innerHTML = `
<div style="display:flex; justify-content:space-between; align-items:center;">
<div>
<div style="font-weight:600;">👨‍🏫 Режим тренера</div>
<div class="text-small text-muted">При создании тренировки выберите клиента</div>
</div>
<button class="btn btn-small" onclick="WL.startWorkout()">▶ Новая тренировка</button>
</div>
`;
app.appendChild(hint);
}
// Все тренировки (в обоих режимах)
const workoutsToShow = state.workouts;
if (workoutsToShow.length === 0) {
app.innerHTML = `
<div class="empty-state">
<h3>🏋️ Нет тренировок</h3>
<p>${state.mode === 'trainer' ? 'Создайте первую тренировку для клиента' : 'Начните первую тренировку'}</p>
<button class="btn" onclick="WL.startWorkout()">▶ Начать тренировку</button>
</div>
`;
return;
}
const sorted = [...workoutsToShow].sort((a, b) => {
if (!a.endTime && b.endTime) return -1;
if (a.endTime && !b.endTime) return 1;
return new Date(b.startTime) - new Date(a.startTime);
});
const hasActive = sorted.some(w => !w.endTime);
if (!hasActive) {
const btn = document.createElement('button');
btn.className = 'btn mb-10';
btn.textContent = '▶ Начать новую тренировку';
btn.onclick = () => window.WL.startWorkout();
app.appendChild(btn);
}
sorted.forEach(w => {
app.appendChild(renderWorkoutCard(w));
});
}
+35
View File
@@ -0,0 +1,35 @@
export function renderSetRow(workoutId, exerciseId, set, index, isReadOnly = false) {
const row = document.createElement('div');
const actionsHtml = isReadOnly ? '' : `
<div class="set-actions">
<button class="icon-btn" onclick="SL.editSet('${workoutId}', '${exerciseId}', '${set.id}')">✎</button>
<button class="icon-btn danger" onclick="SL.deleteSet('${workoutId}', '${exerciseId}', '${set.id}')">✕</button>
</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);
row.innerHTML = `
<div class="set-row" style="grid-template-columns: 30px 1fr auto ${isReadOnly ? '0' : 'auto'};">
<div class="set-number">${index + 1}</div>
<div class="set-cell dropset">🔥 ${subsText}</div>
<div class="set-rating">${ratingStars}</div>
${actionsHtml}
</div>
`;
} else {
row.innerHTML = `
<div class="set-row">
<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>
${actionsHtml}
</div>
`;
}
return row;
}
+206
View File
@@ -0,0 +1,206 @@
import { state } from '../state.js';
import { renderExercise } from './exercise-card.js';
import { renderCardioItem } from './cardio-card.js';
import { formatDate } from '../utils.js';
export function renderWorkoutCard(w) {
const isActive = !w.endTime;
const isExpanded = state.expandedWorkoutId === w.id;
const isReadOnly = w.synced && w.endTime;
// Определяем цвет тренировки
let clientColor = null;
let clientName = null;
if (w.client_id) {
const client = state.clients.find(c => c.id == w.client_id);
if (client) {
clientColor = client.color;
clientName = client.full_name;
}
}
const div = document.createElement('div');
div.className = 'workout-accordion';
// Добавляем цветной border-left, если есть клиент
if (clientColor) {
div.style.borderLeft = `4px solid ${clientColor}`;
}
const headerClass = `workout-header ${isActive ? 'active' : 'completed'}`;
const dateStr = formatDate(w.startTime);
const typeStr = w.type || 'тип не выбран';
const exCount = w.exercises.length;
const cardioCount = w.cardio.length;
let statusBadge;
if (isReadOnly) statusBadge = '<span class="workout-badge synced-badge">✓ архив</span>';
else if (w.synced) statusBadge = '<span class="workout-badge synced-badge">✓</span>';
else statusBadge = '<span class="workout-badge dirty">● не сохранено</span>';
const editDateBtn = !isReadOnly
? `<span class="editable-date" onclick="event.stopPropagation(); WL.editWorkoutDate('${w.id}')">
<span class="edit-icon">✎</span>
</span>`
: '';
// Метка клиента (если есть)
const clientLabel = clientName
? `<div class="workout-meta" style="color:${clientColor}; font-weight:600;">👤 ${clientName}</div>`
: '';
div.innerHTML = `
<div class="${headerClass}" onclick="WL.toggleWorkout('${w.id}')">
<div>
<div style="font-weight:600;">${isActive ? '🔥 Тренировка' : '✅ Завершена'}</div>
<div class="workout-meta">${dateStr} ${editDateBtn} • ${typeStr}</div>
${clientLabel}
<div class="workout-meta">Упр: ${exCount} • Кардио: ${cardioCount}</div>
</div>
<div>${statusBadge} <span class="chevron ${isExpanded ? 'open' : ''}">›</span></div>
</div>
`;
const body = document.createElement('div');
body.className = `workout-body ${isExpanded ? 'expanded' : ''}`;
if (isExpanded) {
body.appendChild(renderWorkoutDetails(w));
}
div.appendChild(body);
return div;
}
export function renderWorkoutDetails(w) {
const wrap = document.createElement('div');
const isActive = !w.endTime;
const isReadOnly = w.synced && w.endTime;
if (isReadOnly) {
const banner = document.createElement('div');
banner.className = 'read-only-banner';
banner.textContent = '🔒 Тренировка в архиве — только просмотр';
wrap.appendChild(banner);
}
// Тип тренировки
const typeCard = document.createElement('div');
typeCard.className = 'card';
if (isReadOnly) {
typeCard.innerHTML = `
<div class="field-group" style="margin:0;">
<span class="text-muted text-small">Тип тренировки</span>
<div style="font-weight:600; margin-top:4px;">${w.type || '—'}</div>
</div>`;
} else {
typeCard.innerHTML = `
<label class="field-group" style="margin:0;">
<span>Тип тренировки</span>
<select onchange="App.getWorkout('${w.id}').type = this.value; App.saveAndRender();">
<option value="">— выберите —</option>
<option ${w.type==='грудь-руки'?'selected':''}>грудь-руки</option>
<option ${w.type==='ноги'?'selected':''}>ноги</option>
<option ${w.type==='спина-плечи'?'selected':''}>спина-плечи</option>
<option ${w.type==='круговая'?'selected':''}>круговая</option>
<option ${w.type==='силовая'?'selected':''}>силовая</option>
<option ${w.type==='многоповторная'?'selected':''}>многоповторная</option>
</select>
</label>`;
}
wrap.appendChild(typeCard);
// Кнопки добавления
if (isActive && !isReadOnly) {
const addSection = document.createElement('div');
addSection.className = 'add-section';
addSection.innerHTML = `
<button class="btn btn-secondary" onclick="EL.addExercise('${w.id}')">+ Упражнение</button>
<button class="btn btn-secondary" onclick="CL.addCardio('${w.id}')">+ Кардио</button>
`;
wrap.appendChild(addSection);
}
// Кардио: разминка сверху
const cardioWarmup = w.cardio.filter(c => c.purpose === 'warmup' || c.purpose === 'separate');
const cardioCooldown = w.cardio.filter(c => c.purpose === 'cooldown');
if (cardioWarmup.length > 0) {
const title = document.createElement('h4');
title.style.margin = '16px 0 8px';
title.textContent = '🔥 Разминка / Кардио';
wrap.appendChild(title);
cardioWarmup.forEach(c => wrap.appendChild(renderCardioItem(w.id, c, isReadOnly)));
}
// Упражнения
[...w.exercises].reverse().forEach(ex => {
wrap.appendChild(renderExercise(w, ex, isReadOnly));
});
// Заминка внизу
if (cardioCooldown.length > 0) {
const title = document.createElement('h4');
title.style.margin = '16px 0 8px';
title.textContent = '🧘 Заминка';
wrap.appendChild(title);
cardioCooldown.forEach(c => wrap.appendChild(renderCardioItem(w.id, c, isReadOnly)));
}
// Комментарий
const notesCard = document.createElement('div');
notesCard.className = 'card mt-10';
if (isReadOnly) {
notesCard.innerHTML = `
<div class="field-group" style="margin:0;">
<span class="text-muted text-small">Комментарий</span>
<div style="margin-top:4px; white-space:pre-wrap;">${w.notes || '—'}</div>
</div>`;
} else {
notesCard.innerHTML = `
<label class="field-group" style="margin:0;">
<span>Комментарий к тренировке</span>
<textarea placeholder="Как прошла тренировка...">${w.notes || ''}</textarea>
</label>`;
notesCard.querySelector('textarea').oninput = (e) => {
w.notes = e.target.value;
window.App.saveAndRender();
};
}
wrap.appendChild(notesCard);
// Блок завершения
const finishBlock = document.createElement('div');
finishBlock.className = 'finish-block';
if (isReadOnly) {
finishBlock.innerHTML = `
<h3>🔒 Архив</h3>
<p class="text-muted text-small">Тренировка синхронизирована и завершена. Редактирование недоступно.</p>`;
} else if (isActive) {
// Проверяем, есть ли уже данные в тренировке
const hasData = (w.exercises && w.exercises.length > 0) || (w.cardio && w.cardio.length > 0);
// Кнопка отмены показывается ТОЛЬКО если тренировка пустая
const cancelBtnHtml = !hasData ? `
<button class="btn btn-ghost mt-10" style="color: var(--danger); border-color: var(--danger);" onclick="WL.cancelEmptyWorkout('${w.id}')">
✕ Отменить пустую тренировку
</button>
` : '';
finishBlock.innerHTML = `
<h3>Завершение тренировки</h3>
<p class="text-muted text-small">После завершения данные останутся локально до синхронизации</p>
<div style="display: flex; flex-direction: column; gap: 10px; margin-top: 10px;">
${cancelBtnHtml}
<button class="btn btn-danger" onclick="WL.finishWorkout('${w.id}')">⏹ Закончить тренировку</button>
</div>
`;
} else {
finishBlock.innerHTML = `
<h3>Тренировка завершена</h3>
<p class="text-muted text-small">До синхронизации можно редактировать</p>
<button class="btn btn-danger" onclick="WL.deleteWorkout('${w.id}')">🗑 Удалить</button>`;
}
wrap.appendChild(finishBlock);
return wrap;
}
+167
View File
@@ -0,0 +1,167 @@
// frontend/js/state.js
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",
];
const MIGRATION_FLAG = "gym_tracker_legacy_migrated_to_user";
function freshState() {
return {
workouts: [],
exerciseRef: [],
bodyMetrics: [],
workoutTypes: [],
metricTypes: [],
clients: [],
expandedWorkoutId: null,
expandedExerciseId: null,
nextId: 1,
mode: "personal",
currentClientId: null,
};
}
export const state = freshState();
// Внутренняя переменная для хранения текущего пользователя (не сохраняется в localStorage напрямую)
let activeUser = null;
/**
* Установить текущего пользователя после логина
*/
export function setActiveUser(user) {
activeUser = user;
}
/**
* Получить данные текущего пользователя
*/
export function getActiveUser() {
return activeUser;
}
/**
* Сбросить состояние при логауте
*/
export function resetState() {
Object.assign(state, freshState());
activeUser = null;
}
function storageKey() {
return activeUser
? `${CURRENT_STORAGE_PREFIX}${activeUser.id}`
: GUEST_STORAGE_KEY;
}
export function migrateLegacyStateForUser() {
if (!activeUser) return;
// Уже мигрировали — не трогаем
if (localStorage.getItem(MIGRATION_FLAG)) return;
const key = storageKey();
// Если у пользователя уже есть данные — просто помечаем миграцию выполненной
if (localStorage.getItem(key)) {
localStorage.setItem(MIGRATION_FLAG, String(activeUser.id));
return;
}
// Ищем старые данные и переносим первому вошедшему пользователю
for (const legacyKey of LEGACY_KEYS) {
const raw = localStorage.getItem(legacyKey);
if (raw) {
localStorage.setItem(key, raw);
localStorage.setItem(MIGRATION_FLAG, String(activeUser.id));
return;
}
}
}
export function loadState() {
migrateLegacyStateForUser();
const raw = localStorage.getItem(storageKey());
Object.assign(state, freshState());
if (raw) {
try {
const parsed = JSON.parse(raw);
Object.assign(state, parsed);
} catch (e) {
console.error("Failed to load state", e);
}
}
if (!Array.isArray(state.workouts)) state.workouts = [];
if (!Array.isArray(state.exerciseRef)) state.exerciseRef = [];
if (!Array.isArray(state.bodyMetrics)) state.bodyMetrics = [];
if (!Array.isArray(state.workoutTypes)) state.workoutTypes = [];
if (!Array.isArray(state.metricTypes)) state.metricTypes = [];
if (!Array.isArray(state.clients)) state.clients = [];
if (!state.mode) state.mode = "personal";
}
export function saveState() {
localStorage.setItem(storageKey(), JSON.stringify(state));
updateSyncStatus();
}
export function genId() {
return (state.nextId++).toString();
}
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);
});
}
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";
}
}
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];
+861
View File
@@ -0,0 +1,861 @@
// 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";
// ============================================================
// Хелперы
// ============================================================
function asString(value) {
if (value === undefined || value === null) return "";
return String(value);
}
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) {
if (!obj) return null;
if (!obj.sync_id) {
obj.sync_id = generateUUID();
}
return obj.sync_id;
}
// ============================================================
// Миграция локальных ID в sync_id
// ============================================================
/**
* Делает локальные ID совместимыми с серверными sync_id.
*
* Важно:
* - тренировки, упражнения, подходы, кардио, замеры, справочник упражнений
* переводим на sync_id как основной локальный id;
* - клиенты остаются с числовым server_id, если он есть, потому что
* API клиентов использует /clients/{id} с числовым id.
*/
function migrateLocalIdsToSyncId() {
const clientOldToNew = new Map();
// Клиенты
for (const client of state.clients || []) {
const oldId = asString(client.id);
if (!client.sync_id) {
client.sync_id = generateUUID();
}
// Если клиент уже синхронизирован, используем серверный числовой id
if (client.server_id) {
client.id = asString(client.server_id);
} else if (!client.id) {
client.id = asString(client.sync_id);
}
const newId = asString(client.id);
if (oldId && newId && oldId !== newId) {
clientOldToNew.set(oldId, newId);
}
}
// Тренировки
for (const workout of state.workouts || []) {
const oldClientKey = asString(workout.client_id);
if (oldClientKey && clientOldToNew.has(oldClientKey)) {
workout.client_id = clientOldToNew.get(oldClientKey);
}
if (!workout.sync_id) {
workout.sync_id = generateUUID();
}
const oldWorkoutId = asString(workout.id);
const newWorkoutId = asString(workout.sync_id);
workout.id = newWorkoutId;
if (asString(state.expandedWorkoutId) === oldWorkoutId) {
state.expandedWorkoutId = newWorkoutId;
}
for (const exercise of workout.exercises || []) {
if (!exercise.sync_id) {
exercise.sync_id = generateUUID();
}
const oldExerciseId = asString(exercise.id);
const newExerciseId = asString(exercise.sync_id);
exercise.id = newExerciseId;
if (asString(state.expandedExerciseId) === oldExerciseId) {
state.expandedExerciseId = newExerciseId;
}
for (const set of exercise.sets || []) {
if (!set.sync_id) {
set.sync_id = generateUUID();
}
set.id = asString(set.sync_id);
}
}
for (const cardio of workout.cardio || []) {
if (!cardio.sync_id) {
cardio.sync_id = generateUUID();
}
cardio.id = asString(cardio.sync_id);
}
}
// Замеры
for (const metric of state.bodyMetrics || []) {
const oldClientKey = asString(metric.client_id);
if (oldClientKey && clientOldToNew.has(oldClientKey)) {
metric.client_id = clientOldToNew.get(oldClientKey);
}
if (!metric.sync_id) {
metric.sync_id = generateUUID();
}
metric.id = asString(metric.sync_id);
}
// Справочник упражнений
for (const exercise of state.exerciseRef || []) {
if (!exercise.sync_id) {
exercise.sync_id = generateUUID();
}
exercise.id = asString(exercise.sync_id);
}
}
// ============================================================
// Конвертация backend -> frontend
// ============================================================
function convertBackendClient(c) {
const syncId = c.sync_id || generateUUID();
const serverId = asString(c.id);
return {
id: serverId || syncId,
sync_id: syncId,
server_id: serverId || null,
full_name: c.full_name || "",
birth_date: c.birth_date || "",
goal: c.goal || "",
notes: c.notes || "",
color: c.color || DEFAULT_COLOR,
is_active: c.is_active ?? 1,
};
}
function convertBackendExercise(e, workoutTypeNameById) {
const syncId = e.sync_id || generateUUID();
return {
id: syncId,
sync_id: syncId,
server_id: e.id ?? null,
name: e.name || "",
workoutType: e.workout_type_id
? workoutTypeNameById[asString(e.workout_type_id)] || ""
: "",
};
}
function convertBackendWorkoutToFrontend(w) {
const workoutSyncId = w.sync_id || generateUUID();
// Используем подготовленное имя типа из бэкенда, если оно есть, иначе ищем по ID
let typeStr = w.workout_type_name;
if (!typeStr && w.workout_type_id) {
const wt = state.workoutTypes.find(t => String(t.id) === String(w.workout_type_id));
typeStr = wt ? wt.name : "";
}
return {
id: workoutSyncId,
sync_id: workoutSyncId,
server_id: w.id ?? null,
client_id: w.client_id ? asString(w.client_id) : null,
startTime: w.start_time || new Date().toISOString(),
endTime: w.end_time || null,
type: typeStr || "", // Имя типа тренировки
notes: w.notes || "",
synced: true,
exercises: (w.workout_exercises || []).map((ex) => {
const exSyncId = ex.sync_id || generateUUID();
return {
id: exSyncId,
sync_id: exSyncId,
server_id: ex.id ?? null,
exercise_id: ex.exercise_id ?? null,
name: ex.exercise_name || "",
sort_order: ex.sort_order ?? 0,
sets: (ex.sets || []).map((s) => {
const setSyncId = s.sync_id || generateUUID();
return {
id: setSyncId,
sync_id: setSyncId,
server_id: s.id ?? null,
isDropset: !!s.is_dropset,
weight: s.weight ?? null,
reps: s.reps ?? null,
rating: s.rating ?? 3,
notes: s.notes || "",
timestamp: s.timestamp || w.start_time || new Date().toISOString(),
sort_order: s.sort_order ?? 0,
subSets: (s.dropset_items || []).map((di) => ({
weight: di.weight ?? 0,
reps: di.reps ?? 0,
sort_order: di.sort_order ?? 0,
})),
};
}),
};
}),
cardio: (w.cardio_sessions || []).map((c) => {
const cardioSyncId = c.sync_id || generateUUID();
return {
id: cardioSyncId,
sync_id: cardioSyncId,
server_id: c.id ?? null,
type: c.cardio_type || "",
purpose: c.purpose || "separate",
duration: c.duration ?? null,
distance: c.distance ?? null,
speed: c.speed ?? null,
incline: c.incline ?? null,
resistance: c.resistance ?? null,
notes: c.notes || "",
sort_order: c.sort_order ?? 0,
};
}),
};
}
function convertBackendWorkout(w, workoutTypeNameById) {
const workoutSyncId = w.sync_id || generateUUID();
return {
id: workoutSyncId,
sync_id: workoutSyncId,
server_id: w.id ?? null,
client_id: w.client_id ? asString(w.client_id) : null,
startTime: w.start_time || new Date().toISOString(),
endTime: w.end_time || null,
type: w.workout_type_id
? workoutTypeNameById[asString(w.workout_type_id)] || ""
: "",
notes: w.notes || "",
synced: true,
exercises: (w.workout_exercises || []).map((ex) => {
const exSyncId = ex.sync_id || generateUUID();
return {
id: exSyncId,
sync_id: exSyncId,
server_id: ex.id ?? null,
exercise_id: ex.exercise_id ?? null,
name: ex.exercise_name || "",
sort_order: ex.sort_order ?? 0,
sets: (ex.sets || []).map((s) => {
const setSyncId = s.sync_id || generateUUID();
return {
id: setSyncId,
sync_id: setSyncId,
server_id: s.id ?? null,
isDropset: !!s.is_dropset,
weight: s.weight ?? null,
reps: s.reps ?? null,
rating: s.rating ?? 3,
notes: s.notes || "",
timestamp: s.timestamp || w.start_time || new Date().toISOString(),
sort_order: s.sort_order ?? 0,
subSets: (s.dropset_items || []).map((di) => ({
weight: di.weight ?? 0,
reps: di.reps ?? 0,
sort_order: di.sort_order ?? 0,
})),
};
}),
};
}),
cardio: (w.cardio_sessions || []).map((c) => {
const cardioSyncId = c.sync_id || generateUUID();
return {
id: cardioSyncId,
sync_id: cardioSyncId,
server_id: c.id ?? null,
type: c.cardio_type || "",
purpose: c.purpose || "separate",
duration: c.duration ?? null,
distance: c.distance ?? null,
speed: c.speed ?? null,
incline: c.incline ?? null,
resistance: c.resistance ?? null,
notes: c.notes || "",
sort_order: c.sort_order ?? 0,
};
}),
};
}
function convertBackendMetric(m) {
const metricSyncId = m.sync_id || generateUUID();
return {
id: metricSyncId,
sync_id: metricSyncId,
server_id: m.id ?? null,
client_id: m.client_id ? asString(m.client_id) : null,
date: m.metric_date || new Date().toISOString(),
notes: m.notes || "",
values: (m.values || []).map((v) => ({
metric_type_id: v.metric_type_id,
value: v.value,
})),
};
}
// ============================================================
// Merge локальных и серверных данных
// ============================================================
function mergeBySyncId(localItems, serverItems, options = {}) {
const map = new Map();
// Сначала серверные данные
for (const item of serverItems || []) {
const key = item?.sync_id;
if (key) {
map.set(key, item);
}
}
// Потом локальные
for (const item of localItems || []) {
const key = item?.sync_id;
if (!key) {
// На всякий случай: если вдруг нет sync_id, сохраняем локальное по id
map.set(`local:${item?.id}`, item);
continue;
}
const shouldKeepLocal =
options.localWinsIfDirty && item.synced === false;
if (shouldKeepLocal) {
// Несинхронизированная локальная тренировка важнее серверной копии
map.set(key, item);
} else if (!map.has(key)) {
map.set(key, item);
}
}
return Array.from(map.values());
}
function mergeClients(localItems, serverItems) {
// 1. Merge по sync_id
const bySync = new Map();
for (const item of serverItems || []) {
if (item?.sync_id) {
bySync.set(item.sync_id, item);
}
}
for (const item of localItems || []) {
if (!item?.sync_id) continue;
// Серверный клиент важнее локального с тем же sync_id
if (!bySync.has(item.sync_id)) {
bySync.set(item.sync_id, item);
}
}
// 2. Deduplicate по id, чтобы не было двух клиентов с одним числовым id
const byId = new Map();
for (const item of bySync.values()) {
const id = asString(item.id);
if (!id) continue;
const existing = byId.get(id);
if (!existing) {
byId.set(id, item);
} else if (item.server_id && !existing.server_id) {
// Серверный клиент побеждает локальный при конфликте id
byId.set(id, item);
}
}
return Array.from(byId.values());
}
function mergeExerciseRef(localItems, serverItems) {
// Справочник упражнений лучше мержить по имени,
// иначе могут появиться дубли "Жим лежа" с разными sync_id.
const map = new Map();
for (const item of serverItems || []) {
const key = normalizeName(item.name);
if (key) {
map.set(key, item);
}
}
for (const item of localItems || []) {
const key = normalizeName(item.name);
if (key && !map.has(key)) {
map.set(key, item);
}
}
return Array.from(map.values()).sort((a, b) =>
String(a.name || "").localeCompare(String(b.name || ""))
);
}
function resolveClientId(rawId, clients) {
const key = asString(rawId);
if (!key) return null;
// Ищем по id
const byId = (clients || []).find((c) => asString(c.id) === key);
if (byId) return asString(byId.id);
// Ищем по sync_id
const bySync = (clients || []).find((c) => asString(c.sync_id) === key);
if (bySync) return asString(bySync.id);
// Если не нашли — оставляем как есть
return key;
}
function reconcileClientReferences() {
for (const workout of state.workouts || []) {
workout.client_id = resolveClientId(workout.client_id, state.clients);
}
for (const metric of state.bodyMetrics || []) {
metric.client_id = resolveClientId(metric.client_id, state.clients);
}
}
// ============================================================
// Загрузка данных пользователя с сервера
// ============================================================
export async function initAppData() {
try {
console.log("🔄 Загружаем bootstrap-данные с сервера...");
const data = await fetchBootstrapData();
// Сначала нормализуем локальные ID, чтобы корректно смержить
migrateLocalIdsToSyncId();
// Справочники
state.workoutTypes = Array.isArray(data.workout_types)
? data.workout_types
: [];
state.metricTypes = Array.isArray(data.metric_types)
? data.metric_types
: [];
const workoutTypeNameById = {};
for (const wt of state.workoutTypes || []) {
workoutTypeNameById[asString(wt.id)] = wt.name;
}
// Клиенты
const serverClients = (data.clients || []).map(convertBackendClient);
state.clients = mergeClients(state.clients || [], serverClients);
// Упражнения / справочник
const serverExercises = (data.exercises || []).map((e) =>
convertBackendExercise(e, workoutTypeNameById)
);
state.exerciseRef = mergeExerciseRef(
state.exerciseRef || [],
serverExercises
);
// Тренировки
const serverWorkouts = (data.workouts || []).map((w) =>
convertBackendWorkout(w, workoutTypeNameById)
);
state.workouts = mergeBySyncId(
state.workouts || [],
serverWorkouts,
{ localWinsIfDirty: true }
);
// Замеры
const serverMetrics = (data.body_metrics || []).map(convertBackendMetric);
state.bodyMetrics = mergeBySyncId(
state.bodyMetrics || [],
serverMetrics
);
// Чиним ссылки на клиентов после merge
reconcileClientReferences();
saveState();
renderMainScreen();
console.log(
`✅ Bootstrap загружен: тренировок ${state.workouts.length}, клиентов ${state.clients.length}, замеров ${state.bodyMetrics.length}`
);
} catch (e) {
console.warn("❌ Bootstrap не удался, пробуем загрузить только справочники:", e);
try {
const [workoutTypes, metricTypes] = await Promise.all([
fetchWorkoutTypes(),
fetchMetricTypes(),
]);
state.workoutTypes = Array.isArray(workoutTypes) ? workoutTypes : [];
state.metricTypes = Array.isArray(metricTypes) ? metricTypes : [];
saveState();
renderMainScreen();
console.log("✅ Справочники загружены отдельно");
} catch (e2) {
console.warn("❌ Не удалось загрузить даже справочники:", e2);
if (!Array.isArray(state.workoutTypes)) state.workoutTypes = [];
if (!Array.isArray(state.metricTypes)) state.metricTypes = [];
}
}
}
// ============================================================
// Синхронизация frontend -> backend
// ============================================================
export function getDirtyWorkouts() {
return state.workouts.filter((w) => !w.synced);
}
function findWorkoutTypeByName(name) {
if (!name) return null;
return state.workoutTypes.find((t) => t.name === name) || null;
}
function findExerciseRefByName(name) {
const normalized = normalizeName(name);
if (!normalized) return null;
return (
state.exerciseRef.find(
(e) => normalizeName(e.name) === normalized
) || null
);
}
function findClientByLocalId(clientId) {
const key = asString(clientId);
if (!key) return null;
return (
state.clients.find(
(c) => asString(c.id) === key || asString(c.sync_id) === key
) || null
);
}
function buildClientsPayload() {
return (state.clients || []).map((c) => {
ensureSyncId(c);
return {
sync_id: c.sync_id,
full_name: c.full_name || "Без имени",
birth_date: c.birth_date || null,
goal: c.goal || "",
notes: c.notes || "",
color: c.color || null,
is_active: c.is_active === undefined ? 1 : c.is_active,
};
});
}
function buildExercisesPayload() {
return (state.exerciseRef || []).map((e) => {
ensureSyncId(e);
const wt = findWorkoutTypeByName(e.workoutType);
return {
sync_id: e.sync_id,
name: e.name,
workout_type_id: wt ? wt.id : null,
};
});
}
function buildSetsPayload(sets) {
return (sets || []).map((s, setIndex) => {
ensureSyncId(s);
const isDropset = !!s.isDropset;
return {
sync_id: s.sync_id,
is_dropset: isDropset ? 1 : 0,
weight: isDropset ? null : toNumberOrNull(s.weight),
reps: isDropset ? null : toIntOrNull(s.reps),
rating: toIntOrNull(s.rating) ?? 3,
notes: s.notes || "",
sort_order: s.sort_order ?? setIndex,
timestamp: s.timestamp || new Date().toISOString(),
dropset_items: isDropset
? (s.subSets || [])
.map((item, itemIndex) => ({
weight: toNumberOrNull(item.weight) ?? 0,
reps: toIntOrNull(item.reps) ?? 0,
sort_order: item.sort_order ?? itemIndex,
}))
.filter((item) => item.weight > 0 && item.reps > 0)
: [],
};
});
}
function buildWorkoutExercisesPayload(exercises) {
return (exercises || []).map((ex, exIndex) => {
ensureSyncId(ex);
const exerciseRef = findExerciseRefByName(ex.name);
return {
sync_id: ex.sync_id,
exercise_sync_id: exerciseRef ? exerciseRef.sync_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),
};
});
}
function buildCardioPayload(cardioList) {
return (cardioList || []).map((c, cIndex) => {
ensureSyncId(c);
return {
sync_id: c.sync_id,
cardio_type: c.type || "другое",
purpose: c.purpose || "separate",
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,
};
});
}
function buildWorkoutsPayload(dirty) {
return dirty.map((w) => {
ensureSyncId(w);
const client = findClientByLocalId(w.client_id);
const wt = findWorkoutTypeByName(w.type);
return {
sync_id: w.sync_id,
// Для клиентов отправляем именно sync_id,
// потому что локальный id может отличаться на разных устройствах.
client_id: null,
client_sync_id: client ? client.sync_id : null,
workout_type_id: wt ? wt.id : null,
start_time: w.startTime,
end_time: w.endTime || null,
notes: w.notes || "",
workout_exercises: buildWorkoutExercisesPayload(w.exercises),
cardio_sessions: buildCardioPayload(w.cardio),
};
});
}
// ... предыдущие импорты и хелперы остаются ...
export async function sync() {
const dirtyWorkouts = getDirtyWorkouts();
const dirtyMetrics = getDirtyMetrics(); // Новая функция
if (dirtyWorkouts.length === 0 && dirtyMetrics.length === 0) {
alert("Нет данных для синхронизации");
return;
}
const btn = document.querySelector(".header-actions .btn-secondary");
if (btn) {
btn.disabled = true;
btn.textContent = "⏳";
}
try {
// Генерируем sync_id для всего необходимого
ensureSyncIds(dirtyWorkouts, dirtyMetrics);
const payload = {
clients: buildClientsPayload(),
exercises: buildExercisesPayload(),
workouts: buildWorkoutsPayload(dirtyWorkouts),
body_metrics: buildMetricsPayload(dirtyMetrics), // Отправляем замеры
};
console.log("📤 Sending sync payload:", payload);
const response = await syncData(payload);
console.log("✅ Sync response:", response);
// Помечаем все как синхронизированные
dirtyWorkouts.forEach(w => w.synced = true);
dirtyMetrics.forEach(m => m.synced = true);
saveState();
if (typeof window.renderMainScreen === "function") {
window.renderMainScreen();
}
const createdW = response.created?.workouts || 0;
const createdM = response.created?.body_metrics || 0;
let message = `Синхронизировано:\nТренировок: ${createdW}\nЗамеров: ${createdM}`;
if (response.warnings?.length) {
message += `\n\nПредупреждения:\n${response.warnings.join("\n")}`;
}
alert(message);
} catch (e) {
console.error("❌ Sync error:", e);
alert("Ошибка синхронизации: " + e.message);
} finally {
if (btn) {
btn.disabled = false;
btn.textContent = "🔄";
}
}
}
// --- НОВЫЕ ХЕЛПЕРЫ ДЛЯ ЗАМЕРОВ ---
function getDirtyMetrics() {
return state.bodyMetrics.filter(m => !m.synced);
}
function ensureSyncIds(workouts, metrics) {
// Тренировки
workouts.forEach(w => {
if (!w.sync_id) w.sync_id = generateUUID();
(w.exercises || []).forEach(ex => {
if (!ex.sync_id) ex.sync_id = generateUUID();
(ex.sets || []).forEach(s => {
if (!s.sync_id) s.sync_id = generateUUID();
});
});
(w.cardio || []).forEach(c => {
if (!c.sync_id) c.sync_id = generateUUID();
});
});
// Замеры
metrics.forEach(m => {
if (!m.sync_id) m.sync_id = generateUUID();
});
}
function buildMetricsPayload(metrics) {
return metrics.map(m => {
// Ищем server_id клиента, если есть
let clientServerId = null;
if (m.client_id) {
const client = state.clients.find(c => String(c.id) === String(m.client_id));
if (client && client.server_id) {
clientServerId = client.server_id;
} else if (client && client.sync_id) {
// Если нет server_id, но есть sync_id, бэк может найти его по sync_id
// Но в нашей схеме BodyMetricCreate ожидает client_id (int) или client_sync_id (str)?
// Смотрим schemas.py: BodyMetricCreate имеет client_id: Optional[int] и client_sync_id: Optional[str]
// Лучше отправить sync_id, если server_id неизвестен
return {
sync_id: m.sync_id,
client_sync_id: client.sync_id,
metric_date: m.date,
notes: m.notes || "",
values: (m.values || []).map(v => ({
metric_type_id: v.metric_type_id,
value: v.value
}))
};
}
}
return {
sync_id: m.sync_id,
client_id: clientServerId, // Числовой ID, если известен
metric_date: m.date,
notes: m.notes || "",
values: (m.values || []).map(v => ({
metric_type_id: v.metric_type_id,
value: v.value
}))
};
});
}
+28
View File
@@ -0,0 +1,28 @@
export function formatDate(isoString) {
const d = new Date(isoString);
return d.toLocaleDateString('ru-RU') + ' ' +
d.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });
}
export function formatShortDate(isoString) {
return new Date(isoString).toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit' });
}
export function formatSet(set) {
if (set.isDropset && set.subSets) {
return set.subSets.map(s => `${s.weight}×${s.reps}`).join('-');
}
return `${set.weight}×${set.reps}`;
}
export function escapeHtml(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
export function toDatetimeLocal(isoString) {
const d = new Date(isoString);
const pad = n => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
+33
View File
@@ -0,0 +1,33 @@
server {
listen 80;
server_name localhost;
# Статика фронтенда
location / {
root /usr/share/nginx/html;
index index.html;
try_files $uri $uri/ /index.html;
}
# Проксирование API на бэкенд
location /api/ {
proxy_pass http://backend:8000/;
# КРИТИЧЕСКИ ВАЖНЫЕ ЗАГОЛОВКИ ДЛЯ JWT/AUTHORIZATION
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# ЭТА СТРОКА ИСПРАВЛЯЕТ ОШИБКУ 401:
proxy_set_header Authorization $http_authorization;
# Для WebSocket (если понадобится в будущем)
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# Убираем префикс /api, так как бэк ожидает пути вроде /auth/login
rewrite ^/api/(.*)$ /$1 break;
}
}
+132
View File
@@ -0,0 +1,132 @@
/* === Buttons === */
.btn {
background-color: var(--primary);
color: #000;
border: none;
border-radius: var(--radius);
padding: 14px 20px;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
width: 100%;
text-align: center;
transition: opacity 0.15s;
}
.btn:active { opacity: 0.7; }
.btn:disabled { opacity: 0.4; cursor: not-allowed; }
.btn-secondary { background-color: var(--surface-2); color: var(--text); border: 1px solid var(--border); }
.btn-danger { background-color: var(--danger); color: #fff; }
.btn-success { background-color: var(--success); color: #000; }
.btn-small { width: auto; padding: 8px 14px; font-size: 0.9rem; }
.btn-ghost {
background: transparent; border: 1px solid var(--border); color: var(--text-secondary);
padding: 6px 10px; font-size: 0.85rem; width: auto; border-radius: 6px;
}
.btn-row { display: flex; gap: 8px; margin-top: 10px; }
.btn-row .btn { flex: 1; }
/* === Cards === */
.card {
background-color: var(--surface); border-radius: var(--radius);
padding: 14px; margin-bottom: 12px; border: 1px solid var(--border);
}
/* === Sync status === */
.sync-status { font-size: 0.75rem; color: var(--text-secondary); display: flex; align-items: center; gap: 5px; margin-top: 2px; }
.sync-status.synced { color: var(--success); }
.sync-status.pending { color: var(--warning); }
/* === Inputs === */
input, select, textarea {
background-color: var(--surface-2); border: 1px solid var(--border); color: var(--text);
border-radius: 8px; padding: 13px; font-size: 1rem; width: 100%; font-family: inherit;
}
input:focus, select:focus, textarea:focus { outline: 2px solid var(--primary); border-color: transparent; }
input[type="number"] { text-align: center; font-weight: 600; }
textarea { resize: vertical; min-height: 60px; }
/* === Stepper === */
.stepper-field {
display: flex; align-items: center; background: var(--surface-2);
border: 1px solid var(--border); border-radius: 8px; overflow: hidden;
}
.stepper-field .stepper-btn {
background: transparent; border: none; color: var(--primary); font-size: 1.3rem;
font-weight: bold; padding: 10px 12px; cursor: pointer; flex-shrink: 0; min-width: 44px;
}
.stepper-field .stepper-btn:active { background: var(--surface); }
.stepper-field input {
border: none; background: transparent; text-align: center; padding: 10px 4px;
font-size: 1rem; font-weight: 600; flex: 1; min-width: 0;
}
.stepper-field input:focus { outline: none; }
.stepper-row {
display: flex; gap: 6px; margin-bottom: 8px; align-items: center; flex-wrap: nowrap;
}
.stepper-row .stepper-field { flex: 1; min-width: 0; }
/* === Rating === */
.rating-grid { display: grid; grid-template-columns: repeat(5, 1fr); gap: 6px; margin: 10px 0; }
.rating-btn {
background: var(--surface-2); border: 1px solid var(--border); color: var(--text);
border-radius: 8px; padding: 14px 0; font-size: 1.1rem; font-weight: 600; cursor: pointer;
}
.rating-btn.active { background-color: var(--warning); color: #000; border-color: var(--warning); }
/* === Icon buttons === */
.icon-btn {
background: transparent; border: none; color: var(--text-secondary);
padding: 6px 8px; cursor: pointer; border-radius: 4px; font-size: 1rem;
}
.icon-btn:active { background: var(--surface-2); }
.icon-btn.danger { color: var(--danger); }
/* === Empty state === */
.empty-state { text-align: center; padding: 40px 20px; color: var(--text-secondary); }
.empty-state h3 { color: var(--text); margin-bottom: 10px; }
/* === Read-only === */
.read-only-banner {
background: var(--success); color: #000; padding: 8px 12px;
border-radius: 8px; font-size: 0.85rem; font-weight: 600; text-align: center; margin-bottom: 12px;
}
/* === Client select list (в модалке) === */
.client-select-list {
max-height: 60vh;
overflow-y: auto;
}
.client-select-item {
display: flex;
align-items: center;
padding: 14px;
background: var(--surface-2);
border-radius: 8px;
margin-bottom: 8px;
cursor: pointer;
transition: background 0.15s;
}
.client-select-item:active {
background: var(--surface);
}
/* === Color palette (в настройках клиента) === */
.color-palette {
display: grid;
grid-template-columns: repeat(8, 1fr);
gap: 6px;
margin-top: 8px;
}
.color-swatch {
aspect-ratio: 1;
border-radius: 6px;
cursor: pointer;
border: 2px solid transparent;
transition: transform 0.1s;
}
.color-swatch:active { transform: scale(0.9); }
.color-swatch.selected {
border-color: var(--text);
box-shadow: 0 0 0 2px var(--bg), 0 0 0 4px var(--text);
}
+57
View File
@@ -0,0 +1,57 @@
:root {
--bg: #121212;
--surface: #1e1e1e;
--surface-2: #2c2c2c;
--primary: #bb86fc;
--primary-variant: #3700b3;
--text: #ffffff;
--text-secondary: #b0b0b0;
--success: #03dac6;
--danger: #cf6679;
--warning: #fbbc04;
--border: #333333;
--radius: 10px;
}
* {
box-sizing: border-box;
touch-action: manipulation;
-webkit-tap-highlight-color: transparent;
}
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
background-color: var(--bg);
color: var(--text);
padding-bottom: 40px;
}
header {
background-color: var(--surface);
padding: 14px 16px;
position: sticky;
top: 0;
z-index: 50;
border-bottom: 1px solid var(--border);
display: flex;
justify-content: space-between;
align-items: center;
}
h1, h2, h3, h4 { margin: 0; }
h2 { font-size: 1.15rem; }
h3 { font-size: 1.05rem; }
.container { padding: 12px; }
.header-actions { display: flex; gap: 8px; align-items: center; }
.header-btn { font-size: 1.3rem; padding: 8px 10px; }
.hidden { display: none !important; }
.text-muted { color: var(--text-secondary); font-size: 0.85rem; }
.text-small { font-size: 0.8rem; }
.mt-10 { margin-top: 10px; }
.mt-20 { margin-top: 20px; }
.mb-10 { margin-bottom: 10px; }
.divider { height: 1px; background: var(--border); margin: 12px 0; }
+25
View File
@@ -0,0 +1,25 @@
/* === Modal === */
.modal-overlay {
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
background: rgba(0,0,0,0.85); z-index: 100; display: flex;
align-items: flex-end; justify-content: center; animation: fadeIn 0.2s;
}
.modal-content {
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;
}
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
@keyframes slideUp { from { transform: translateY(100%); } to { transform: translateY(0); } }
.modal-title { margin-bottom: 16px; }
.field-group { margin-bottom: 14px; }
.field-group label { display: block; font-size: 0.85rem; color: var(--text-secondary); margin-bottom: 6px; }
.field-row { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
.field-row-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; }
/* === Autocomplete === */
.autocomplete-list { background: var(--surface-2); border: 1px solid var(--border); border-radius: 8px; max-height: 200px; overflow-y: auto; margin-top: 6px; }
.autocomplete-item { padding: 12px 14px; cursor: pointer; border-bottom: 1px solid var(--border); font-size: 0.95rem; }
.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); }
+18
View File
@@ -0,0 +1,18 @@
/* === Settings === */
.settings-screen { padding: 12px; }
.settings-section { margin-bottom: 24px; }
.settings-section h3 { color: var(--primary); margin-bottom: 12px; padding-bottom: 8px; border-bottom: 1px solid var(--border); }
.exercise-ref-item {
display: flex; justify-content: space-between; align-items: center; padding: 12px;
background: var(--surface); border-radius: 8px; margin-bottom: 6px; border: 1px solid var(--border);
}
.exercise-ref-item .name { font-weight: 500; }
.exercise-ref-item .count { font-size: 0.75rem; color: var(--text-secondary); margin-left: 6px; }
.exercise-ref-item .type-badge { font-size: 0.7rem; padding: 2px 6px; border-radius: 4px; background: var(--primary-variant); color: var(--primary); margin-left: 6px; }
/* === Body metrics === */
.metrics-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.metric-card { background: var(--surface); border: 1px solid var(--border); border-radius: 8px; padding: 12px; text-align: center; }
.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; }
+70
View File
@@ -0,0 +1,70 @@
/* === Workout accordion === */
.workout-accordion { margin-bottom: 10px; border-radius: var(--radius); overflow: hidden; border: 1px solid var(--border); }
.workout-header {
background-color: var(--surface); padding: 14px; display: flex;
justify-content: space-between; align-items: center; cursor: pointer;
}
.workout-header.active { border-left: 4px solid var(--primary); }
.workout-header.completed { opacity: 0.7; }
.workout-meta { font-size: 0.8rem; color: var(--text-secondary); margin-top: 4px; }
.workout-body { background-color: var(--bg); padding: 12px; display: none; }
.workout-body.expanded { display: block; }
.workout-badge { font-size: 0.7rem; padding: 3px 8px; border-radius: 4px; background: var(--surface-2); color: var(--text-secondary); }
.workout-badge.dirty { background: var(--warning); color: #000; }
.workout-badge.synced-badge { background: var(--success); color: #000; }
/* === Exercise accordion === */
.exercise-card { background-color: var(--surface); border-radius: var(--radius); margin-bottom: 10px; border: 1px solid var(--border); overflow: hidden; }
.exercise-header { padding: 12px 14px; display: flex; justify-content: space-between; align-items: center; cursor: pointer; user-select: none; }
.exercise-header.expanded { border-bottom: 1px solid var(--border); }
.exercise-name { font-weight: 600; color: var(--primary); font-size: 1rem; }
.exercise-summary { font-size: 0.8rem; color: var(--text-secondary); margin-left: 6px; }
.chevron { transition: transform 0.2s; color: var(--text-secondary); }
.chevron.open { transform: rotate(90deg); }
.exercise-body { padding: 12px 14px; display: none; }
.exercise-body.expanded { display: block; }
/* === Sets === */
.sets-table { margin-bottom: 12px; }
.set-row {
display: grid; grid-template-columns: 30px 1fr 1fr 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-rating { color: var(--warning); font-size: 0.85rem; }
.set-actions { display: flex; gap: 4px; }
/* === Dropset === */
.dropset-group {
background: rgba(251, 188, 4, 0.05); border-left: 3px solid var(--warning);
padding-left: 8px; margin: 4px 0; border-radius: 0 6px 6px 0;
}
/* === History hint === */
.history-hint {
background: rgba(187, 134, 252, 0.08); border: 1px dashed var(--primary);
border-radius: 8px; padding: 10px 12px; margin-bottom: 14px; font-size: 0.85rem;
color: var(--text-secondary); opacity: 0.85;
}
.history-hint-title { color: var(--primary); font-weight: 600; margin-bottom: 6px; font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.5px; }
.history-hint-row { display: flex; justify-content: space-between; padding: 3px 0; border-bottom: 1px dotted var(--border); }
.history-hint-row:last-child { border-bottom: none; }
.history-hint-date { color: var(--text-secondary); font-size: 0.75rem; }
.history-hint-sets { color: var(--text); font-weight: 500; }
/* === 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; }
/* === Add section === */
.add-section { display: flex; gap: 8px; margin-bottom: 10px; }
.add-section .btn { flex: 1; }
/* === Editable date === */
.editable-date { display: inline-flex; align-items: center; gap: 4px; cursor: pointer; padding: 2px 6px; border-radius: 4px; }
.editable-date:hover { background: var(--surface-2); }
.editable-date .edit-icon { font-size: 0.75rem; color: var(--text-secondary); opacity: 0; transition: opacity 0.15s; }
.editable-date:hover .edit-icon { opacity: 1; }
-30
View File
@@ -1,30 +0,0 @@
<!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 Tracker</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<div>
<h2 id="page-title">Gym Tracker</h2>
<div id="sync-status" class="sync-status">● Локально</div>
</div>
<div class="header-actions">
<button class="icon-btn header-btn" onclick="App.showBodyMetrics()" title="Замеры">📏</button>
<button class="icon-btn header-btn" onclick="App.showSettings()" title="Настройки">⚙️</button>
<button class="btn btn-small btn-secondary" onclick="App.sync()">🔄</button>
</div>
</header>
<main id="app" class="container"></main>
<div id="modal-container"></div>
<!-- ВАЖНО: modal.js загружается ПЕРВЫМ, так как app.js использует его при инициализации -->
<script src="modal.js"></script>
<script src="app.js"></script>
</body>
</html>
-742
View File
@@ -1,742 +0,0 @@
const Modal = {
show(html) {
const container = document.getElementById('modal-container');
container.innerHTML = `<div class="modal-overlay" onclick="Modal.closeOnBg(event)">${html}</div>`;
// Блокируем скролл страницы: клавиатура не должна «уводить» контент под модалкой
document.body.classList.add('modal-open');
const content = container.querySelector('.modal-content');
if (content) content.scrollTop = 0;
},
close() {
document.getElementById('modal-container').innerHTML = '';
document.body.classList.remove('modal-open');
},
closeOnBg(e) {
if (e.target.classList.contains('modal-overlay')) this.close();
},
esc(s) {
return String(s ?? '').replace(/[&<>"]/g, c =>
({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
},
// ============================================================
// Универсальный степпер
// ============================================================
stepperHtml(id, value, step, placeholder, inputmode = 'decimal', adaptive = false) {
const displayValue = value !== '' && value !== null && value !== undefined ? value : '';
const adaptiveArg = adaptive ? ', true' : '';
return `
<div class="stepper-field">
<button type="button" class="stepper-btn" onclick="Modal.stepValue('${id}', -1${adaptiveArg})">−</button>
<input type="number" id="${id}" step="${step}" value="${displayValue}"
placeholder="${placeholder}" inputmode="${inputmode}"
onfocus="Modal._focusInput(this)"
onchange="Modal._onStepperChange('${id}')">
<button type="button" class="stepper-btn" onclick="Modal.stepValue('${id}', 1${adaptiveArg})">+</button>
</div>
`;
},
stepValue(id, dir, adaptive = false) {
const input = document.getElementById(id);
if (!input) return;
const current = parseFloat(input.value) || 0;
// Адаптивный шаг веса: лёгкий вес — мелкий шаг, тяжёлый — крупный
const base = adaptive ? this.weightStep(current) : (parseFloat(input.step) || 1);
const newVal = Math.max(0, current + base * (dir < 0 ? -1 : 1));
// Округляем до шага, чтобы избежать 0.30000000004
const rounded = Math.round(newVal / base) * base;
input.value = parseFloat(rounded.toFixed(4));
this._onStepperChange(id);
},
// Шаг для веса в подходах: до 12 кг — 1, до 40 кг — 2.5, дальше — 5
weightStep(value) {
if (value < 12) return 1;
if (value < 40) return 2.5;
return 5;
},
// При фокусе: выделяем значение целиком (клавиатура сразу перезапишет)
// и подтягиваем поле к верху модалки, чтобы его не закрыла клавиатура
_focusInput(el) {
setTimeout(() => {
try { el.select(); } catch (e) { /* не все input это поддерживают */ }
const content = el.closest('.modal-content');
if (content) {
const r = el.getBoundingClientRect();
const c = content.getBoundingClientRect();
if (r.top > c.top + c.height * 0.45) {
content.scrollTop += (r.top - c.top) - c.height * 0.2;
}
}
}, 80);
},
_onStepperChange(id) {
// Хук для подклассов модалок — переопределяется при необходимости
if (this._stepperChangeHook) {
this._stepperChangeHook(id);
}
},
// ============================================================
// Dialog: Упражнение
// ============================================================
showExerciseDialog(workoutType, callback) {
const nameCount = {};
App.state.exerciseRef.forEach(ex => {
const isMatch = workoutType && ex.workoutType === workoutType;
const bonus = isMatch ? 100 : 10;
nameCount[ex.name] = (nameCount[ex.name] || 0) + bonus;
});
App.state.workouts.forEach(w => {
w.exercises.forEach(ex => {
nameCount[ex.name] = (nameCount[ex.name] || 0) + 1;
});
});
const sortedNames = Object.keys(nameCount).sort((a, b) => {
const diff = nameCount[b] - nameCount[a];
if (diff !== 0) return diff;
return a.localeCompare(b);
});
this.show(`
<div class="modal-content">
<h3 class="modal-title">Добавить упражнение</h3>
<div class="field-group">
<label>Название</label>
<input type="text" id="m-ex-name" placeholder="Начните вводить..."
oninput="Modal._filterExercises()" autocomplete="off">
<div id="m-ex-autocomplete" class="autocomplete-list"></div>
</div>
<div class="btn-row">
<button class="btn btn-secondary" onclick="Modal.close()">Отмена</button>
<button class="btn" onclick="Modal._submitExercise()">Добавить</button>
</div>
</div>
`);
this._exerciseCb = callback;
this._exerciseNames = sortedNames;
setTimeout(() => {
document.getElementById('m-ex-name').focus();
this._filterExercises();
}, 50);
},
_filterExercises() {
const input = document.getElementById('m-ex-name');
const list = document.getElementById('m-ex-autocomplete');
const query = input.value.trim().toLowerCase();
let filtered = this._exerciseNames;
if (query) {
filtered = filtered.filter(n => n.toLowerCase().includes(query));
}
if (filtered.length === 0) {
list.innerHTML = '<div class="autocomplete-item text-muted">Нет совпадений — можно ввести новое</div>';
return;
}
list.innerHTML = filtered.slice(0, 15).map(name => {
const count = App.state.workouts.reduce((sum, w) =>
sum + w.exercises.filter(e => e.name === name).length, 0
);
return `
<div class="autocomplete-item" onclick="Modal._selectExercise('${name.replace(/'/g, "\\'")}')">
${name}
${count > 0 ? `<span class="freq">${count}×</span>` : ''}
</div>
`;
}).join('');
},
_selectExercise(name) {
document.getElementById('m-ex-name').value = name;
document.getElementById('m-ex-autocomplete').innerHTML = '';
},
_submitExercise() {
const name = document.getElementById('m-ex-name').value.trim();
this.close();
this._exerciseCb(name);
},
// ============================================================
// Dialog: Подход
// ============================================================
showSetDialog(existingSet, history, callback, options = {}) {
const isEdit = !!existingSet;
// prefill — значения предыдущего подхода для нового (без режима «редактирование»)
const source = existingSet || options.prefill || null;
const isDropset = existingSet?.isDropset || false;
let historyHtml = '';
if (history && history.length > 0) {
const weekdays = ['вс', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб'];
const pad = n => String(n).padStart(2, '0');
const rows = history.map(h => {
const d = new Date(h.date);
const dateStr = `${pad(d.getDate())}.${pad(d.getMonth() + 1)}.${String(d.getFullYear()).slice(2)} ${weekdays[d.getDay()]}`;
// Если подход из упражнения-варианта (та же группа мышц, другое название) — подписываем
const isVariant = options.historyLabel && h.name &&
h.name.trim().toLowerCase() !== options.historyLabel.trim().toLowerCase();
const variantHtml = isVariant ? `<div class="history-hint-name">${this.esc(h.name)}</div>` : '';
const setsStr = h.sets.map((s, i) => {
let txt;
if (s.isDropset && s.subSets) {
txt = s.subSets.map(ss => `${ss.weight}×${ss.reps}`).join('→');
} else {
txt = `${s.weight}×${s.reps}`;
}
return `<span class="history-hint-set">${i + 1}&nbsp;${txt}</span>`;
}).join('');
return `<div class="history-hint-row">
<span class="history-hint-date">${dateStr}</span>
<span class="history-hint-sets">${variantHtml}${setsStr}</span>
</div>`;
}).join('');
historyHtml = `
<div class="history-hint">
<div class="history-hint-title">📊 Прошлые тренировки</div>
${rows}
</div>
`;
}
this.show(`
<div class="modal-content">
<h3 class="modal-title">${isEdit ? 'Редактировать' : 'Новый'} подход</h3>
${historyHtml}
<div class="field-group">
<label style="display:flex; align-items:center; gap:8px;">
<input type="checkbox" id="m-set-dropset" ${isDropset ? 'checked' : ''}
onchange="Modal._toggleDropsetMode()" style="width:auto;">
Это дроп-сет (несколько сбрасываний веса)
</label>
</div>
<div id="m-set-normal" class="${isDropset ? 'hidden' : ''}">
<div class="field-row">
<div class="field-group">
<label>Вес (кг)</label>
${this.stepperHtml('m-set-weight', source?.weight ?? '', 0.5, 'Вес', 'decimal', true)}
</div>
<div class="field-group">
<label>Повторения</label>
${this.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="Modal._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="Modal._selectRating(${r})">${r}</button>
`).join('')}
</div>
</div>
<div class="btn-row">
${isEdit ? `<button class="btn btn-danger" onclick="Modal._deleteSetRequested()">Удалить</button>` : ''}
<button class="btn btn-secondary" onclick="Modal.close()">Отмена</button>
<button class="btn btn-success" onclick="Modal._submitSet()">Сохранить</button>
</div>
</div>
`);
this._setData = {
isDropset: isDropset,
weight: source?.weight ?? '',
reps: source?.reps ?? '',
rating: existingSet?.rating ?? 5,
subSets: existingSet?.subSets ? JSON.parse(JSON.stringify(existingSet.subSets)) : [],
};
this._setCb = callback;
this._setDeleteCb = typeof options.onDelete === 'function' ? options.onDelete : null;
this._stepperChangeHook = null;
if (isDropset) {
if (this._setData.subSets.length === 0) {
this._addSubset();
} else {
this._renderSubsets();
}
}
this._selectRating(this._setData.rating);
},
_deleteSetRequested() {
this.close();
if (this._setDeleteCb) this._setDeleteCb();
},
_toggleDropsetMode() {
const isDropset = document.getElementById('m-set-dropset').checked;
this._setData.isDropset = isDropset;
document.getElementById('m-set-normal').classList.toggle('hidden', isDropset);
document.getElementById('m-set-dropset-block').classList.toggle('hidden', !isDropset);
if (isDropset && this._setData.subSets.length === 0) {
this._addSubset();
} else if (isDropset) {
this._renderSubsets();
}
},
_addSubset() {
const last = this._setData.subSets[this._setData.subSets.length - 1];
this._setData.subSets.push({
weight: last ? last.weight : '',
reps: last ? last.reps : '',
});
this._renderSubsets();
},
_renderSubsets() {
const list = document.getElementById('m-subsets-list');
list.innerHTML = this._setData.subSets.map((s, i) => `
<div class="stepper-row">
${this.stepperHtml(`m-sub-w-${i}`, s.weight, 0.5, 'Вес', 'decimal', true)}
${this.stepperHtml(`m-sub-r-${i}`, s.reps, 1, 'Повт.', 'numeric')}
<button class="icon-btn danger" onclick="Modal._removeSubset(${i})">✕</button>
</div>
`).join('');
// Включаем хук для синхронизации с _setData
this._stepperChangeHook = (id) => {
const wMatch = id.match(/^m-sub-w-(\d+)$/);
const rMatch = id.match(/^m-sub-r-(\d+)$/);
if (wMatch) {
const i = parseInt(wMatch[1]);
this._setData.subSets[i].weight = document.getElementById(id).value;
} else if (rMatch) {
const i = parseInt(rMatch[1]);
this._setData.subSets[i].reps = document.getElementById(id).value;
}
};
},
_removeSubset(i) {
this._setData.subSets.splice(i, 1);
this._renderSubsets();
},
_selectRating(r) {
this._setData.rating = r;
document.querySelectorAll('#m-rating-grid .rating-btn').forEach(btn => {
btn.classList.toggle('active', parseInt(btn.dataset.rating) === r);
});
},
_submitSet() {
if (this._setData.isDropset) {
// Синхронизируем значения из input в _setData перед сабмитом
this._setData.subSets.forEach((s, i) => {
const wInput = document.getElementById(`m-sub-w-${i}`);
const rInput = document.getElementById(`m-sub-r-${i}`);
if (wInput) s.weight = wInput.value;
if (rInput) s.reps = rInput.value;
});
if (this._setData.subSets.length === 0) {
alert('Добавьте хотя бы одно сбрасывание');
return;
}
const result = {
isDropset: true,
subSets: this._setData.subSets.map(s => ({
weight: parseFloat(s.weight) || 0,
reps: parseInt(s.reps) || 0,
})),
rating: this._setData.rating,
};
this.close();
this._setCb(result);
} else {
const weight = parseFloat(document.getElementById('m-set-weight').value);
const reps = parseInt(document.getElementById('m-set-reps').value);
if (!weight && !reps) {
alert('Укажите вес и повторения');
return;
}
const result = {
isDropset: false,
weight: weight || 0,
reps: reps || 0,
rating: this._setData.rating,
};
this.close();
this._setCb(result);
}
},
// ============================================================
// Dialog: Кардио (со степперами)
// ============================================================
showCardioDialog(existing, callback) {
const isEdit = !!existing;
// Популярные типы кардио — выше в списке
const cardioCounts = {};
App.state.workouts.forEach(w => (w.cardio || []).forEach(c => {
if (c.type) cardioCounts[c.type] = (cardioCounts[c.type] || 0) + 1;
}));
const cardioTypes = [
['вело', '🚴 Вело'],
['ходьба', '🚶 Ходьба'],
['бег', '🏃 Бег'],
['эллипс', '⚡ Эллипс'],
['гребля', '🚣 Гребля'],
];
cardioTypes.sort((a, b) => (cardioCounts[b[0]] || 0) - (cardioCounts[a[0]] || 0));
const typeOptions = cardioTypes.map(([v, label]) =>
`<option value="${v}" ${existing?.type === v ? 'selected' : ''}>${label}</option>`).join('');
this.show(`
<div class="modal-content">
<h3 class="modal-title">${isEdit ? 'Редактировать' : 'Новое'} кардио</h3>
<div class="field-row">
<div class="field-group">
<label>Тип</label>
<select id="m-cardio-type">${typeOptions}</select>
</div>
<div class="field-group">
<label>Назначение</label>
<select id="m-cardio-purpose">
<option value="warmup" ${existing?.purpose==='warmup'?'selected':''}>🔥 Разминка</option>
<option value="cooldown" ${existing?.purpose==='cooldown'?'selected':''}>🧘 Заминка</option>
<option value="separate" ${existing?.purpose==='separate'?'selected':''}>➕ Отдельная</option>
</select>
</div>
</div>
<div class="field-row-3">
<div class="field-group">
<label>Минут</label>
${this.stepperHtml('m-cardio-duration', existing?.duration ?? '', 1, 'мин', 'numeric')}
</div>
<div class="field-group">
<label>Дистанция</label>
${this.stepperHtml('m-cardio-distance', existing?.distance ?? '', 0.1, 'км', 'decimal')}
</div>
<div class="field-group">
<label>Скорость</label>
${this.stepperHtml('m-cardio-speed', existing?.speed ?? '', 0.5, 'км/ч', 'decimal')}
</div>
</div>
<div class="field-row">
<div class="field-group">
<label>Наклон</label>
${this.stepperHtml('m-cardio-incline', existing?.incline ?? '', 0.5, '—', 'decimal')}
</div>
<div class="field-group">
<label>Сопротивление</label>
${this.stepperHtml('m-cardio-resistance', existing?.resistance ?? '', 1, '—', 'numeric')}
</div>
</div>
<div class="field-group">
<label>Заметка</label>
<input type="text" id="m-cardio-notes" value="${existing?.notes || ''}"
placeholder="Например: тяжёло после 20 минуты">
</div>
<div class="btn-row">
<button class="btn btn-secondary" onclick="Modal.close()">Отмена</button>
<button class="btn btn-success" onclick="Modal._submitCardio()">Сохранить</button>
</div>
</div>
`);
this._cardioCb = callback;
},
_submitCardio() {
const result = {
type: document.getElementById('m-cardio-type').value,
purpose: document.getElementById('m-cardio-purpose').value,
duration: parseInt(document.getElementById('m-cardio-duration').value) || 0,
distance: parseFloat(document.getElementById('m-cardio-distance').value) || 0,
speed: parseFloat(document.getElementById('m-cardio-speed').value) || 0,
incline: parseFloat(document.getElementById('m-cardio-incline').value) || 0,
resistance: parseInt(document.getElementById('m-cardio-resistance').value) || 0,
notes: document.getElementById('m-cardio-notes').value.trim(),
};
this.close();
this._cardioCb(result);
},
// ============================================================
// Dialog: Замеры тела (со степперами + дата)
// ============================================================
showBodyMetricsDialog(existingMetrics, callback, editingMetric = null) {
const source = editingMetric || existingMetrics[0];
const isEdit = !!editingMetric;
// Форматируем дату для datetime-local
let dateValue = '';
if (source?.date) {
const d = new Date(source.date);
// Формат YYYY-MM-DDTHH:MM
const pad = n => String(n).padStart(2, '0');
dateValue = `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
} else if (!isEdit) {
// По умолчанию — сейчас
const d = new Date();
const pad = n => String(n).padStart(2, '0');
dateValue = `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
this.show(`
<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 class="field-row">
<div class="field-group">
<label>⚖️ Вес (кг)</label>
${this.stepperHtml('m-metric-weight', source?.weight ?? '', 0.1, 'кг', 'decimal')}
</div>
<div class="field-group">
<label>📏 Грудь (см)</label>
${this.stepperHtml('m-metric-chest', source?.chest ?? '', 1, 'см', 'numeric')}
</div>
</div>
<div class="field-row">
<div class="field-group">
<label>📏 Талия (см)</label>
${this.stepperHtml('m-metric-waist', source?.waist ?? '', 1, 'см', 'numeric')}
</div>
<div class="field-group">
<label>📏 Бёдра (см)</label>
${this.stepperHtml('m-metric-hips', source?.hips ?? '', 1, 'см', 'numeric')}
</div>
</div>
<div class="field-row">
<div class="field-group">
<label>💪 Руки (см)</label>
${this.stepperHtml('m-metric-arms', source?.arms ?? '', 0.5, 'см', 'decimal')}
</div>
<div class="field-group">
<label>🦵 Ноги (см)</label>
${this.stepperHtml('m-metric-legs', source?.legs ?? '', 0.5, 'см', 'decimal')}
</div>
</div>
<div class="btn-row">
<button class="btn btn-secondary" onclick="Modal.close()">Отмена</button>
<button class="btn btn-success" onclick="Modal._submitMetrics(${isEdit})">Сохранить</button>
</div>
</div>
`);
this._metricsCb = callback;
},
_submitMetrics(isEdit) {
const dateStr = document.getElementById('m-metric-date').value;
const result = {
date: dateStr ? new Date(dateStr).toISOString() : new Date().toISOString(),
weight: parseFloat(document.getElementById('m-metric-weight').value) || null,
chest: parseInt(document.getElementById('m-metric-chest').value) || null,
waist: parseInt(document.getElementById('m-metric-waist').value) || null,
hips: parseInt(document.getElementById('m-metric-hips').value) || null,
arms: parseFloat(document.getElementById('m-metric-arms').value) || null,
legs: parseFloat(document.getElementById('m-metric-legs').value) || null,
};
if (!Object.values(result).some((v, i) => i > 0 && v !== null)) {
alert('Заполните хотя бы одно поле');
return;
}
this.close();
this._metricsCb(result, isEdit);
},
// ============================================================
// Dialog: Сет (суперсет) — упражнения, выполняемые по очереди
// ============================================================
showGroupDialog(workout, group, callback) {
const isEdit = !!group;
const otherGrouped = new Set();
(workout.setGroups || []).forEach(g => {
if (!isEdit || g.id !== group.id) g.exerciseIds.forEach(id => otherGrouped.add(id));
});
this.show(`
<div class="modal-content">
<h3 class="modal-title">${isEdit ? 'Редактировать' : 'Новый'} сет</h3>
<p class="text-muted text-small">
Отметьте упражнения, подходы которых выполняются по очереди:
1-й подход каждого → отдых → 2-й подход каждого → …
</p>
<div class="field-group">
<label>Название</label>
<input type="text" id="m-group-name" placeholder="Например: косичка + разгибание">
</div>
<div class="field-group" id="m-group-list"></div>
<div class="btn-row">
<button class="btn btn-secondary" onclick="Modal.close()">Отмена</button>
<button class="btn btn-success" onclick="Modal._submitGroup()">Сохранить</button>
</div>
</div>
`);
this._groupCb = callback;
if (isEdit) document.getElementById('m-group-name').value = group.name;
const list = document.getElementById('m-group-list');
workout.exercises.forEach(ex => {
const inOther = otherGrouped.has(ex.id);
const label = document.createElement('label');
label.className = 'group-ex-toggle' + (inOther ? ' disabled' : '');
const cb = document.createElement('input');
cb.type = 'checkbox';
cb.dataset.exId = ex.id;
cb.checked = isEdit && group.exerciseIds.includes(ex.id);
cb.disabled = inOther;
label.appendChild(cb);
label.appendChild(document.createTextNode(
' ' + ex.name + ` (${ex.sets.length} подх.)` + (inOther ? ' — уже в сете' : '')
));
list.appendChild(label);
});
},
_submitGroup() {
const name = document.getElementById('m-group-name').value.trim() || 'Суперсет';
const ids = [...document.querySelectorAll('#m-group-list input[type=checkbox]:checked')]
.map(cb => cb.dataset.exId);
if (ids.length < 2) {
alert('Отметьте минимум 2 упражнения');
return;
}
this.close();
this._groupCb({ name, exerciseIds: ids });
},
// ============================================================
// Dialog: Редактирование упражнения из справочника
// ============================================================
showEditExerciseDialog(exercise, callback) {
const groups = [...new Set(App.state.exerciseRef.map(e => e.group).filter(Boolean))].sort();
this.show(`
<div class="modal-content">
<h3 class="modal-title">Редактировать упражнение</h3>
<div class="field-group">
<label>Название</label>
<input type="text" id="m-edit-ex-name" value="${this.esc(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>
</select>
</div>
<div class="field-group">
<label>Группа вариантов (общая статистика)</label>
<input type="text" id="m-edit-ex-group" list="m-edit-groups-list"
value="${this.esc(exercise.group || '')}"
placeholder="Например: жим гантелей на лавке">
<datalist id="m-edit-groups-list">${
groups.map(g => `<option value="${this.esc(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="Modal.close()">Отмена</button>
<button class="btn btn-success" onclick="Modal._submitEditExercise()">Сохранить</button>
</div>
</div>
`);
this._editExerciseCb = callback;
},
_submitEditExercise() {
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;
}
this.close();
this._editExerciseCb({ name, workoutType: type, group });
},
// ============================================================
// Dialog: Редактирование даты тренировки
// ============================================================
showEditWorkoutDateDialog(workout, callback) {
const start = new Date(workout.startTime);
const pad = n => String(n).padStart(2, '0');
const startValue = `${start.getFullYear()}-${pad(start.getMonth()+1)}-${pad(start.getDate())}T${pad(start.getHours())}:${pad(start.getMinutes())}`;
let endValue = '';
if (workout.endTime) {
const end = new Date(workout.endTime);
endValue = `${end.getFullYear()}-${pad(end.getMonth()+1)}-${pad(end.getDate())}T${pad(end.getHours())}:${pad(end.getMinutes())}`;
}
this.show(`
<div class="modal-content">
<h3 class="modal-title">📅 Дата тренировки</h3>
<div class="field-group">
<label>Начало</label>
<input type="datetime-local" id="m-w-start" value="${startValue}">
</div>
<div class="field-group">
<label>Окончание</label>
<input type="datetime-local" id="m-w-end" value="${endValue}">
</div>
<div class="btn-row">
<button class="btn btn-secondary" onclick="Modal.close()">Отмена</button>
<button class="btn btn-success" onclick="Modal._submitWorkoutDate()">Сохранить</button>
</div>
</div>
`);
this._workoutDateCb = callback;
},
_submitWorkoutDate() {
const startStr = document.getElementById('m-w-start').value;
const endStr = document.getElementById('m-w-end').value;
if (!startStr) {
alert('Укажите дату начала');
return;
}
this.close();
this._workoutDateCb({
startTime: new Date(startStr).toISOString(),
endTime: endStr ? new Date(endStr).toISOString() : null,
});
},
};
+98
View File
@@ -0,0 +1,98 @@
# Gym Bro 😈
![License](https://img.shields.io/badge/license-MIT-blue.svg)
![Python](https://img.shields.io/badge/python-3.11+-blue.svg)
![FastAPI](https://img.shields.io/badge/FastAPI-0.104-green.svg)
![Vue/JS](https://img.shields.io/badge/frontend-Vanilla_JS-yellow.svg)
![Docker](https://img.shields.io/badge/docker-ready-2496ED.svg)
**Gym Bro** — это легковесный, self-hosted трекер тренировок с поддержкой офлайн-режима, синхронизации и режима тренера. Без лишнего веса, только мышцы. 💪
## Особенности
* **Offline First:** Работает без интернета. Данные сохраняются локально (`localStorage`) и синхронизируются при появлении связи.
* **Multi-user Support:** Разделение данных между пользователями (JWT Auth). Каждый видит только свои тренировки.
* **Trainer Mode:** Режим для тренеров. Ведите несколько клиентов одновременно, присваивайте им уникальные цвета для визуального разделения.
* **Dropsets & History:** Поддержка дроп-сетов и мгновенная подсказка истории упражнений прямо во время подхода.
* **Body Metrics:** Гибкая система замеров тела (вес, объёмы, % жира) с историей изменений.
* **No Build Step for Frontend:** Чистый HTML/CSS/JS. Не нужен Webpack/Vite. Просто открой файл или залей на любой static host.
* **Single Binary Deployment:** Весь стек упакован в Docker Compose. Один командой поднимается БД, API и Веб-сервер.
## 🛠 Технологии
* **Backend:** Python 3.11, FastAPI, SQLAlchemy, SQLite, PyJWT, Bcrypt.
* **Frontend:** Vanilla JavaScript (ES Modules), CSS Variables, No Frameworks.
* **Infrastructure:** Docker, Nginx (as reverse proxy & static server).
## 🚀 Быстрый старт (Docker)
### Требования
* Docker Engine
* Docker Compose Plugin
### Установка
1. Клонируйте репозиторий:
```bash
git clone https://github.com/your-username/gym-bro.git
cd gym-bro
```
2. Настройте секреты (опционально, для продакшена обязательно):
``` bash
cp .env.example .env
# Отредактируйте .env, замените JWT_SECRET на длинную случайную строку
```
3. Соберите и запустите:
```bash
docker compose up -d --build
```
4. Откройте браузер:
```text
http://localhost
```
5. Зарегистрируйтесь и начинайте качаться!
### 📂 Структура проекта
``` text
gym-bro/
├── backend/ # FastAPI приложение
│ ├── routers/ # API эндпоинты
│ ├── models.py # SQLAlchemy модели
│ ├── schemas.py # Pydantic схемы
│ ├── auth.py # Логика JWT/Bcrypt
│ └── Dockerfile
├── frontend/ # Статические файлы
│ ├── js/ # ES модули логики
│ ├── styles/ # CSS
│ ├── index.html # Точка входа
│ ├── nginx.conf # Конфиг прокси
│ └── Dockerfile
├── data/ # Volume для SQLite (не коммитится!)
├── docker-compose.yml
└── README.md
```
### 🔐 Безопасность
- Пароли хэшируются с помощью bcrypt.
- Сессии управляются через JWT токены (HttpOnly cookie опция планируется).
- Все данные изолированы по owner_id на уровне БД.
- Внимание: Для продакшена обязательно измените JWT_SECRET в .env файле.
### 🤝 Вклад
Pull requests приветствуются!
1. Форкните проект.
2. Создайте ветку feature/amazing-feature.
3. Коммитьте изменения.
4. Пушьте в GitHub.
5. Открывайте Pull Request.
### 📄 Лицензия
MIT License.
----
Made with ❤️ and heavy weights by ivan-igorevich
+224
View File
@@ -0,0 +1,224 @@
-- ============================================================
-- Gym Tracker — SQLite schema v2
-- Гибкие справочники + мультиклиентская схема
-- ============================================================
PRAGMA foreign_keys = ON;
PRAGMA journal_mode = WAL;
-- ============================================================
-- 1. КЛИЕНТЫ (люди, чьи тренировки ведём)
-- ============================================================
CREATE TABLE clients (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sync_id TEXT NOT NULL UNIQUE, -- UUID для синхронизации
full_name TEXT NOT NULL,
birth_date TEXT, -- ISO8601 (YYYY-MM-DD)
goal TEXT DEFAULT '', -- цель тренировок
notes TEXT DEFAULT '',
is_active INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
);
CREATE INDEX idx_clients_name ON clients(full_name);
CREATE INDEX idx_clients_active ON clients(is_active);
-- ============================================================
-- 2. СПРАВОЧНИК ТИПОВ ТРЕНИРОВОК
-- ============================================================
CREATE TABLE workout_types (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sync_id TEXT NOT NULL UNIQUE,
name TEXT NOT NULL UNIQUE,
sort_order INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
);
-- ============================================================
-- 3. СПРАВОЧНИК УПРАЖНЕНИЙ
-- ============================================================
CREATE TABLE exercises (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sync_id TEXT NOT NULL UNIQUE,
workout_type_id INTEGER, -- FK на workout_types
name TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
FOREIGN KEY (workout_type_id) REFERENCES workout_types(id) ON DELETE SET NULL
);
CREATE INDEX idx_exercises_name ON exercises(name);
CREATE INDEX idx_exercises_type ON exercises(workout_type_id);
-- ============================================================
-- 4. ТРЕНИРОВКИ
-- ============================================================
CREATE TABLE workouts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sync_id TEXT NOT NULL UNIQUE,
client_id INTEGER, -- FK на clients
workout_type_id INTEGER, -- FK на workout_types
start_time TEXT NOT NULL, -- ISO8601
end_time TEXT, -- NULL = активная
notes TEXT DEFAULT '',
synced INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
FOREIGN KEY (client_id) REFERENCES clients(id) ON DELETE SET NULL,
FOREIGN KEY (workout_type_id) REFERENCES workout_types(id) ON DELETE SET NULL
);
CREATE INDEX idx_workouts_client ON workouts(client_id);
CREATE INDEX idx_workouts_start ON workouts(start_time);
CREATE INDEX idx_workouts_synced ON workouts(synced);
-- ============================================================
-- 5. УПРАЖНЕНИЯ ВНУТРИ ТРЕНИРОВКИ
-- ============================================================
CREATE TABLE workout_exercises (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sync_id TEXT NOT NULL UNIQUE,
workout_id INTEGER NOT NULL,
exercise_id INTEGER, -- FK на exercises (может быть NULL)
exercise_name TEXT NOT NULL, -- дублируем для истории
sort_order INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
FOREIGN KEY (workout_id) REFERENCES workouts(id) ON DELETE CASCADE,
FOREIGN KEY (exercise_id) REFERENCES exercises(id) ON DELETE SET NULL
);
CREATE INDEX idx_wex_workout ON workout_exercises(workout_id);
CREATE INDEX idx_wex_exercise ON workout_exercises(exercise_id);
CREATE INDEX idx_wex_name ON workout_exercises(exercise_name);
-- ============================================================
-- 6. ПОДХОДЫ
-- ============================================================
CREATE TABLE sets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sync_id TEXT NOT NULL UNIQUE,
workout_exercise_id INTEGER NOT NULL,
is_dropset INTEGER NOT NULL DEFAULT 0,
weight REAL,
reps INTEGER,
rating INTEGER CHECK (rating BETWEEN 1 AND 5),
notes TEXT DEFAULT '',
sort_order INTEGER NOT NULL DEFAULT 0,
timestamp TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
FOREIGN KEY (workout_exercise_id) REFERENCES workout_exercises(id) ON DELETE CASCADE,
CHECK (
(is_dropset = 0 AND weight IS NOT NULL AND reps IS NOT NULL) OR
(is_dropset = 1 AND weight IS NULL AND reps IS NULL)
)
);
CREATE INDEX idx_sets_wex ON sets(workout_exercise_id);
CREATE INDEX idx_sets_timestamp ON sets(timestamp);
-- ============================================================
-- 7. ЭЛЕМЕНТЫ ДРОП-СЕТА
-- ============================================================
CREATE TABLE dropset_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
set_id INTEGER NOT NULL,
weight REAL NOT NULL,
reps INTEGER NOT NULL,
sort_order INTEGER NOT NULL DEFAULT 0,
FOREIGN KEY (set_id) REFERENCES sets(id) ON DELETE CASCADE,
CHECK (weight > 0 AND reps > 0)
);
CREATE INDEX idx_dropset_set ON dropset_items(set_id);
-- ============================================================
-- 8. КАРДИО
-- ============================================================
CREATE TABLE cardio (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sync_id TEXT NOT NULL UNIQUE,
workout_id INTEGER NOT NULL,
cardio_type TEXT NOT NULL CHECK (cardio_type IN (
'вело', 'ходьба', 'бег', 'эллипс', 'гребля'
)),
purpose TEXT NOT NULL CHECK (purpose IN (
'warmup', 'cooldown', 'separate'
)),
duration INTEGER,
distance REAL,
speed REAL,
incline REAL,
resistance INTEGER,
notes TEXT DEFAULT '',
sort_order INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
FOREIGN KEY (workout_id) REFERENCES workouts(id) ON DELETE CASCADE
);
CREATE INDEX idx_cardio_workout ON cardio(workout_id);
CREATE INDEX idx_cardio_purpose ON cardio(purpose);
-- ============================================================
-- 9. СПРАВОЧНИК ТИПОВ ЗАМЕРОВ ТЕЛА
-- ============================================================
CREATE TABLE metric_types (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sync_id TEXT NOT NULL UNIQUE,
name TEXT NOT NULL UNIQUE, -- "Вес", "Грудь", "Бицепс", "Предплечье"...
unit TEXT NOT NULL DEFAULT 'см', -- единица измерения
category TEXT DEFAULT 'body', -- для группировки: body, strength, etc.
sort_order INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
);
-- ============================================================
-- 10. ЗАМЕРЫ ТЕЛА (факт замера)
-- ============================================================
CREATE TABLE body_metrics (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sync_id TEXT NOT NULL UNIQUE,
client_id INTEGER, -- FK на clients
metric_date TEXT NOT NULL, -- ISO8601
notes TEXT DEFAULT '',
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
FOREIGN KEY (client_id) REFERENCES clients(id) ON DELETE SET NULL
);
CREATE INDEX idx_body_metrics_client ON body_metrics(client_id);
CREATE INDEX idx_body_metrics_date ON body_metrics(metric_date);
-- ============================================================
-- 11. ЗНАЧЕНИЯ ЗАМЕРОВ (нормализованно)
-- ============================================================
CREATE TABLE body_metric_values (
id INTEGER PRIMARY KEY AUTOINCREMENT,
body_metric_id INTEGER NOT NULL,
metric_type_id INTEGER NOT NULL,
value REAL NOT NULL,
FOREIGN KEY (body_metric_id) REFERENCES body_metrics(id) ON DELETE CASCADE,
FOREIGN KEY (metric_type_id) REFERENCES metric_types(id) ON DELETE CASCADE,
UNIQUE (body_metric_id, metric_type_id) -- один тип замера — одно значение в замере
);
CREATE INDEX idx_bmv_metric ON body_metric_values(body_metric_id);
CREATE INDEX idx_bmv_type ON body_metric_values(metric_type_id);
-- ============================================================
-- 12. ЛОГ СИНХРОНИЗАЦИИ
-- ============================================================
CREATE TABLE sync_log (
device_id TEXT PRIMARY KEY,
last_sync TEXT NOT NULL,
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
);
+89
View File
@@ -0,0 +1,89 @@
-- ============================================================
-- Тестовые данные v2
-- ============================================================
-- Клиенты
INSERT INTO clients (sync_id, full_name, birth_date, goal) VALUES
('cl-001', 'Иванов Иван Иванович', '1990-05-15', 'Набор мышечной массы'),
('cl-002', 'Петрова Анна Сергеевна', '1995-11-22', 'Снижение веса, тонус');
-- Типы тренировок
INSERT INTO workout_types (sync_id, name, sort_order) VALUES
('wt-001', 'грудь-руки', 1),
('wt-002', 'ноги', 2),
('wt-003', 'спина-плечи', 3),
('wt-004', 'круговая', 4),
('wt-005', 'силовая', 5),
('wt-006', 'многоповторная', 6);
-- Типы замеров
INSERT INTO metric_types (sync_id, name, unit, category, sort_order) VALUES
('mt-001', 'Вес', 'кг', 'body', 1),
('mt-002', 'Грудь', 'см', 'body', 2),
('mt-003', 'Талия', 'см', 'body', 3),
('mt-004', 'Бёдра', 'см', 'body', 4),
('mt-005', 'Бицепс', 'см', 'body', 5),
('mt-006', 'Предплечье', 'см', 'body', 6),
('mt-007', 'Бедро', 'см', 'body', 7),
('mt-008', 'Голень', 'см', 'body', 8),
('mt-009', 'Шея', 'см', 'body', 9);
-- Упражнения (с привязкой к типам тренировок)
INSERT INTO exercises (sync_id, workout_type_id, name) VALUES
('ex-001', 1, 'Жим лёжа'), -- грудь-руки
('ex-002', 3, 'Горизонтальная тяга'), -- спина-плечи
('ex-003', 2, 'Приседания'), -- ноги
('ex-004', 3, 'Становая тяга'); -- спина-плечи
-- Тренировка клиента Иванова
INSERT INTO workouts (sync_id, client_id, workout_type_id, start_time, end_time, notes, synced) VALUES
('w-001', 1, 3, '2026-09-24T18:00:00Z', '2026-09-24T19:30:00Z', 'Хорошая тренировка', 1);
-- Упражнения в тренировке
INSERT INTO workout_exercises (sync_id, workout_id, exercise_id, exercise_name, sort_order) VALUES
('we-001', 1, 2, 'Горизонтальная тяга', 1),
('we-002', 1, NULL, 'Тяга верхнего блока', 2);
-- Обычные подходы
INSERT INTO sets (sync_id, workout_exercise_id, is_dropset, weight, reps, rating, sort_order, timestamp) VALUES
('s-001', 1, 0, 15.0, 12, 3, 1, '2026-09-24T18:10:00Z'),
('s-002', 1, 0, 20.0, 12, 4, 2, '2026-09-24T18:15:00Z');
-- Дроп-сет
INSERT INTO sets (sync_id, workout_exercise_id, is_dropset, weight, reps, rating, sort_order, timestamp) VALUES
('s-003', 1, 1, NULL, NULL, 5, 3, '2026-09-24T18:20:00Z');
INSERT INTO dropset_items (set_id, weight, reps, sort_order) VALUES
(3, 25.0, 8, 1),
(3, 20.0, 10, 2),
(3, 15.0, 12, 3);
-- Кардио
INSERT INTO cardio (sync_id, workout_id, cardio_type, purpose, duration, speed, sort_order) VALUES
('c-001', 1, 'вело', 'warmup', 10, 20.0, 1),
('c-002', 1, 'ходьба', 'cooldown', 15, 6.0, 2);
-- Замеры тела клиента Иванова (с разными типами)
INSERT INTO body_metrics (sync_id, client_id, metric_date) VALUES
('bm-001', 1, '2026-09-24T08:00:00Z');
INSERT INTO body_metric_values (body_metric_id, metric_type_id, value) VALUES
(1, 1, 78.5), -- Вес
(1, 2, 102), -- Грудь
(1, 3, 84), -- Талия
(1, 5, 36), -- Бицепс
(1, 6, 29); -- Предплечье
-- Второй замер через неделю (добавили новые типы)
INSERT INTO body_metrics (sync_id, client_id, metric_date) VALUES
('bm-002', 1, '2026-10-01T08:00:00Z');
INSERT INTO body_metric_values (body_metric_id, metric_type_id, value) VALUES
(2, 1, 79.0), -- Вес
(2, 2, 103), -- Грудь
(2, 3, 83), -- Талия
(2, 5, 36.5), -- Бицепс
(2, 6, 29.5), -- Предплечье
(2, 7, 58), -- Бедро (новый тип!)
(2, 8, 38); -- Голень (новый тип!)
+123
View File
@@ -0,0 +1,123 @@
-- ============================================================
-- Проверочные запросы v2
-- ============================================================
-- 1. Все тренировки клиента с типом тренировки
SELECT
c.full_name,
w.start_time,
wt.name AS workout_type,
w.notes,
CASE WHEN w.end_time IS NULL THEN '🔥 Активная' ELSE '✅ Завершена' END AS status
FROM workouts w
JOIN clients c ON c.id = w.client_id
LEFT JOIN workout_types wt ON wt.id = w.workout_type_id
ORDER BY w.start_time DESC;
-- 2. Полная тренировка с дроп-сетами
SELECT
w.start_time,
wt.name AS workout_type,
we.exercise_name,
CASE
WHEN s.is_dropset = 0 THEN printf('%s кг × %s', s.weight, s.reps)
ELSE '🔥 DROPSET'
END AS set_info,
s.rating
FROM workouts w
LEFT JOIN workout_types wt ON wt.id = w.workout_type_id
JOIN workout_exercises we ON we.workout_id = w.id
JOIN sets s ON s.workout_exercise_id = we.id
WHERE w.id = 1
ORDER BY we.sort_order, s.sort_order;
-- 3. Элементы дроп-сета
SELECT
s.id AS set_id,
di.sort_order,
di.weight,
di.reps
FROM sets s
JOIN dropset_items di ON di.set_id = s.id
WHERE s.is_dropset = 1
ORDER BY s.id, di.sort_order;
-- 4. История упражнения (для подсказок)
SELECT
w.start_time,
s.weight,
s.reps,
s.is_dropset
FROM workout_exercises we
JOIN sets s ON s.workout_exercise_id = we.id
JOIN workouts w ON w.id = we.workout_id
WHERE we.exercise_name = 'Горизонтальная тяга'
AND w.end_time IS NOT NULL
ORDER BY w.start_time DESC
LIMIT 10;
-- 5. Динамика замеров клиента (для дашборда)
SELECT
bm.metric_date,
mt.name AS metric_name,
mt.unit,
bmv.value
FROM body_metrics bm
JOIN body_metric_values bmv ON bmv.body_metric_id = bm.id
JOIN metric_types mt ON mt.id = bmv.metric_type_id
WHERE bm.client_id = 1
ORDER BY bm.metric_date DESC, mt.sort_order;
-- 6. Динамика конкретного замера (например, бицепс)
SELECT
date(bm.metric_date) AS day,
bmv.value
FROM body_metrics bm
JOIN body_metric_values bmv ON bmv.body_metric_id = bm.id
JOIN metric_types mt ON mt.id = bmv.metric_type_id
WHERE bm.client_id = 1
AND mt.name = 'Бицепс'
ORDER BY bm.metric_date DESC;
-- 7. Статистика по клиентам (для тренера)
SELECT
c.full_name,
c.goal,
COUNT(DISTINCT w.id) AS total_workouts,
SUM(CASE WHEN w.end_time IS NOT NULL THEN 1 ELSE 0 END) AS completed,
MAX(w.start_time) AS last_workout
FROM clients c
LEFT JOIN workouts w ON w.client_id = c.id
GROUP BY c.id
ORDER BY last_workout DESC;
-- 8. Тренировки клиента за последнюю неделю
SELECT
w.start_time,
wt.name AS workout_type,
COUNT(DISTINCT we.id) AS exercises_count,
SUM(CASE WHEN s.is_dropset = 0 THEN 1 ELSE (SELECT COUNT(*) FROM dropset_items WHERE set_id = s.id) END) AS total_sets
FROM workouts w
LEFT JOIN workout_types wt ON wt.id = w.workout_type_id
LEFT JOIN workout_exercises we ON we.workout_id = w.id
LEFT JOIN sets s ON s.workout_exercise_id = we.id
WHERE w.client_id = 1
AND w.start_time >= date('now', '-7 days')
GROUP BY w.id
ORDER BY w.start_time DESC;
-- 9. Все упражнения с их типами тренировок
SELECT
e.name,
wt.name AS workout_type
FROM exercises e
LEFT JOIN workout_types wt ON wt.id = e.workout_type_id
ORDER BY wt.sort_order, e.name;
-- 10. Все доступные типы замеров
SELECT
name,
unit,
category
FROM metric_types
ORDER BY sort_order;
-623
View File
@@ -1,623 +0,0 @@
:root {
--bg: #121212;
--surface: #1e1e1e;
--surface-2: #2c2c2c;
--primary: #bb86fc;
--primary-variant: #3700b3;
--text: #ffffff;
--text-secondary: #b0b0b0;
--success: #03dac6;
--danger: #cf6679;
--warning: #fbbc04;
--border: #333333;
--radius: 10px;
}
* {
box-sizing: border-box;
touch-action: manipulation;
-webkit-tap-highlight-color: transparent;
}
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
background-color: var(--bg);
color: var(--text);
padding-bottom: 40px;
}
header {
background-color: var(--surface);
padding: 14px 16px;
position: sticky;
top: 0;
z-index: 50;
border-bottom: 1px solid var(--border);
display: flex;
justify-content: space-between;
align-items: center;
}
h1, h2, h3, h4 { margin: 0; }
h2 { font-size: 1.15rem; }
h3 { font-size: 1.05rem; }
.container { padding: 12px; }
.header-actions { display: flex; gap: 8px; align-items: center; }
.header-btn { font-size: 1.3rem; padding: 8px 10px; }
/* === Buttons === */
.btn {
background-color: var(--primary);
color: #000;
border: none;
border-radius: var(--radius);
padding: 14px 20px;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
width: 100%;
text-align: center;
transition: opacity 0.15s;
}
.btn:active { opacity: 0.7; }
.btn:disabled { opacity: 0.4; cursor: not-allowed; }
.btn-secondary {
background-color: var(--surface-2);
color: var(--text);
border: 1px solid var(--border);
}
.btn-danger { background-color: var(--danger); color: #fff; }
.btn-success { background-color: var(--success); color: #000; }
.btn-small { width: auto; padding: 8px 14px; font-size: 0.9rem; }
.btn-ghost {
background: transparent;
border: 1px solid var(--border);
color: var(--text-secondary);
padding: 6px 10px;
font-size: 0.85rem;
width: auto;
border-radius: 6px;
}
.btn-row { display: flex; gap: 8px; margin-top: 10px; }
.btn-row .btn { flex: 1; }
/* === Cards === */
.card {
background-color: var(--surface);
border-radius: var(--radius);
padding: 14px;
margin-bottom: 12px;
border: 1px solid var(--border);
}
/* === Sync status === */
.sync-status {
font-size: 0.75rem;
color: var(--text-secondary);
display: flex;
align-items: center;
gap: 5px;
margin-top: 2px;
}
.sync-status.synced { color: var(--success); }
.sync-status.pending { color: var(--warning); }
/* === Inputs === */
input, select, textarea {
background-color: var(--surface-2);
border: 1px solid var(--border);
color: var(--text);
border-radius: 8px;
padding: 13px;
font-size: 1rem;
width: 100%;
font-family: inherit;
}
input:focus, select:focus, textarea:focus {
outline: 2px solid var(--primary);
border-color: transparent;
}
input[type="number"] { text-align: center; font-weight: 600; }
textarea { resize: vertical; min-height: 60px; }
/* === Accordion (workout list) === */
.workout-accordion {
margin-bottom: 10px;
border-radius: var(--radius);
overflow: hidden;
border: 1px solid var(--border);
}
.workout-header {
background-color: var(--surface);
padding: 14px;
display: flex;
justify-content: space-between;
align-items: center;
cursor: pointer;
}
.workout-header.active { border-left: 4px solid var(--primary); }
.workout-header.completed { opacity: 0.7; }
.workout-meta {
font-size: 0.8rem;
color: var(--text-secondary);
margin-top: 4px;
}
.workout-body {
background-color: var(--bg);
padding: 12px;
display: none;
}
.workout-body.expanded { display: block; }
.workout-badge {
font-size: 0.7rem;
padding: 3px 8px;
border-radius: 4px;
background: var(--surface-2);
color: var(--text-secondary);
}
.workout-badge.dirty { background: var(--warning); color: #000; }
.workout-badge.synced-badge { background: var(--success); color: #000; }
/* === Exercise accordion === */
.exercise-card {
background-color: var(--surface);
border-radius: var(--radius);
margin-bottom: 10px;
border: 1px solid var(--border);
overflow: hidden;
}
.exercise-header {
padding: 12px 14px;
display: flex;
justify-content: space-between;
align-items: center;
cursor: pointer;
user-select: none;
}
.exercise-header.expanded { border-bottom: 1px solid var(--border); }
.exercise-name { font-weight: 600; color: var(--primary); font-size: 1rem; }
.exercise-summary {
font-size: 0.8rem;
color: var(--text-secondary);
margin-left: 6px;
}
.chevron {
transition: transform 0.2s;
color: var(--text-secondary);
}
.chevron.open { transform: rotate(90deg); }
.exercise-body {
padding: 12px 14px;
display: none;
}
.exercise-body.expanded { display: block; }
/* === Set rows === */
.sets-table { margin-bottom: 12px; }
.set-row {
display: grid;
grid-template-columns: 30px 1fr 1fr 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-rating {
color: var(--warning);
font-size: 0.85rem;
}
.set-actions {
display: flex;
gap: 4px;
}
.icon-btn {
background: transparent;
border: none;
color: var(--text-secondary);
padding: 6px 8px;
cursor: pointer;
border-radius: 4px;
font-size: 1rem;
}
.icon-btn:active { background: var(--surface-2); }
.icon-btn.danger { color: var(--danger); }
/* === Dropset sub-rows === */
.dropset-group {
background: rgba(251, 188, 4, 0.05);
border-left: 3px solid var(--warning);
padding-left: 8px;
margin: 4px 0;
border-radius: 0 6px 6px 0;
}
/* === Stepper (ИСПРАВЛЕНО: теперь в строку) === */
.stepper-row {
display: flex;
gap: 6px;
margin-bottom: 8px;
align-items: center;
flex-wrap: nowrap;
}
/* === Rating buttons === */
.rating-grid {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 6px;
margin: 10px 0;
}
.rating-btn {
background: var(--surface-2);
border: 1px solid var(--border);
color: var(--text);
border-radius: 8px;
padding: 14px 0;
font-size: 1.1rem;
font-weight: 600;
cursor: pointer;
}
.rating-btn.active {
background-color: var(--warning);
color: #000;
border-color: var(--warning);
}
/* === History hint === */
.history-hint {
background: rgba(187, 134, 252, 0.08);
border: 1px dashed var(--primary);
border-radius: 8px;
padding: 10px 12px;
margin-bottom: 14px;
font-size: 0.85rem;
color: var(--text-secondary);
opacity: 0.85;
}
.history-hint-title {
color: var(--primary);
font-weight: 600;
margin-bottom: 6px;
font-size: 0.8rem;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.history-hint-row {
display: flex;
justify-content: space-between;
padding: 3px 0;
border-bottom: 1px dotted var(--border);
}
.history-hint-row:last-child { border-bottom: none; }
.history-hint-date { color: var(--text-secondary); font-size: 0.75rem; }
.history-hint-sets { color: var(--text); font-weight: 500; }
/* === Autocomplete === */
.autocomplete-list {
background: var(--surface-2);
border: 1px solid var(--border);
border-radius: 8px;
max-height: 200px;
overflow-y: auto;
margin-top: 6px;
}
.autocomplete-item {
padding: 12px 14px;
cursor: pointer;
border-bottom: 1px solid var(--border);
font-size: 0.95rem;
}
.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);
}
/* === Finish workout 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; }
/* === Add exercise / cardio buttons === */
.add-section {
display: flex;
gap: 8px;
margin-bottom: 10px;
}
.add-section .btn { flex: 1; }
/* === Modal === */
.modal-overlay {
position: fixed;
top: 0; left: 0;
width: 100%; height: 100%;
background: rgba(0,0,0,0.85);
z-index: 100;
display: flex;
align-items: flex-end;
justify-content: center;
animation: fadeIn 0.2s;
}
.modal-content {
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;
}
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
@keyframes slideUp { from { transform: translateY(100%); } to { transform: translateY(0); } }
.modal-title { margin-bottom: 16px; }
.field-group { margin-bottom: 14px; }
.field-group label {
display: block;
font-size: 0.85rem;
color: var(--text-secondary);
margin-bottom: 6px;
}
.field-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.field-row-3 {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 8px;
}
/* === Empty state === */
.empty-state {
text-align: center;
padding: 40px 20px;
color: var(--text-secondary);
}
.empty-state h3 { color: var(--text); margin-bottom: 10px; }
/* === Settings screen === */
.settings-screen { padding: 12px; }
.settings-section { margin-bottom: 24px; }
.settings-section h3 {
color: var(--primary);
margin-bottom: 12px;
padding-bottom: 8px;
border-bottom: 1px solid var(--border);
}
.exercise-ref-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px;
background: var(--surface);
border-radius: 8px;
margin-bottom: 6px;
border: 1px solid var(--border);
}
.exercise-ref-item .name { font-weight: 500; }
.exercise-ref-item .count {
font-size: 0.75rem;
color: var(--text-secondary);
margin-left: 6px;
}
.exercise-ref-item .type-badge {
font-size: 0.7rem;
padding: 2px 6px;
border-radius: 4px;
background: var(--primary-variant);
color: var(--primary);
margin-left: 6px;
}
/* === Universal stepper field === */
.stepper-field {
display: flex;
align-items: center;
background: var(--surface-2);
border: 1px solid var(--border);
border-radius: 8px;
overflow: hidden;
}
.stepper-field .stepper-btn {
background: transparent;
border: none;
color: var(--primary);
font-size: 1.3rem;
font-weight: bold;
padding: 10px 12px;
cursor: pointer;
flex-shrink: 0;
min-width: 44px;
}
.stepper-field .stepper-btn:active { background: var(--surface); }
.stepper-field input {
border: none;
background: transparent;
text-align: center;
padding: 10px 4px;
font-size: 1rem;
font-weight: 600;
flex: 1;
min-width: 0;
}
.stepper-field input:focus { outline: none; }
/* === Read-only state === */
.read-only-overlay {
position: relative;
}
.read-only-banner {
background: var(--success);
color: #000;
padding: 8px 12px;
border-radius: 8px;
font-size: 0.85rem;
font-weight: 600;
text-align: center;
margin-bottom: 12px;
}
/* === Editable date === */
.editable-date {
display: inline-flex;
align-items: center;
gap: 4px;
cursor: pointer;
padding: 2px 6px;
border-radius: 4px;
}
.editable-date:hover { background: var(--surface-2); }
.editable-date .edit-icon {
font-size: 0.75rem;
color: var(--text-secondary);
opacity: 0;
transition: opacity 0.15s;
}
.editable-date:hover .edit-icon { opacity: 1; }
/* === Utility === */
.hidden { display: none !important; }
.text-muted { color: var(--text-secondary); font-size: 0.85rem; }
.text-small { font-size: 0.8rem; }
.mt-10 { margin-top: 10px; }
.mb-10 { margin-bottom: 10px; }
/* === Клавиатура и модалка: страница под модалкой не скроллится === */
body.modal-open { overflow: hidden; }
/* === История подходов: номер подхода + вес === */
.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;
}
/* === Справочник: типы и группы вариантов === */
.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; }
/* === Время взятия подхода в таблице === */
.set-time { font-size: 0.65rem; color: var(--text-secondary); font-weight: 400; margin-top: 2px; }
/* === Сеты (суперсеты) === */
.circuit-card {
border: 1px solid var(--primary);
border-radius: var(--radius);
background: rgba(187, 134, 252, 0.06);
margin-bottom: 10px;
overflow: hidden;
}
.circuit-header {
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px;
flex-wrap: wrap;
padding: 12px;
border-bottom: 1px dashed var(--border);
}
.circuit-controls { display: flex; gap: 6px; flex-shrink: 0; }
.circuit-controls .btn { font-size: 0.8rem; padding: 8px 10px; }
.circuit-name { font-weight: 700; color: var(--primary); }
.circuit-members { font-size: 0.75rem; color: var(--text-secondary); margin-top: 2px; }
.circuit-round {
display: flex;
align-items: center;
gap: 6px;
padding: 8px 12px;
flex-wrap: wrap;
border-bottom: 1px solid rgba(51, 51, 51, 0.5);
}
.circuit-rounds .circuit-round:last-child { border-bottom: none; }
.round-num {
width: 22px;
height: 22px;
border-radius: 50%;
background: var(--primary);
color: #000;
font-size: 0.75rem;
font-weight: 700;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.circuit-chip {
background: var(--surface-2);
border: 1px solid var(--border);
border-radius: 8px;
padding: 6px 10px;
font-size: 0.85rem;
cursor: pointer;
}
.circuit-chip:active { background: var(--surface); }
.circuit-chip b { font-weight: 600; color: var(--primary); margin-right: 4px; }
.circuit-chip.empty { color: var(--text-secondary); cursor: default; opacity: 0.6; }
.circuit-stars { color: var(--warning); font-size: 0.7rem; margin-left: 4px; }
.circuit-add {
display: flex;
gap: 6px;
padding: 10px 12px;
flex-wrap: wrap;
border-top: 1px dashed var(--border);
}
.circuit-add .btn { width: auto; flex: 1; min-width: 140px; }
/* === Выбор упражнений в сет === */
.group-ex-toggle {
display: flex;
align-items: center;
gap: 8px;
padding: 12px 8px;
border-bottom: 1px solid var(--border);
font-size: 1rem;
color: var(--text);
cursor: pointer;
}
.group-ex-toggle:last-child { border-bottom: none; }
.group-ex-toggle input { width: 20px; height: 20px; accent-color: var(--primary); flex-shrink: 0; }
.group-ex-toggle.disabled { opacity: 0.5; cursor: not-allowed; }