merge: iovi/master (дашборды и авторизация с прода) + портированные фичи
Конфликты: app/state/sync/settings — наша версия (= файлы прода + группы вариантов, синхронизация всех тренировок, рейтинг по умолчанию 5, нормализация состояния); backend/auth.py — его боевая версия.
This commit is contained in:
+10
-3
@@ -1,4 +1,7 @@
|
|||||||
import os
|
import os
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
import bcrypt
|
import bcrypt
|
||||||
import jwt
|
import jwt
|
||||||
from jwt.exceptions import PyJWTError
|
from jwt.exceptions import PyJWTError
|
||||||
@@ -7,10 +10,10 @@ from fastapi import Depends, HTTPException, status
|
|||||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
|
||||||
import database
|
import database
|
||||||
import models
|
import models
|
||||||
|
|
||||||
|
|
||||||
SECRET = os.getenv("GYM_JWT_SECRET", "dev-secret-change-me")
|
SECRET = os.getenv("GYM_JWT_SECRET", "dev-secret-change-me")
|
||||||
ALGORITHM = "HS256"
|
ALGORITHM = "HS256"
|
||||||
EXPIRE_DAYS = int(os.getenv("GYM_JWT_EXPIRE_DAYS", "30"))
|
EXPIRE_DAYS = int(os.getenv("GYM_JWT_EXPIRE_DAYS", "30"))
|
||||||
@@ -19,12 +22,16 @@ bearer_scheme = HTTPBearer(auto_error=False)
|
|||||||
|
|
||||||
|
|
||||||
def hash_password(password: str) -> str:
|
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:
|
def verify_password(password: str, hashed: str) -> bool:
|
||||||
try:
|
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:
|
except ValueError:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|||||||
+7
-1
@@ -3,9 +3,10 @@
|
|||||||
import os
|
import os
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
from database import engine, Base
|
from database import engine, Base
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import routers.bootstrap
|
||||||
import routers.auth
|
import routers.auth
|
||||||
import routers.clients
|
import routers.clients
|
||||||
import routers.workout_types
|
import routers.workout_types
|
||||||
@@ -14,6 +15,10 @@ import routers.exercises
|
|||||||
import routers.metrics
|
import routers.metrics
|
||||||
import routers.sync
|
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)
|
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.exercises.router)
|
||||||
app.include_router(routers.metrics.router)
|
app.include_router(routers.metrics.router)
|
||||||
app.include_router(routers.sync.router)
|
app.include_router(routers.sync.router)
|
||||||
|
app.include_router(routers.bootstrap.router)
|
||||||
|
|
||||||
|
|
||||||
@app.get("/")
|
@app.get("/")
|
||||||
|
|||||||
+10
-12
@@ -11,7 +11,6 @@ from sqlalchemy.orm import relationship
|
|||||||
|
|
||||||
from database import Base
|
from database import Base
|
||||||
|
|
||||||
|
|
||||||
class User(Base):
|
class User(Base):
|
||||||
__tablename__ = "users"
|
__tablename__ = "users"
|
||||||
|
|
||||||
@@ -19,7 +18,7 @@ class User(Base):
|
|||||||
username = Column(String, unique=True, nullable=False, index=True)
|
username = Column(String, unique=True, nullable=False, index=True)
|
||||||
password_hash = Column(String, nullable=False)
|
password_hash = Column(String, nullable=False)
|
||||||
display_name = Column(String, default="")
|
display_name = Column(String, default="")
|
||||||
role = Column(String, default="personal") # personal | trainer
|
role = Column(String, default="personal")
|
||||||
created_at = Column(String)
|
created_at = Column(String)
|
||||||
|
|
||||||
|
|
||||||
@@ -32,7 +31,10 @@ class WorkoutType(Base):
|
|||||||
sort_order = Column(Integer, default=0)
|
sort_order = Column(Integer, default=0)
|
||||||
created_at = Column(String)
|
created_at = Column(String)
|
||||||
|
|
||||||
|
# ВАЖНО: Эта строка должна быть здесь!
|
||||||
exercises = relationship("Exercise", back_populates="workout_type")
|
exercises = relationship("Exercise", back_populates="workout_type")
|
||||||
|
|
||||||
|
# Если есть другие отношения, они тоже должны быть прописаны
|
||||||
workouts = relationship("Workout", 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)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
sync_id = Column(String, unique=True, nullable=False, index=True)
|
sync_id = Column(String, unique=True, nullable=False, index=True)
|
||||||
|
|
||||||
# NULL = глобальный справочник, иначе — личное упражнение пользователя
|
|
||||||
owner_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), index=True)
|
owner_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), index=True)
|
||||||
|
workout_type_id = Column(Integer, ForeignKey("workout_types.id", ondelete="SET NULL"), index=True)
|
||||||
workout_type_id = Column(
|
|
||||||
Integer,
|
|
||||||
ForeignKey("workout_types.id", ondelete="SET NULL"),
|
|
||||||
index=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
name = Column(String, nullable=False, index=True)
|
name = Column(String, nullable=False, index=True)
|
||||||
created_at = Column(String)
|
created_at = Column(String)
|
||||||
updated_at = Column(String)
|
updated_at = Column(String)
|
||||||
|
|
||||||
|
# ВАЖНО: И эта строка тоже!
|
||||||
workout_type = relationship("WorkoutType", back_populates="exercises")
|
workout_type = relationship("WorkoutType", back_populates="exercises")
|
||||||
|
|
||||||
workout_exercises = relationship("WorkoutExercise", back_populates="exercise")
|
workout_exercises = relationship("WorkoutExercise", back_populates="exercise")
|
||||||
|
|
||||||
|
|
||||||
@@ -73,7 +71,7 @@ class Client(Base):
|
|||||||
color = Column(String)
|
color = Column(String)
|
||||||
is_active = Column(Integer, default=1)
|
is_active = Column(Integer, default=1)
|
||||||
|
|
||||||
created_at = Column(String)
|
created_at = Column(String, default=lambda: datetime.utcnow().isoformat())
|
||||||
updated_at = Column(String)
|
updated_at = Column(String)
|
||||||
|
|
||||||
workouts = relationship("Workout", back_populates="client")
|
workouts = relationship("Workout", back_populates="client")
|
||||||
@@ -232,7 +230,7 @@ class MetricType(Base):
|
|||||||
unit = Column(String, default="см")
|
unit = Column(String, default="см")
|
||||||
category = Column(String, default="body")
|
category = Column(String, default="body")
|
||||||
sort_order = Column(Integer, default=0)
|
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")
|
metric_values = relationship("BodyMetricValue", back_populates="metric_type")
|
||||||
|
|
||||||
@@ -248,7 +246,7 @@ class BodyMetric(Base):
|
|||||||
|
|
||||||
metric_date = Column(String, nullable=False)
|
metric_date = Column(String, nullable=False)
|
||||||
notes = Column(String, default="")
|
notes = Column(String, default="")
|
||||||
created_at = Column(String)
|
created_at = Column(String, default=lambda: datetime.utcnow().isoformat())
|
||||||
|
|
||||||
client = relationship("Client", back_populates="body_metrics")
|
client = relationship("Client", back_populates="body_metrics")
|
||||||
values = relationship(
|
values = relationship(
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
-i https://mirror.yandex.ru/pypi/simple/
|
fastapi==0.115.6
|
||||||
--trusted-host mirror.yandex.ru
|
uvicorn[standard]==0.32.1
|
||||||
fastapi==0.104.1
|
sqlalchemy==2.0.36
|
||||||
uvicorn[standard]==0.24.0
|
pydantic==2.10.4
|
||||||
sqlalchemy==2.0.23
|
python-multipart==0.0.20
|
||||||
pydantic==2.5.0
|
PyJWT==2.10.1
|
||||||
python-multipart==0.0.6
|
bcrypt==4.2.1
|
||||||
PyJWT==2.8.0
|
|
||||||
bcrypt==4.1.2
|
|
||||||
|
|||||||
@@ -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))
|
||||||
+52
-42
@@ -168,26 +168,21 @@ def upsert_exercise(
|
|||||||
return obj, "created"
|
return obj, "created"
|
||||||
|
|
||||||
|
|
||||||
def resolve_client_id_from_sync_id(
|
def resolve_client_id_from_sync_id(db, user, client_sync_id, client_map):
|
||||||
db: Session,
|
"""Ищет client_id по sync_id."""
|
||||||
user: models.User,
|
|
||||||
client_sync_id: Optional[str],
|
|
||||||
client_map: Dict[str, int],
|
|
||||||
) -> Optional[int]:
|
|
||||||
if not client_sync_id:
|
if not client_sync_id:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
# 1. Проверяем кэш карты клиентов (клиенты, созданные в этом же запросе sync)
|
||||||
if client_sync_id in client_map:
|
if client_sync_id in client_map:
|
||||||
return client_map[client_sync_id]
|
return client_map[client_sync_id]
|
||||||
|
|
||||||
client = (
|
# 2. Ищем в БД среди клиентов пользователя
|
||||||
db.query(models.Client)
|
client = db.query(models.Client).filter(
|
||||||
.filter(
|
|
||||||
models.Client.sync_id == client_sync_id,
|
models.Client.sync_id == client_sync_id,
|
||||||
models.Client.owner_id == user.id,
|
models.Client.owner_id == user.id
|
||||||
)
|
).first()
|
||||||
.first()
|
|
||||||
)
|
|
||||||
return client.id if client else None
|
return client.id if client else None
|
||||||
|
|
||||||
|
|
||||||
@@ -289,19 +284,15 @@ def create_cardio_from_payload(
|
|||||||
return db_cardio
|
return db_cardio
|
||||||
|
|
||||||
|
|
||||||
def resolve_metric_type_for_sync(
|
def resolve_metric_type_for_sync(db, value_data):
|
||||||
db: Session,
|
"""Находит объект MetricType по ID или sync_id."""
|
||||||
value: schemas.BodyMetricValueCreate,
|
if value_data.metric_type_id:
|
||||||
) -> Optional[models.MetricType]:
|
return db.get(models.MetricType, value_data.metric_type_id)
|
||||||
if value.metric_type_id:
|
|
||||||
return db.get(models.MetricType, value.metric_type_id)
|
|
||||||
|
|
||||||
if value.metric_type_sync_id:
|
if value_data.metric_type_sync_id:
|
||||||
return (
|
return db.query(models.MetricType).filter(
|
||||||
db.query(models.MetricType)
|
models.MetricType.sync_id == value_data.metric_type_sync_id
|
||||||
.filter(models.MetricType.sync_id == value.metric_type_sync_id)
|
).first()
|
||||||
.first()
|
|
||||||
)
|
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -449,21 +440,25 @@ def sync_data(
|
|||||||
for metric_data in payload.body_metrics or []:
|
for metric_data in payload.body_metrics or []:
|
||||||
sync_id = metric_data.sync_id or new_sync_id()
|
sync_id = metric_data.sync_id or new_sync_id()
|
||||||
|
|
||||||
|
# Попытка найти существующую запись
|
||||||
existing = db.query(models.BodyMetric).filter(models.BodyMetric.sync_id == sync_id).first()
|
existing = db.query(models.BodyMetric).filter(models.BodyMetric.sync_id == sync_id).first()
|
||||||
|
|
||||||
if existing:
|
if existing:
|
||||||
|
# --- ОБНОВЛЕНИЕ СУЩЕСТВУЮЩЕГО ЗАМЕРА ---
|
||||||
if existing.owner_id != current_user.id:
|
if existing.owner_id != current_user.id:
|
||||||
raise HTTPException(status_code=409, detail="BodyMetric sync_id belongs to another user")
|
raise HTTPException(status_code=409, detail="BodyMetric sync_id belongs to another user")
|
||||||
|
|
||||||
|
# Обновляем основные поля
|
||||||
existing.metric_date = metric_data.metric_date
|
existing.metric_date = metric_data.metric_date
|
||||||
existing.notes = metric_data.notes or ""
|
existing.notes = metric_data.notes or ""
|
||||||
|
|
||||||
|
# Резолвим client_id (приоритет у sync_id, затем числовой id)
|
||||||
client_id = resolve_client_id_from_sync_id(
|
client_id = resolve_client_id_from_sync_id(
|
||||||
db,
|
db, current_user, metric_data.client_sync_id, client_map
|
||||||
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 = (
|
client = (
|
||||||
db.query(models.Client)
|
db.query(models.Client)
|
||||||
.filter(
|
.filter(
|
||||||
@@ -472,18 +467,22 @@ def sync_data(
|
|||||||
)
|
)
|
||||||
.first()
|
.first()
|
||||||
)
|
)
|
||||||
client_id = client.id if client else None
|
if client:
|
||||||
|
client_id = client.id
|
||||||
|
|
||||||
existing.client_id = client_id
|
existing.client_id = client_id
|
||||||
|
|
||||||
|
# Удаляем старые значения перед добавлением новых
|
||||||
db.query(models.BodyMetricValue).filter(
|
db.query(models.BodyMetricValue).filter(
|
||||||
models.BodyMetricValue.body_metric_id == existing.id
|
models.BodyMetricValue.body_metric_id == existing.id
|
||||||
).delete()
|
).delete(synchronize_session=False)
|
||||||
|
|
||||||
|
# Добавляем новые значения
|
||||||
for value_data in metric_data.values or []:
|
for value_data in metric_data.values or []:
|
||||||
|
try:
|
||||||
mt = resolve_metric_type_for_sync(db, value_data)
|
mt = resolve_metric_type_for_sync(db, value_data)
|
||||||
if not mt:
|
if not mt:
|
||||||
warnings.append("Body metric value skipped: metric type not found")
|
warnings.append(f"BodyMetric {sync_id}: Metric type not found for value {value_data.value}")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
db.add(
|
db.add(
|
||||||
@@ -493,17 +492,22 @@ def sync_data(
|
|||||||
value=float(value_data.value),
|
value=float(value_data.value),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
except Exception as e:
|
||||||
|
warnings.append(f"BodyMetric {sync_id}: Error adding value - {str(e)}")
|
||||||
|
|
||||||
updated["body_metrics"] += 1
|
updated["body_metrics"] += 1
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
else:
|
||||||
|
# --- СОЗДАНИЕ НОВОГО ЗАМЕРА ---
|
||||||
|
|
||||||
|
# Резолвим client_id
|
||||||
client_id = resolve_client_id_from_sync_id(
|
client_id = resolve_client_id_from_sync_id(
|
||||||
db,
|
db, current_user, metric_data.client_sync_id, client_map
|
||||||
current_user,
|
|
||||||
metric_data.client_sync_id,
|
|
||||||
client_map,
|
|
||||||
)
|
)
|
||||||
if metric_data.client_id and not client_id:
|
|
||||||
|
# Fallback на числовой ID, если sync_id не сработал
|
||||||
|
if not client_id and metric_data.client_id:
|
||||||
client = (
|
client = (
|
||||||
db.query(models.Client)
|
db.query(models.Client)
|
||||||
.filter(
|
.filter(
|
||||||
@@ -512,8 +516,10 @@ def sync_data(
|
|||||||
)
|
)
|
||||||
.first()
|
.first()
|
||||||
)
|
)
|
||||||
client_id = client.id if client else None
|
if client:
|
||||||
|
client_id = client.id
|
||||||
|
|
||||||
|
# Создаем запись метрики
|
||||||
db_metric = models.BodyMetric(
|
db_metric = models.BodyMetric(
|
||||||
sync_id=sync_id,
|
sync_id=sync_id,
|
||||||
owner_id=current_user.id,
|
owner_id=current_user.id,
|
||||||
@@ -524,13 +530,16 @@ def sync_data(
|
|||||||
)
|
)
|
||||||
|
|
||||||
db.add(db_metric)
|
db.add(db_metric)
|
||||||
db.flush()
|
db.flush() # Получаем ID для связи со значениями
|
||||||
|
|
||||||
created["body_metrics"] += 1
|
created["body_metrics"] += 1
|
||||||
|
|
||||||
|
# Добавляем значения
|
||||||
for value_data in metric_data.values or []:
|
for value_data in metric_data.values or []:
|
||||||
|
try:
|
||||||
mt = resolve_metric_type_for_sync(db, value_data)
|
mt = resolve_metric_type_for_sync(db, value_data)
|
||||||
if not mt:
|
if not mt:
|
||||||
warnings.append("Body metric value skipped: metric type not found")
|
warnings.append(f"New BodyMetric {sync_id}: Metric type not found for value {value_data.value}")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
db.add(
|
db.add(
|
||||||
@@ -540,7 +549,8 @@ def sync_data(
|
|||||||
value=float(value_data.value),
|
value=float(value_data.value),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
except Exception as e:
|
||||||
|
warnings.append(f"New BodyMetric {sync_id}: Error adding value - {str(e)}")
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|
||||||
return schemas.SyncResponse(
|
return schemas.SyncResponse(
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
from typing import Optional, List, Dict, Any
|
from typing import Optional, List, Dict, Any
|
||||||
|
|
||||||
|
|
||||||
# ============================================================
|
# ============================================================
|
||||||
# AUTH / USERS
|
# AUTH / USERS
|
||||||
# ============================================================
|
# ============================================================
|
||||||
|
|||||||
+14
-9
@@ -1,28 +1,33 @@
|
|||||||
version: '3.8'
|
|
||||||
|
|
||||||
services:
|
services:
|
||||||
backend:
|
backend:
|
||||||
build: ./backend
|
build:
|
||||||
|
context: ./backend
|
||||||
|
network: host
|
||||||
container_name: gym-bro-backend
|
container_name: gym-bro-backend
|
||||||
dns:
|
|
||||||
- 8.8.8.8
|
|
||||||
- 1.1.1.1
|
|
||||||
environment:
|
environment:
|
||||||
- GYM_JWT_SECRET=${JWT_SECRET:-super-secret-key-change-in-prod}
|
- GYM_JWT_SECRET=${JWT_SECRET:-super-secret-key-change-in-prod}
|
||||||
- GYM_DB_PATH=/data/gym.db
|
- GYM_DB_PATH=/data/gym.db
|
||||||
volumes:
|
volumes:
|
||||||
- ./data:/data # Монтируем локальную папку ./data в /data контейнера
|
- ./data:/data
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
networks:
|
networks:
|
||||||
- gym-net
|
- gym-net
|
||||||
|
healthcheck:
|
||||||
|
# Используем python вместо curl
|
||||||
|
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 5
|
||||||
|
start_period: 10s # Даём время серверу подняться перед первой проверкой
|
||||||
|
|
||||||
frontend:
|
frontend:
|
||||||
build: ./frontend
|
build: ./frontend
|
||||||
container_name: gym-bro-frontend
|
container_name: gym-bro-frontend
|
||||||
ports:
|
ports:
|
||||||
- "80:80" # Или другой порт, если 80 занят
|
- "80:80"
|
||||||
depends_on:
|
depends_on:
|
||||||
- backend
|
backend:
|
||||||
|
condition: service_healthy
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
networks:
|
networks:
|
||||||
- gym-net
|
- gym-net
|
||||||
|
|||||||
+14
-5
@@ -6,19 +6,28 @@ server {
|
|||||||
location / {
|
location / {
|
||||||
root /usr/share/nginx/html;
|
root /usr/share/nginx/html;
|
||||||
index index.html;
|
index index.html;
|
||||||
try_files $uri $uri/ /index.html; # Для SPA роутинга (если понадобится)
|
try_files $uri $uri/ /index.html;
|
||||||
}
|
}
|
||||||
|
|
||||||
# Проксирование API на бэкенд
|
# Проксирование API на бэкенд
|
||||||
location /api/ {
|
location /api/ {
|
||||||
proxy_pass http://backend:8000/;
|
proxy_pass http://backend:8000/;
|
||||||
|
|
||||||
|
# КРИТИЧЕСКИ ВАЖНЫЕ ЗАГОЛОВКИ ДЛЯ JWT/AUTHORIZATION
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
|
||||||
|
# ЭТА СТРОКА ИСПРАВЛЯЕТ ОШИБКУ 401:
|
||||||
|
proxy_set_header Authorization $http_authorization;
|
||||||
|
|
||||||
|
# Для WebSocket (если понадобится в будущем)
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
proxy_set_header Connection 'upgrade';
|
proxy_set_header Connection "upgrade";
|
||||||
proxy_set_header Host $host;
|
|
||||||
proxy_cache_bypass $http_upgrade;
|
|
||||||
|
|
||||||
# Важно: убираем префикс /api, так как бэк ожидает пути вроде /auth/login
|
# Убираем префикс /api, так как бэк ожидает пути вроде /auth/login
|
||||||
rewrite ^/api/(.*)$ /$1 break;
|
rewrite ^/api/(.*)$ /$1 break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user