lots of work done, dashboards added
This commit is contained in:
@@ -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))
|
||||
Reference in New Issue
Block a user