lots of work done, dashboards added
This commit is contained in:
+10
-2
@@ -1,3 +1,7 @@
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
|
||||
import bcrypt
|
||||
import jwt
|
||||
from jwt.exceptions import PyJWTError
|
||||
@@ -18,12 +22,16 @@ bearer_scheme = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||
# bcrypt.hashpw ожидает байты, возвращает байты. Декодируем в string для хранения.
|
||||
salt = bcrypt.gensalt()
|
||||
hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
|
||||
return hashed.decode('utf-8')
|
||||
|
||||
|
||||
def verify_password(password: str, hashed: str) -> bool:
|
||||
try:
|
||||
return bcrypt.checkpw(password.encode("utf-8"), hashed.encode("utf-8"))
|
||||
# bcrypt.checkpw ожидает байты
|
||||
return bcrypt.checkpw(password.encode('utf-8'), hashed.encode('utf-8'))
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
+7
-1
@@ -3,9 +3,10 @@
|
||||
import os
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from database import engine, Base
|
||||
from pathlib import Path
|
||||
|
||||
import routers.bootstrap
|
||||
import routers.auth
|
||||
import routers.clients
|
||||
import routers.workout_types
|
||||
@@ -14,6 +15,10 @@ import routers.exercises
|
||||
import routers.metrics
|
||||
import routers.sync
|
||||
|
||||
# Создаем директорию для БД, если её нет
|
||||
db_path = os.getenv("GYM_DB_PATH", "./gym.db")
|
||||
Path(db_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Гарантируем, что директория существует
|
||||
os.makedirs(os.path.dirname(os.getenv("GYM_DB_PATH", "./gym.db")), exist_ok=True)
|
||||
|
||||
@@ -41,6 +46,7 @@ app.include_router(routers.workouts.router)
|
||||
app.include_router(routers.exercises.router)
|
||||
app.include_router(routers.metrics.router)
|
||||
app.include_router(routers.sync.router)
|
||||
app.include_router(routers.bootstrap.router)
|
||||
|
||||
|
||||
@app.get("/")
|
||||
|
||||
+10
-12
@@ -11,7 +11,6 @@ from sqlalchemy.orm import relationship
|
||||
|
||||
from database import Base
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
@@ -19,7 +18,7 @@ class User(Base):
|
||||
username = Column(String, unique=True, nullable=False, index=True)
|
||||
password_hash = Column(String, nullable=False)
|
||||
display_name = Column(String, default="")
|
||||
role = Column(String, default="personal") # personal | trainer
|
||||
role = Column(String, default="personal")
|
||||
created_at = Column(String)
|
||||
|
||||
|
||||
@@ -32,7 +31,10 @@ class WorkoutType(Base):
|
||||
sort_order = Column(Integer, default=0)
|
||||
created_at = Column(String)
|
||||
|
||||
# ВАЖНО: Эта строка должна быть здесь!
|
||||
exercises = relationship("Exercise", back_populates="workout_type")
|
||||
|
||||
# Если есть другие отношения, они тоже должны быть прописаны
|
||||
workouts = relationship("Workout", back_populates="workout_type")
|
||||
|
||||
|
||||
@@ -42,20 +44,16 @@ class Exercise(Base):
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
sync_id = Column(String, unique=True, nullable=False, index=True)
|
||||
|
||||
# NULL = глобальный справочник, иначе — личное упражнение пользователя
|
||||
owner_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), index=True)
|
||||
|
||||
workout_type_id = Column(
|
||||
Integer,
|
||||
ForeignKey("workout_types.id", ondelete="SET NULL"),
|
||||
index=True,
|
||||
)
|
||||
workout_type_id = Column(Integer, ForeignKey("workout_types.id", ondelete="SET NULL"), index=True)
|
||||
|
||||
name = Column(String, nullable=False, index=True)
|
||||
created_at = Column(String)
|
||||
updated_at = Column(String)
|
||||
|
||||
# ВАЖНО: И эта строка тоже!
|
||||
workout_type = relationship("WorkoutType", back_populates="exercises")
|
||||
|
||||
workout_exercises = relationship("WorkoutExercise", back_populates="exercise")
|
||||
|
||||
|
||||
@@ -73,7 +71,7 @@ class Client(Base):
|
||||
color = Column(String)
|
||||
is_active = Column(Integer, default=1)
|
||||
|
||||
created_at = Column(String)
|
||||
created_at = Column(String, default=lambda: datetime.utcnow().isoformat())
|
||||
updated_at = Column(String)
|
||||
|
||||
workouts = relationship("Workout", back_populates="client")
|
||||
@@ -232,7 +230,7 @@ class MetricType(Base):
|
||||
unit = Column(String, default="см")
|
||||
category = Column(String, default="body")
|
||||
sort_order = Column(Integer, default=0)
|
||||
created_at = Column(String)
|
||||
created_at = Column(String, default=lambda: datetime.utcnow().isoformat())
|
||||
|
||||
metric_values = relationship("BodyMetricValue", back_populates="metric_type")
|
||||
|
||||
@@ -248,7 +246,7 @@ class BodyMetric(Base):
|
||||
|
||||
metric_date = Column(String, nullable=False)
|
||||
notes = Column(String, default="")
|
||||
created_at = Column(String)
|
||||
created_at = Column(String, default=lambda: datetime.utcnow().isoformat())
|
||||
|
||||
client = relationship("Client", back_populates="body_metrics")
|
||||
values = relationship(
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
-i https://mirror.yandex.ru/pypi/simple/
|
||||
--trusted-host mirror.yandex.ru
|
||||
fastapi==0.104.1
|
||||
uvicorn[standard]==0.24.0
|
||||
sqlalchemy==2.0.23
|
||||
pydantic==2.5.0
|
||||
python-multipart==0.0.6
|
||||
PyJWT==2.8.0
|
||||
bcrypt==4.1.2
|
||||
fastapi==0.115.6
|
||||
uvicorn[standard]==0.32.1
|
||||
sqlalchemy==2.0.36
|
||||
pydantic==2.10.4
|
||||
python-multipart==0.0.20
|
||||
PyJWT==2.10.1
|
||||
bcrypt==4.2.1
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
# backend/routers/bootstrap.py
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
from sqlalchemy import or_
|
||||
import auth
|
||||
import database
|
||||
import models
|
||||
import schemas
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/bootstrap",
|
||||
tags=["bootstrap"],
|
||||
dependencies=[Depends(auth.get_current_user)],
|
||||
)
|
||||
|
||||
@router.get("/")
|
||||
def get_bootstrap_data(
|
||||
current_user: models.User = Depends(auth.get_current_user),
|
||||
db: Session = Depends(database.get_db),
|
||||
):
|
||||
"""
|
||||
Возвращает ВСЕ данные пользователя для инициализации фронтенда.
|
||||
Безопасная версия с проверкой NULL-связей.
|
||||
"""
|
||||
|
||||
try:
|
||||
# 1. Типы тренировок (глобальные)
|
||||
workout_types = db.query(models.WorkoutType).order_by(models.WorkoutType.sort_order).all()
|
||||
|
||||
# 2. Типы замеров (глобальные)
|
||||
metric_types = db.query(models.MetricType).order_by(models.MetricType.sort_order).all()
|
||||
|
||||
# 3. Клиенты пользователя
|
||||
clients = db.query(models.Client).filter(models.Client.owner_id == current_user.id).all()
|
||||
|
||||
# 4. Упражнения пользователя + глобальные
|
||||
exercises = db.query(models.Exercise).filter(
|
||||
or_(
|
||||
models.Exercise.owner_id == current_user.id,
|
||||
models.Exercise.owner_id.is_(None)
|
||||
)
|
||||
).all()
|
||||
|
||||
# 5. Тренировки пользователя (полные, с подходами и кардио)
|
||||
workouts = db.query(models.Workout).options(
|
||||
joinedload(models.Workout.workout_exercises).joinedload(models.WorkoutExercise.sets).joinedload(models.Set.dropset_items),
|
||||
joinedload(models.Workout.cardio_sessions),
|
||||
joinedload(models.Workout.client), # Загружаем клиента, если есть
|
||||
joinedload(models.Workout.workout_type) # Загружаем тип тренировки
|
||||
).filter(
|
||||
models.Workout.owner_id == current_user.id
|
||||
).order_by(models.Workout.start_time.desc()).all()
|
||||
|
||||
# 6. Замеры пользователя
|
||||
body_metrics = db.query(models.BodyMetric).options(
|
||||
joinedload(models.BodyMetric.values),
|
||||
joinedload(models.BodyMetric.client) # Если нужно имя клиента в замерах
|
||||
).filter(
|
||||
models.BodyMetric.owner_id == current_user.id
|
||||
).order_by(models.BodyMetric.metric_date.desc()).all()
|
||||
|
||||
# --- Ручная конвертация в словари, чтобы избежать ошибок Pydantic/SQLAlchemy lazy-loading ---
|
||||
|
||||
def serialize_workout(w):
|
||||
wt_name = w.workout_type.name if w.workout_type else ""
|
||||
client_name = w.client.full_name if w.client else None
|
||||
|
||||
return {
|
||||
"id": w.id,
|
||||
"sync_id": w.sync_id,
|
||||
"owner_id": w.owner_id,
|
||||
"client_id": w.client_id,
|
||||
"workout_type_id": w.workout_type_id,
|
||||
"start_time": w.start_time,
|
||||
"end_time": w.end_time,
|
||||
"notes": w.notes,
|
||||
"synced": w.synced,
|
||||
"created_at": w.created_at,
|
||||
"updated_at": w.updated_at,
|
||||
# Дополнительные поля для фронта
|
||||
"workout_type_name": wt_name,
|
||||
"client_full_name": client_name,
|
||||
|
||||
"workout_exercises": [
|
||||
{
|
||||
"id": ex.id,
|
||||
"sync_id": ex.sync_id,
|
||||
"exercise_name": ex.exercise_name,
|
||||
"sort_order": ex.sort_order,
|
||||
"sets": [
|
||||
{
|
||||
"id": s.id,
|
||||
"sync_id": s.sync_id,
|
||||
"is_dropset": s.is_dropset,
|
||||
"weight": s.weight,
|
||||
"reps": s.reps,
|
||||
"rating": s.rating,
|
||||
"notes": s.notes,
|
||||
"timestamp": s.timestamp,
|
||||
"dropset_items": [
|
||||
{
|
||||
"id": di.id,
|
||||
"weight": di.weight,
|
||||
"reps": di.reps,
|
||||
"sort_order": di.sort_order
|
||||
} for di in (s.dropset_items or [])
|
||||
]
|
||||
} for s in (ex.sets or [])
|
||||
]
|
||||
} for ex in (w.workout_exercises or [])
|
||||
],
|
||||
"cardio_sessions": [
|
||||
{
|
||||
"id": c.id,
|
||||
"sync_id": c.sync_id,
|
||||
"cardio_type": c.cardio_type,
|
||||
"purpose": c.purpose,
|
||||
"duration": c.duration,
|
||||
"distance": c.distance,
|
||||
"speed": c.speed,
|
||||
"incline": c.incline,
|
||||
"resistance": c.resistance,
|
||||
"notes": c.notes,
|
||||
"sort_order": c.sort_order
|
||||
} for c in (w.cardio_sessions or [])
|
||||
]
|
||||
}
|
||||
|
||||
def serialize_metric(m):
|
||||
return {
|
||||
"id": m.id,
|
||||
"sync_id": m.sync_id,
|
||||
"client_id": m.client_id,
|
||||
"metric_date": m.metric_date,
|
||||
"notes": m.notes,
|
||||
"values": [
|
||||
{
|
||||
"id": v.id,
|
||||
"metric_type_id": v.metric_type_id,
|
||||
"value": v.value
|
||||
} for v in (m.values or [])
|
||||
]
|
||||
}
|
||||
|
||||
return {
|
||||
"workout_types": [{"id": t.id, "sync_id": t.sync_id, "name": t.name, "sort_order": t.sort_order} for t in workout_types],
|
||||
"metric_types": [{"id": t.id, "sync_id": t.sync_id, "name": t.name, "unit": t.unit, "category": t.category, "sort_order": t.sort_order} for t in metric_types],
|
||||
"clients": [{"id": c.id, "sync_id": c.sync_id, "full_name": c.full_name, "birth_date": c.birth_date, "goal": c.goal, "color": c.color} for c in clients],
|
||||
"exercises": [{"id": e.id, "sync_id": e.sync_id, "name": e.name, "workout_type_id": e.workout_type_id} for e in exercises],
|
||||
"workouts": [serialize_workout(w) for w in workouts],
|
||||
"body_metrics": [serialize_metric(m) for m in body_metrics],
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ CRITICAL ERROR IN BOOTSTRAP: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
+94
-84
@@ -168,26 +168,21 @@ def upsert_exercise(
|
||||
return obj, "created"
|
||||
|
||||
|
||||
def resolve_client_id_from_sync_id(
|
||||
db: Session,
|
||||
user: models.User,
|
||||
client_sync_id: Optional[str],
|
||||
client_map: Dict[str, int],
|
||||
) -> Optional[int]:
|
||||
def resolve_client_id_from_sync_id(db, user, client_sync_id, client_map):
|
||||
"""Ищет client_id по sync_id."""
|
||||
if not client_sync_id:
|
||||
return None
|
||||
|
||||
# 1. Проверяем кэш карты клиентов (клиенты, созданные в этом же запросе sync)
|
||||
if client_sync_id in client_map:
|
||||
return client_map[client_sync_id]
|
||||
|
||||
client = (
|
||||
db.query(models.Client)
|
||||
.filter(
|
||||
models.Client.sync_id == client_sync_id,
|
||||
models.Client.owner_id == user.id,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
# 2. Ищем в БД среди клиентов пользователя
|
||||
client = db.query(models.Client).filter(
|
||||
models.Client.sync_id == client_sync_id,
|
||||
models.Client.owner_id == user.id
|
||||
).first()
|
||||
|
||||
return client.id if client else None
|
||||
|
||||
|
||||
@@ -289,19 +284,15 @@ def create_cardio_from_payload(
|
||||
return db_cardio
|
||||
|
||||
|
||||
def resolve_metric_type_for_sync(
|
||||
db: Session,
|
||||
value: schemas.BodyMetricValueCreate,
|
||||
) -> Optional[models.MetricType]:
|
||||
if value.metric_type_id:
|
||||
return db.get(models.MetricType, value.metric_type_id)
|
||||
def resolve_metric_type_for_sync(db, value_data):
|
||||
"""Находит объект MetricType по ID или sync_id."""
|
||||
if value_data.metric_type_id:
|
||||
return db.get(models.MetricType, value_data.metric_type_id)
|
||||
|
||||
if value.metric_type_sync_id:
|
||||
return (
|
||||
db.query(models.MetricType)
|
||||
.filter(models.MetricType.sync_id == value.metric_type_sync_id)
|
||||
.first()
|
||||
)
|
||||
if value_data.metric_type_sync_id:
|
||||
return db.query(models.MetricType).filter(
|
||||
models.MetricType.sync_id == value_data.metric_type_sync_id
|
||||
).first()
|
||||
|
||||
return None
|
||||
|
||||
@@ -449,21 +440,25 @@ def sync_data(
|
||||
for metric_data in payload.body_metrics or []:
|
||||
sync_id = metric_data.sync_id or new_sync_id()
|
||||
|
||||
# Попытка найти существующую запись
|
||||
existing = db.query(models.BodyMetric).filter(models.BodyMetric.sync_id == sync_id).first()
|
||||
|
||||
if existing:
|
||||
# --- ОБНОВЛЕНИЕ СУЩЕСТВУЮЩЕГО ЗАМЕРА ---
|
||||
if existing.owner_id != current_user.id:
|
||||
raise HTTPException(status_code=409, detail="BodyMetric sync_id belongs to another user")
|
||||
|
||||
# Обновляем основные поля
|
||||
existing.metric_date = metric_data.metric_date
|
||||
existing.notes = metric_data.notes or ""
|
||||
|
||||
# Резолвим client_id (приоритет у sync_id, затем числовой id)
|
||||
client_id = resolve_client_id_from_sync_id(
|
||||
db,
|
||||
current_user,
|
||||
metric_data.client_sync_id,
|
||||
client_map,
|
||||
db, current_user, metric_data.client_sync_id, client_map
|
||||
)
|
||||
if metric_data.client_id and not client_id:
|
||||
|
||||
# Если client_id не найден по sync_id, пробуем по числовому ID из payload
|
||||
if not client_id and metric_data.client_id:
|
||||
client = (
|
||||
db.query(models.Client)
|
||||
.filter(
|
||||
@@ -472,75 +467,90 @@ def sync_data(
|
||||
)
|
||||
.first()
|
||||
)
|
||||
client_id = client.id if client else None
|
||||
if client:
|
||||
client_id = client.id
|
||||
|
||||
existing.client_id = client_id
|
||||
|
||||
# Удаляем старые значения перед добавлением новых
|
||||
db.query(models.BodyMetricValue).filter(
|
||||
models.BodyMetricValue.body_metric_id == existing.id
|
||||
).delete()
|
||||
).delete(synchronize_session=False)
|
||||
|
||||
# Добавляем новые значения
|
||||
for value_data in metric_data.values or []:
|
||||
mt = resolve_metric_type_for_sync(db, value_data)
|
||||
if not mt:
|
||||
warnings.append("Body metric value skipped: metric type not found")
|
||||
continue
|
||||
try:
|
||||
mt = resolve_metric_type_for_sync(db, value_data)
|
||||
if not mt:
|
||||
warnings.append(f"BodyMetric {sync_id}: Metric type not found for value {value_data.value}")
|
||||
continue
|
||||
|
||||
db.add(
|
||||
models.BodyMetricValue(
|
||||
body_metric_id=existing.id,
|
||||
metric_type_id=mt.id,
|
||||
value=float(value_data.value),
|
||||
db.add(
|
||||
models.BodyMetricValue(
|
||||
body_metric_id=existing.id,
|
||||
metric_type_id=mt.id,
|
||||
value=float(value_data.value),
|
||||
)
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
warnings.append(f"BodyMetric {sync_id}: Error adding value - {str(e)}")
|
||||
|
||||
updated["body_metrics"] += 1
|
||||
continue
|
||||
|
||||
client_id = resolve_client_id_from_sync_id(
|
||||
db,
|
||||
current_user,
|
||||
metric_data.client_sync_id,
|
||||
client_map,
|
||||
)
|
||||
if metric_data.client_id and not client_id:
|
||||
client = (
|
||||
db.query(models.Client)
|
||||
.filter(
|
||||
models.Client.id == metric_data.client_id,
|
||||
models.Client.owner_id == current_user.id,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
client_id = client.id if client else None
|
||||
else:
|
||||
# --- СОЗДАНИЕ НОВОГО ЗАМЕРА ---
|
||||
|
||||
db_metric = models.BodyMetric(
|
||||
sync_id=sync_id,
|
||||
owner_id=current_user.id,
|
||||
client_id=client_id,
|
||||
metric_date=metric_data.metric_date,
|
||||
notes=metric_data.notes or "",
|
||||
created_at=timestamp,
|
||||
)
|
||||
|
||||
db.add(db_metric)
|
||||
db.flush()
|
||||
created["body_metrics"] += 1
|
||||
|
||||
for value_data in metric_data.values or []:
|
||||
mt = resolve_metric_type_for_sync(db, value_data)
|
||||
if not mt:
|
||||
warnings.append("Body metric value skipped: metric type not found")
|
||||
continue
|
||||
|
||||
db.add(
|
||||
models.BodyMetricValue(
|
||||
body_metric_id=db_metric.id,
|
||||
metric_type_id=mt.id,
|
||||
value=float(value_data.value),
|
||||
)
|
||||
# Резолвим client_id
|
||||
client_id = resolve_client_id_from_sync_id(
|
||||
db, current_user, metric_data.client_sync_id, client_map
|
||||
)
|
||||
|
||||
# Fallback на числовой ID, если sync_id не сработал
|
||||
if not client_id and metric_data.client_id:
|
||||
client = (
|
||||
db.query(models.Client)
|
||||
.filter(
|
||||
models.Client.id == metric_data.client_id,
|
||||
models.Client.owner_id == current_user.id,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if client:
|
||||
client_id = client.id
|
||||
|
||||
# Создаем запись метрики
|
||||
db_metric = models.BodyMetric(
|
||||
sync_id=sync_id,
|
||||
owner_id=current_user.id,
|
||||
client_id=client_id,
|
||||
metric_date=metric_data.metric_date,
|
||||
notes=metric_data.notes or "",
|
||||
created_at=timestamp,
|
||||
)
|
||||
|
||||
db.add(db_metric)
|
||||
db.flush() # Получаем ID для связи со значениями
|
||||
|
||||
created["body_metrics"] += 1
|
||||
|
||||
# Добавляем значения
|
||||
for value_data in metric_data.values or []:
|
||||
try:
|
||||
mt = resolve_metric_type_for_sync(db, value_data)
|
||||
if not mt:
|
||||
warnings.append(f"New BodyMetric {sync_id}: Metric type not found for value {value_data.value}")
|
||||
continue
|
||||
|
||||
db.add(
|
||||
models.BodyMetricValue(
|
||||
body_metric_id=db_metric.id,
|
||||
metric_type_id=mt.id,
|
||||
value=float(value_data.value),
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
warnings.append(f"New BodyMetric {sync_id}: Error adding value - {str(e)}")
|
||||
db.commit()
|
||||
|
||||
return schemas.SyncResponse(
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional, List, Dict, Any
|
||||
|
||||
|
||||
# ============================================================
|
||||
# AUTH / USERS
|
||||
# ============================================================
|
||||
|
||||
Reference in New Issue
Block a user