1 Commits

Author SHA1 Message Date
Иван Овчинников d017a757d6 wip: session changes (circuits, variant groups, sync-all, stepper UX) — pre-refactor base 2026-11-20 00:40:15 +03:00
53 changed files with 2500 additions and 5537 deletions
-2
View File
@@ -1,2 +0,0 @@
__pycache__/
*.pyc
+5
View File
@@ -0,0 +1,5 @@
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
-68
View File
@@ -1,68 +0,0 @@
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:
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
def verify_password(password: str, hashed: str) -> bool:
try:
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
-21
View File
@@ -1,21 +0,0 @@
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base
SQLALCHEMY_DATABASE_URL = "sqlite:///./gym.db"
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False} # только для SQLite
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
-52
View File
@@ -1,52 +0,0 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from database import engine, Base
import routers.auth
import routers.clients
import routers.workout_types
import routers.workouts
import routers.exercises
import routers.metrics
import routers.sync
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.get("/")
def root():
return {
"message": "Gym Bro API",
"docs": "/docs",
"version": "1.2.0",
}
@app.get("/health")
def health_check():
return {"status": "ok"}
-296
View File
@@ -1,296 +0,0 @@
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") # personal | trainer
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)
# NULL = глобальный справочник, иначе — личное упражнение пользователя
owner_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), index=True)
workout_type_id = Column(
Integer,
ForeignKey("workout_types.id", ondelete="SET NULL"),
index=True,
)
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)
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)
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)
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
@@ -1,7 +0,0 @@
fastapi==0.104.1
uvicorn[standard]==0.24.0
sqlalchemy==2.0.23
pydantic==2.5.0
python-multipart==0.0.6
PyJWT==2.8.0
bcrypt==4.1.2
-106
View File
@@ -1,106 +0,0 @@
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)
-149
View File
@@ -1,149 +0,0 @@
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
@@ -1,305 +0,0 @@
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
@@ -1,284 +0,0 @@
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"}
-551
View File
@@ -1,551 +0,0 @@
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: Session,
user: models.User,
client_sync_id: Optional[str],
client_map: Dict[str, int],
) -> Optional[int]:
if not client_sync_id:
return None
if client_sync_id in client_map:
return client_map[client_sync_id]
client = (
db.query(models.Client)
.filter(
models.Client.sync_id == client_sync_id,
models.Client.owner_id == user.id,
)
.first()
)
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: 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
@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 = resolve_client_id_from_sync_id(
db,
current_user,
metric_data.client_sync_id,
client_map,
)
if metric_data.client_id and not client_id:
client = (
db.query(models.Client)
.filter(
models.Client.id == metric_data.client_id,
models.Client.owner_id == current_user.id,
)
.first()
)
client_id = client.id if client else None
existing.client_id = client_id
db.query(models.BodyMetricValue).filter(
models.BodyMetricValue.body_metric_id == existing.id
).delete()
for value_data in metric_data.values or []:
mt = resolve_metric_type_for_sync(db, value_data)
if not mt:
warnings.append("Body metric value skipped: metric type not found")
continue
db.add(
models.BodyMetricValue(
body_metric_id=existing.id,
metric_type_id=mt.id,
value=float(value_data.value),
)
)
updated["body_metrics"] += 1
continue
client_id = resolve_client_id_from_sync_id(
db,
current_user,
metric_data.client_sync_id,
client_map,
)
if metric_data.client_id and not client_id:
client = (
db.query(models.Client)
.filter(
models.Client.id == metric_data.client_id,
models.Client.owner_id == current_user.id,
)
.first()
)
client_id = client.id if client else None
db_metric = models.BodyMetric(
sync_id=sync_id,
owner_id=current_user.id,
client_id=client_id,
metric_date=metric_data.metric_date,
notes=metric_data.notes or "",
created_at=timestamp,
)
db.add(db_metric)
db.flush()
created["body_metrics"] += 1
for value_data in metric_data.values or []:
mt = resolve_metric_type_for_sync(db, value_data)
if not mt:
warnings.append("Body metric value skipped: metric type not found")
continue
db.add(
models.BodyMetricValue(
body_metric_id=db_metric.id,
metric_type_id=mt.id,
value=float(value_data.value),
)
)
db.commit()
return schemas.SyncResponse(
status="success",
created=created,
updated=updated,
warnings=warnings,
)
-62
View File
@@ -1,62 +0,0 @@
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
@@ -1,294 +0,0 @@
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"}
-347
View File
@@ -1,347 +0,0 @@
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)
-19
View File
@@ -1,19 +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/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>
-44
View File
@@ -1,44 +0,0 @@
// Базовый URL API. Если фронт и бэк на одном домене, можно использовать '' или '/api'
const API_BASE = 'http://localhost:8000';
export async function fetchWorkoutTypes() {
const res = await fetch(`${API_BASE}/workout-types/`);
if (!res.ok) throw new Error('Failed to fetch workout types');
return await res.json();
}
export async function fetchMetricTypes() {
const res = await fetch(`${API_BASE}/metric-types/`);
if (!res.ok) throw new Error('Failed to fetch metric types');
return await res.json();
}
export async function fetchClients() {
const res = await fetch(`${API_BASE}/clients/`);
if (!res.ok) throw new Error('Failed to fetch clients');
return await res.json();
}
export async function fetchExerciseHistory(exerciseName, clientId = null) {
let url = `${API_BASE}/exercises/history/${encodeURIComponent(exerciseName)}?limit=10`;
if (clientId) url += `&client_id=${clientId}`;
const res = await fetch(url);
if (!res.ok) throw new Error('Failed to fetch history');
return await res.json();
}
export async function syncData(payload) {
const res = await fetch(`${API_BASE}/sync/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (!res.ok) {
const err = await res.json();
console.error('❌ Sync API Error Detail:', err); // <-- Покажет, какое именно поле не прошло валидацию
throw new Error(err.detail ? JSON.stringify(err.detail) : 'Sync failed');
}
return await res.json();
}
-65
View File
@@ -1,65 +0,0 @@
import { loadState, saveState, state, updateSyncStatus } from './state.js';
import { renderMainScreen } from './render/main-screen.js';
import { sync, initAppData } from './sync.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/client-select-modal.js';
import './modals/edit-exercise-modal.js';
import './modals/edit-workout-date-modal.js';
function renderHeader() {
const modeLabel = state.mode === 'trainer' ? '👨‍🏫 Тренер' : '👤 Личный';
document.getElementById('app-header').innerHTML = `
<div>
<h2>Gym Bro <span style="font-size:0.8rem; color:var(--text-secondary); font-weight:400;">(${modeLabel})</span></h2>
<div id="sync-status" class="sync-status">● Локально</div>
</div>
<div class="header-actions">
<button class="icon-btn header-btn" onclick="App.toggleMode()" title="Сменить режим">🔄</button>
<button class="icon-btn header-btn" onclick="ML.showBodyMetrics()" title="Личные замеры">📏</button>
<button class="icon-btn header-btn" onclick="SettingsLogic.show()" title="Настройки">⚙️</button>
<button class="btn btn-small btn-secondary" onclick="AppSync.sync()" title="Синхронизация">🔄</button>
</div>
`;
}
async function init() {
loadState();
renderHeader();
renderMainScreen();
updateSyncStatus();
// Загружаем справочники с бэкенда в фоне
await initAppData();
}
window.App = {
getWorkout: (id) => state.workouts.find(w => w.id === id),
saveAndRender: () => { saveState(); },
toggleMode: () => {
state.mode = state.mode === 'personal' ? 'trainer' : 'personal';
saveState();
renderHeader();
renderMainScreen();
},
backToMain: () => renderMainScreen(),
};
window.AppSync = { sync };
// Делаем renderMainScreen доступным глобально
window.renderMainScreen = renderMainScreen;
document.addEventListener('DOMContentLoaded', init);
-35
View File
@@ -1,35 +0,0 @@
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
@@ -1,126 +0,0 @@
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,
};
-51
View File
@@ -1,51 +0,0 @@
import { state, saveState, genId } from '../state.js';
import { renderMainScreen } from '../render/main-screen.js';
import { showBodyMetricsDialog } from '../modals/metrics-modal.js';
export function showBodyMetrics() {
// В личном режиме — замеры без клиента
const personalMetrics = state.bodyMetrics.filter(m => !m.client_id);
showBodyMetricsDialog(personalMetrics, (newMetric) => {
if (!newMetric) return;
newMetric.id = genId();
newMetric.client_id = null; // личный замер
state.bodyMetrics.unshift(newMetric);
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;
showBodyMetricsDialog(state.bodyMetrics, (updatedData) => {
if (!updatedData) return;
Object.assign(metric, updatedData);
state.bodyMetrics.sort((a, b) => new Date(b.date) - new Date(a.date));
saveState();
// Обновляем список в настройках, если он открыт
const list = document.getElementById('body-metrics-list');
if (list && typeof window.SettingsLogic !== 'undefined') {
window.SettingsLogic._renderPersonalMetricsList();
} else {
renderMainScreen();
}
}, metric);
}
export function deleteMetric(id) {
if (!confirm('Удалить замер?')) return;
state.bodyMetrics = state.bodyMetrics.filter(m => m.id !== id);
saveState();
const list = document.getElementById('body-metrics-list');
if (list && typeof window.SettingsLogic !== 'undefined') {
window.SettingsLogic._renderPersonalMetricsList();
} else {
renderMainScreen();
}
}
window.ML = { showBodyMetrics, editBodyMetric, deleteMetric };
-91
View File
@@ -1,91 +0,0 @@
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,
};
-498
View File
@@ -1,498 +0,0 @@
import { state, saveState, CLIENT_COLORS, DEFAULT_COLOR, genId, generateUUID } from '../state.js';
import { showEditExerciseDialog } from '../modals/edit-exercise-modal.js';
import { showBodyMetricsDialog } from '../modals/metrics-modal.js';
import { showModal } from '../modals/modal-base.js';
export function showSettings() {
const app = document.getElementById('app');
app.innerHTML = '';
const screen = document.createElement('div');
screen.className = 'settings-screen';
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="settings-section">
<h3>👥 Клиенты</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>
<div class="settings-section">
<h3>📋 Справочник упражнений</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>
${state.workoutTypes.map(wt => `<option value="${wt.name}">${wt.name}</option>`).join('')}
</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>
<div class="settings-section">
<h3>📏 Личные замеры</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>
<div class="settings-section">
<h3>🗑 Данные</h3>
<button class="btn btn-danger" onclick="SettingsLogic.clearAllData()">Очистить все данные</button>
</div>
`;
app.appendChild(screen);
_renderClientsList();
_renderRefExercises();
_renderPersonalMetricsList();
}
export function _renderPersonalMetricsList() {
const list = document.getElementById('body-metrics-list');
if (!list) return;
const personalMetrics = state.bodyMetrics.filter(m => !m.client_id);
if (personalMetrics.length === 0) {
list.innerHTML = '<p class="text-muted text-small">Нет личных замеров</p>';
return;
}
list.innerHTML = personalMetrics.map(m => {
const date = new Date(m.date);
const dateStr = date.toLocaleDateString('ru-RU') + ' ' + date.toLocaleTimeString('ru-RU', {hour:'2-digit', minute:'2-digit'});
const parts = [];
if (m.weight) parts.push(`⚖️ ${m.weight} кг`);
if (m.chest) parts.push(`📏 ${m.chest} см`);
if (m.waist) parts.push(`📏 ${m.waist} см`);
if (m.hips) parts.push(`📏 ${m.hips} см`);
if (m.arms) parts.push(`💪 ${m.arms} см`);
if (m.legs) parts.push(`🦵 ${m.legs} см`);
return `
<div class="exercise-ref-item">
<div>
<div style="font-weight:500;">${dateStr}</div>
<div class="text-small text-muted">${parts.join(' • ') || '—'}</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 addRefExercise() {
const input = document.getElementById('new-ref-exercise');
const typeSelect = document.getElementById('new-ref-type');
const name = input.value.trim();
if (!name) return;
const normalizedName = name.trim().toLowerCase();
const exists = state.exerciseRef.find(
e => e.name.trim().toLowerCase() === normalizedName
);
if (!exists) {
state.exerciseRef.push({
id: (state.nextId++).toString(),
name: name.trim(),
workoutType: typeSelect.value,
});
}
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();
}
}
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 clearAllData() {
if (!confirm('Удалить ВСЕ данные? Это действие необратимо!')) return;
if (!confirm('Точно уверены?')) return;
localStorage.clear();
location.reload();
}
export function _renderRefExercises() {
const list = document.getElementById('ref-exercises-list');
if (!list) return;
if (state.exerciseRef.length === 0) {
list.innerHTML = '<p class="text-muted text-small">Справочник пуст</p>';
return;
}
const sorted = [...state.exerciseRef].sort((a, b) => {
if (a.workoutType !== b.workoutType) return (a.workoutType || '').localeCompare(b.workoutType || '');
return a.name.localeCompare(b.name);
});
// Генерируем опции для select динамически из state.workoutTypes
const typeOptions = state.workoutTypes.map(wt =>
`<option value="${wt.name}" ${a => a.workoutType === wt.name ? 'selected' : ''}>${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>
${state.workoutTypes.map(wt => `<option value="${wt.name}" ${ex.workoutType === wt.name ? 'selected' : ''}>${wt.name}</option>`).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 _renderMetricTypes() {
const container = document.getElementById('metric-types-list');
if (!container) return;
if (state.metricTypes.length === 0) {
container.innerHTML = '<p class="text-muted text-small">Нет типов замеров</p>';
return;
}
container.innerHTML = state.metricTypes.map(mt => `
<div class="exercise-ref-item">
<div>
<span class="name">${mt.name}</span>
<span class="type-badge">${mt.unit}</span>
</div>
</div>
`).join('');
}
export function _renderBodyMetricsList() {
const list = document.getElementById('body-metrics-list');
if (!list) return;
if (state.bodyMetrics.length === 0) {
list.innerHTML = '<p class="text-muted text-small">Нет замеров</p>';
return;
}
list.innerHTML = state.bodyMetrics.map(m => {
const date = new Date(m.date);
const dateStr = date.toLocaleDateString('ru-RU') + ' ' + date.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });
const parts = [];
if (m.weight) parts.push(`⚖️ ${m.weight} кг`);
if (m.chest) parts.push(`📏 ${m.chest} см`);
if (m.waist) parts.push(`📏 ${m.waist} см`);
if (m.hips) parts.push(`📏 ${m.hips} см`);
if (m.arms) parts.push(`💪 ${m.arms} см`);
if (m.legs) parts.push(`🦵 ${m.legs} см`);
return `
<div class="exercise-ref-item">
<div>
<div style="font-weight:500;">${dateStr}</div>
<div class="text-small text-muted">${parts.join(' • ') || '—'}</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 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};"
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>
`;
showModal(html);
window._tempClientColor = client.color;
}
export function selectClientColor(color) {
window._tempClientColor = color;
document.querySelectorAll('#m-client-palette .color-swatch').forEach(el => {
el.classList.toggle('selected', el.style.background === color ||
rgbToHex(el.style.backgroundColor) === color.toLowerCase());
});
}
function rgbToHex(rgb) {
if (rgb.startsWith('#')) return rgb.toLowerCase();
const match = rgb.match(/\d+/g);
if (!match) return rgb;
return '#' + match.slice(0, 3).map(x => parseInt(x).toString(16).padStart(2, '0')).join('');
}
export function submitClient(editingId) {
const name = document.getElementById('m-client-name').value.trim();
if (!name) { alert('Введите ФИО'); return; }
const color = window._tempClientColor || DEFAULT_COLOR;
if (editingId) {
// Редактирование
const client = state.clients.find(c => c.id == editingId);
if (client) {
client.full_name = name;
client.birth_date = document.getElementById('m-client-dob').value || null;
client.goal = document.getElementById('m-client-goal').value.trim();
client.color = color;
}
} else {
// Создание
const newClient = {
id: genId(),
sync_id: generateUUID(),
full_name: name,
birth_date: document.getElementById('m-client-dob').value || null,
goal: document.getElementById('m-client-goal').value.trim(),
color: color,
is_active: 1,
};
state.clients.push(newClient);
}
saveState();
window.ModalBase.closeModal();
_renderClientsList();
window.renderMainScreen(); // Обновляем цвета тренировок
}
export function deleteClient(id) {
if (!confirm('Удалить клиента? Тренировки останутся, но без привязки.')) return;
state.clients = state.clients.filter(c => c.id != id);
// Отвязываем тренировки
state.workouts.forEach(w => {
if (w.client_id == id) w.client_id = null;
});
// Отвязываем замеры
state.bodyMetrics.forEach(m => {
if (m.client_id == id) m.client_id = null;
});
saveState();
_renderClientsList();
window.renderMainScreen();
}
export function _renderClientsList() {
const list = document.getElementById('clients-list');
if (!list) return;
if (state.clients.length === 0) {
list.innerHTML = '<p class="text-muted text-small">Нет клиентов. Добавьте первого!</p>';
return;
}
list.innerHTML = state.clients.map(c => {
// Считаем замеры этого клиента
const clientMetrics = state.bodyMetrics.filter(m => m.client_id == c.id);
const lastMetric = clientMetrics[0]; // уже отсортированы по дате
let metricsPreview = 'Нет замеров';
if (lastMetric) {
const parts = [];
if (lastMetric.weight) parts.push(`⚖️ ${lastMetric.weight} кг`);
if (lastMetric.chest) parts.push(`📏 ${lastMetric.chest} см`);
metricsPreview = parts.join(' • ') || 'Замеры без значений';
}
// Считаем тренировки
const clientWorkouts = state.workouts.filter(w => w.client_id == c.id);
return `
<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>
${lastMetric ? `<div class="text-small" style="margin-top:2px; color:var(--text-secondary);">Последний: ${metricsPreview}</div>` : ''}
</div>
<div style="display:flex; gap:4px; flex-direction:column;">
<button class="icon-btn" onclick="SettingsLogic.showClientMetrics('${c.id}')" title="Замеры">📏</button>
<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 showClientMetrics(clientId) {
const client = state.clients.find(c => c.id == clientId);
if (!client) return;
const clientMetrics = state.bodyMetrics
.filter(m => m.client_id == clientId)
.sort((a, b) => new Date(b.date) - new Date(a.date));
const metricsHtml = clientMetrics.length === 0
? '<p class="text-muted text-small">Нет замеров</p>'
: clientMetrics.map(m => {
const date = new Date(m.date);
const dateStr = date.toLocaleDateString('ru-RU') + ' ' + date.toLocaleTimeString('ru-RU', {hour:'2-digit', minute:'2-digit'});
const parts = [];
if (m.weight) parts.push(`⚖️ ${m.weight} кг`);
if (m.chest) parts.push(`📏 ${m.chest} см`);
if (m.waist) parts.push(`📏 ${m.waist} см`);
if (m.hips) parts.push(`📏 ${m.hips} см`);
if (m.arms) parts.push(`💪 ${m.arms} см`);
if (m.legs) parts.push(`🦵 ${m.legs} см`);
return `
<div class="exercise-ref-item">
<div>
<div style="font-weight:500;">${dateStr}</div>
<div class="text-small text-muted">${parts.join(' • ') || '—'}</div>
</div>
<div style="display:flex; gap:4px;">
<button class="icon-btn" onclick="SettingsLogic.editClientMetric('${m.id}', '${clientId}')">✎</button>
<button class="icon-btn danger" onclick="SettingsLogic.deleteClientMetric('${m.id}', '${clientId}')">✕</button>
</div>
</div>
`;
}).join('');
const html = `
<div class="modal-content">
<h3 class="modal-title">📏 Замеры: ${client.full_name}</h3>
<div id="client-metrics-list" style="max-height:50vh; overflow-y:auto;">
${metricsHtml}
</div>
<div class="btn-row" style="margin-top:16px;">
<button class="btn btn-secondary" onclick="ModalBase.closeModal()">Закрыть</button>
<button class="btn" onclick="SettingsLogic.addClientMetric('${clientId}')">+ Добавить замер</button>
</div>
</div>
`;
showModal(html);
}
export function addClientMetric(clientId) {
showBodyMetricsDialog(
state.bodyMetrics.filter(m => m.client_id == clientId),
(newMetric) => {
if (!newMetric) return;
newMetric.id = genId();
newMetric.client_id = parseInt(clientId);
state.bodyMetrics.unshift(newMetric);
state.bodyMetrics.sort((a, b) => new Date(b.date) - new Date(a.date));
saveState();
showClientMetrics(clientId); // Перерисовываем модалку
}
);
}
export function editClientMetric(metricId, clientId) {
const metric = state.bodyMetrics.find(m => m.id === metricId);
if (!metric) return;
showBodyMetricsDialog(
state.bodyMetrics,
(updatedData) => {
if (!updatedData) return;
Object.assign(metric, updatedData);
state.bodyMetrics.sort((a, b) => new Date(b.date) - new Date(a.date));
saveState();
showClientMetrics(clientId);
},
metric
);
}
export function deleteClientMetric(metricId, clientId) {
if (!confirm('Удалить замер?')) return;
state.bodyMetrics = state.bodyMetrics.filter(m => m.id !== metricId);
saveState();
showClientMetrics(clientId);
}
// Обновляем экспорт
window.SettingsLogic = {
show: showSettings,
addRefExercise, deleteRefExercise, updateRefExerciseType,
editRefExercise, clearAllData,
_renderRefExercises, _renderBodyMetricsList,
// Клиенты:
showAddClientModal, submitClient, deleteClient, _renderClientsList,
selectClientColor,
// Замеры клиента:
showClientMetrics, addClientMetric, editClientMetric, deleteClientMetric,
};
// Делаем state доступным для inline onclick
window.state = state;
-88
View File
@@ -1,88 +0,0 @@
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
@@ -1,57 +0,0 @@
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
@@ -1,58 +0,0 @@
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
@@ -1,42 +0,0 @@
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 };
@@ -1,41 +0,0 @@
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
@@ -1,60 +0,0 @@
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 };
-44
View File
@@ -1,44 +0,0 @@
import { showModal, closeModal, stepperHtml } from './modal-base.js';
import { toDatetimeLocal } from '../utils.js';
let _cb = null;
export function showBodyMetricsDialog(metrics, callback, editing = null) {
_cb = callback;
const src = editing || metrics[0] || {};
const isEdit = !!editing;
const dateVal = src.date ? toDatetimeLocal(src.date) : toDatetimeLocal(new Date().toISOString());
showModal(`<div class="modal-content">
<h3 class="modal-title">📏 Замеры ${isEdit ? '(ред.)' : ''}</h3>
<div class="field-group"><label>📅 Дата</label><input type="datetime-local" id="m-md" value="${dateVal}"></div>
<div class="field-row">
<div class="field-group"><label>⚖️ Вес</label>${stepperHtml('m-mw', src.weight??'', 0.1, 'кг')}</div>
<div class="field-group"><label>📏 Грудь</label>${stepperHtml('m-mc', src.chest??'', 1, 'см', 'numeric')}</div></div>
<div class="field-row">
<div class="field-group"><label>📏 Талия</label>${stepperHtml('m-mwa', src.waist??'', 1, 'см', 'numeric')}</div>
<div class="field-group"><label>📏 Бёдра</label>${stepperHtml('m-mh', src.hips??'', 1, 'см', 'numeric')}</div></div>
<div class="field-row">
<div class="field-group"><label>💪 Руки</label>${stepperHtml('m-ma', src.arms??'', 0.5, 'см')}</div>
<div class="field-group"><label>🦵 Ноги</label>${stepperHtml('m-ml', src.legs??'', 0.5, 'см')}</div></div>
<div class="btn-row">
<button class="btn btn-secondary" onclick="ModalBase.closeOnBg({target:document.querySelector('.modal-overlay')})">Отмена</button>
<button class="btn btn-success" onclick="MetricsModal.submit(${isEdit})">Сохранить</button></div>
</div>`);
}
export function submit(isEdit) {
const r = {
date: new Date(document.getElementById('m-md').value).toISOString(),
weight: parseFloat(document.getElementById('m-mw').value)||null,
chest: parseInt(document.getElementById('m-mc').value)||null,
waist: parseInt(document.getElementById('m-mwa').value)||null,
hips: parseInt(document.getElementById('m-mh').value)||null,
arms: parseFloat(document.getElementById('m-ma').value)||null,
legs: parseFloat(document.getElementById('m-ml').value)||null,
};
if (!Object.values(r).some((v,i) => i>0 && v!==null)) { alert('Заполните поле'); return; }
closeModal(); _cb?.(r, isEdit);
}
window.MetricsModal = { submit };
-39
View File
@@ -1,39 +0,0 @@
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
@@ -1,127 +0,0 @@
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
@@ -1,30 +0,0 @@
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;
}
-60
View File
@@ -1,60 +0,0 @@
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
@@ -1,59 +0,0 @@
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
@@ -1,35 +0,0 @@
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
@@ -1,206 +0,0 @@
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;
}
-88
View File
@@ -1,88 +0,0 @@
const STORAGE_KEY = 'gym_tracker_v6';
// Палитра из 16 контрастных цветов для клиентов
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];
export const state = {
workouts: [],
exerciseRef: [],
bodyMetrics: [],
workoutTypes: [],
metricTypes: [],
clients: [], // каждый клиент: {id, sync_id, full_name, birth_date, goal, color}
expandedWorkoutId: null,
expandedExerciseId: null,
nextId: 1,
mode: 'personal',
currentClientId: null, // больше не используется глобально, но оставим для совместимости
};
export function loadState() {
const saved = localStorage.getItem(STORAGE_KEY);
if (saved) {
try {
const parsed = JSON.parse(saved);
// Объединяем, чтобы не потерять новые поля при обновлении версии
Object.assign(state, parsed);
if (!state.workoutTypes) state.workoutTypes = [];
if (!state.metricTypes) state.metricTypes = [];
if (!state.clients) state.clients = [];
if (!state.mode) state.mode = 'personal';
} catch (e) {
console.error('Failed to load state', e);
}
}
}
export function saveState() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
updateSyncStatus();
}
export function genId() {
return (state.nextId++).toString();
}
// Генерация UUID v4 для sync_id (идемпотентность на бэкенде)
export function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
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';
}
}
-243
View File
@@ -1,243 +0,0 @@
import { state, saveState, generateUUID } from "./state.js";
import { syncData } from "./api.js";
import { renderMainScreen } from "./render/main-screen.js";
export async function initAppData() {
try {
const { fetchWorkoutTypes, fetchMetricTypes } = await import("./api.js");
state.workoutTypes = await fetchWorkoutTypes();
state.metricTypes = await fetchMetricTypes();
saveState();
console.log("Справочники загружены с бэкенда");
} catch (e) {
console.warn("Не удалось загрузить справочники (возможно, бэк недоступен):", e);
}
}
export function getDirtyWorkouts() {
return state.workouts.filter((w) => !w.synced);
}
function ensureSyncId(obj) {
if (!obj) return null;
if (!obj.sync_id) {
obj.sync_id = generateUUID();
}
return obj.sync_id;
}
function findWorkoutTypeByName(name) {
if (!name) return null;
return state.workoutTypes.find((t) => t.name === name) || null;
}
function findExerciseRefByName(name) {
const normalized = String(name || "").trim().toLowerCase();
if (!normalized) return null;
return (
state.exerciseRef.find(
(e) => String(e.name || "").trim().toLowerCase() === normalized
) || null
);
}
function findClientByLocalId(clientId) {
if (clientId === undefined || clientId === null || clientId === "") return null;
return (
state.clients.find((c) => String(c.id) === String(clientId)) || 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 : (parseFloat(s.weight) || null),
reps: isDropset ? null : (parseInt(s.reps, 10) || null),
rating: s.rating || 3,
notes: s.notes || "",
sort_order: s.sort_order ?? setIndex,
timestamp: s.timestamp || new Date().toISOString(),
dropset_items: isDropset
? (s.subSets || []).map((item, itemIndex) => ({
weight: parseFloat(item.weight) || 0,
reps: parseInt(item.reps, 10) || 0,
sort_order: item.sort_order ?? itemIndex,
}))
: [],
};
});
}
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 || 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: 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 ?? 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,
client_id: null,
client_sync_id: client ? client.sync_id : null,
workout_type_id: wt ? wt.id : null,
start_time: w.startTime,
end_time: w.endTime || null,
notes: w.notes || "",
workout_exercises: buildWorkoutExercisesPayload(w.exercises),
cardio_sessions: buildCardioPayload(w.cardio),
};
});
}
export async function sync() {
const dirty = getDirtyWorkouts();
if (dirty.length === 0) {
alert("Нет данных для синхронизации");
return;
}
const btn = document.querySelector(".header-actions .btn-secondary");
if (btn) {
btn.disabled = true;
btn.textContent = "⏳";
}
try {
// Генерируем sync_id локально и сохраняем, чтобы при повторе не плодить дубли
state.clients.forEach(ensureSyncId);
state.exerciseRef.forEach(ensureSyncId);
dirty.forEach((w) => {
ensureSyncId(w);
(w.exercises || []).forEach((ex) => {
ensureSyncId(ex);
(ex.sets || []).forEach(ensureSyncId);
});
(w.cardio || []).forEach(ensureSyncId);
});
saveState();
const payload = {
clients: buildClientsPayload(),
exercises: buildExercisesPayload(),
workouts: buildWorkoutsPayload(dirty),
body_metrics: [], // динамические замеры подключим следующим этапом
};
console.log("📤 Отправляем на синхронизацию:", payload);
const response = await syncData(payload);
console.log("✅ Ответ синхронизации:", response);
dirty.forEach((w) => {
w.synced = true;
});
saveState();
if (typeof window.renderMainScreen === "function") {
window.renderMainScreen();
} else {
renderMainScreen();
}
const createdWorkouts = response.created?.workouts || 0;
const updatedWorkouts = response.updated?.workouts || 0;
const warnings = response.warnings || [];
let message = `Синхронизировано: создано ${createdWorkouts}, обновлено ${updatedWorkouts}`;
if (warnings.length) {
message += `\n\nПредупреждения:\n${warnings.join("\n")}`;
}
alert(message);
} catch (e) {
console.error("❌ Sync error:", e);
alert("Ошибка синхронизации: " + e.message);
} finally {
if (btn) {
btn.disabled = false;
btn.textContent = "🔄";
}
}
}
-28
View File
@@ -1,28 +0,0 @@
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())}`;
}
-132
View File
@@ -1,132 +0,0 @@
/* === 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
@@ -1,57 +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; }
.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
@@ -1,25 +0,0 @@
/* === 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
@@ -1,18 +0,0 @@
/* === 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
@@ -1,70 +0,0 @@
/* === 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
@@ -0,0 +1,30 @@
<!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
@@ -0,0 +1,742 @@
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,
});
},
};
-21
View File
@@ -1,21 +0,0 @@
# gym bro
``` text
clients (ФИО, ДР, цель)
│
│ 1:N
├──► workouts ──────► workout_types (справочник)
│ │
│ │ 1:N
│ ├──► workout_exercises ──► exercises ──► workout_types
│ │ │
│ │ │ 1:N
│ │ └──► sets ──► dropset_items
│ │
│ └──► cardio
│
└──► body_metrics
│
│ 1:N
└──► body_metric_values ──► metric_types (справочник)
```
-224
View File
@@ -1,224 +0,0 @@
-- ============================================================
-- 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
@@ -1,89 +0,0 @@
-- ============================================================
-- Тестовые данные 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
@@ -1,123 +0,0 @@
-- ============================================================
-- Проверочные запросы 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
@@ -0,0 +1,623 @@
: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; }