From b72f5f8e3603761c8faac702c94722317085fd2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=B2=D0=B0=D0=BD=20=D0=9E=D0=B2=D1=87=D0=B8=D0=BD?= =?UTF-8?q?=D0=BD=D0=B8=D0=BA=D0=BE=D0=B2?= Date: Sun, 22 Nov 2026 00:53:32 +0300 Subject: [PATCH] =?UTF-8?q?fix(sync):=20=D1=81=D0=BE=D1=81=D1=82=D0=B0?= =?UTF-8?q?=D0=B2=20=D1=81=D0=B5=D1=82=D0=BE=D0=B2=20=D0=B5=D0=B7=D0=B4?= =?UTF-8?q?=D0=B8=D1=82=20=D0=BD=D0=B0=20=D1=81=D0=B5=D1=80=D0=B2=D0=B5?= =?UTF-8?q?=D1=80=20=E2=80=94=20=D0=BA=D0=BE=D0=BB=D0=BE=D0=BD=D0=BA=D0=B0?= =?UTF-8?q?=20set=5Fgroups,=20upsert,=20bootstrap;=20=D1=81=D1=87=D1=91?= =?UTF-8?q?=D1=82=D1=87=D0=B8=D0=BA=20=D1=81=D0=B8=D0=BD=D0=BA=D0=B0=20?= =?UTF-8?q?=D1=81=D1=87=D0=B8=D1=82=D0=B0=D0=B5=D1=82=20=D0=B8=20=D0=BE?= =?UTF-8?q?=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/main.py | 14 ++++++++++++ backend/models.py | 3 +++ backend/routers/bootstrap.py | 9 ++++++++ backend/routers/sync.py | 8 +++++++ backend/schemas.py | 7 ++++++ frontend/js/sync.js | 43 +++++++++++++++++++++++++++++++++++- 6 files changed, 83 insertions(+), 1 deletion(-) diff --git a/backend/main.py b/backend/main.py index bb8f783..59e4f17 100644 --- a/backend/main.py +++ b/backend/main.py @@ -24,6 +24,20 @@ os.makedirs(os.path.dirname(os.getenv("GYM_DB_PATH", "./gym.db")), exist_ok=True Base.metadata.create_all(bind=engine) +# Лёгкая миграция: create_all не трогает уже существующие таблицы, а колонки, +# добавленные после релиза, заводить надо (SQLite, без alembic) +def _ensure_columns(): + from sqlalchemy import inspect, text + insp = inspect(engine) + if "workouts" not in insp.get_table_names(): + return + cols = {c["name"] for c in insp.get_columns("workouts")} + if "set_groups" not in cols: + with engine.begin() as conn: + conn.execute(text("ALTER TABLE workouts ADD COLUMN set_groups TEXT DEFAULT '[]'")) + +_ensure_columns() + app = FastAPI( title="Gym Bro API", description="API для трекера тренировок с офлайн-синхронизацией и авторизацией", diff --git a/backend/models.py b/backend/models.py index d98f368..abb7ab0 100644 --- a/backend/models.py +++ b/backend/models.py @@ -95,6 +95,9 @@ class Workout(Base): start_time = Column(String, nullable=False) end_time = Column(String) notes = Column(String, default="") + # Состав сетов (JSON: [{"sync_id","name","exercise_sync_ids":[...]}]) — + # плоским полем, т.к. структура целиком принадлежит клиенту + set_groups = Column(String, default="[]") synced = Column(Integer, default=0) created_at = Column(String) diff --git a/backend/routers/bootstrap.py b/backend/routers/bootstrap.py index 0dc7778..31a022c 100644 --- a/backend/routers/bootstrap.py +++ b/backend/routers/bootstrap.py @@ -1,5 +1,7 @@ # backend/routers/bootstrap.py +import json + from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session, joinedload from sqlalchemy import or_ @@ -65,6 +67,12 @@ def get_bootstrap_data( 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 + try: + set_groups = json.loads(w.set_groups or "[]") + if not isinstance(set_groups, list): + set_groups = [] + except Exception: + set_groups = [] return { "id": w.id, @@ -75,6 +83,7 @@ def get_bootstrap_data( "start_time": w.start_time, "end_time": w.end_time, "notes": w.notes, + "set_groups": set_groups, "synced": w.synced, "created_at": w.created_at, "updated_at": w.updated_at, diff --git a/backend/routers/sync.py b/backend/routers/sync.py index 4b67e44..808bb64 100644 --- a/backend/routers/sync.py +++ b/backend/routers/sync.py @@ -1,3 +1,4 @@ +import json import uuid from datetime import datetime from typing import Dict, Optional, Tuple @@ -361,6 +362,10 @@ def sync_data( 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) + if workout_data.set_groups is not None: + existing.set_groups = json.dumps( + [g.model_dump() for g in workout_data.set_groups], ensure_ascii=False + ) existing.synced = 1 existing.updated_at = timestamp @@ -398,6 +403,9 @@ def sync_data( start_time=workout_data.start_time, end_time=workout_data.end_time, notes=workout_data.notes or "", + set_groups=json.dumps( + [g.model_dump() for g in workout_data.set_groups or []], ensure_ascii=False + ), synced=1, created_at=timestamp, updated_at=timestamp, diff --git a/backend/schemas.py b/backend/schemas.py index fb708c7..38c99b9 100644 --- a/backend/schemas.py +++ b/backend/schemas.py @@ -252,10 +252,17 @@ class WorkoutBase(BaseModel): workout_type_id: Optional[int] = None +class SetGroupData(BaseModel): + sync_id: Optional[str] = None + name: str = "Сет" + exercise_sync_ids: List[str] = Field(default_factory=list) + + class WorkoutCreate(WorkoutBase): sync_id: Optional[str] = None client_id: Optional[int] = None client_sync_id: Optional[str] = None + set_groups: Optional[List[SetGroupData]] = None workout_exercises: List[WorkoutExerciseCreate] = Field(default_factory=list) cardio_sessions: List[CardioCreate] = Field(default_factory=list) diff --git a/frontend/js/sync.js b/frontend/js/sync.js index b28e9a4..8c8c829 100644 --- a/frontend/js/sync.js +++ b/frontend/js/sync.js @@ -263,6 +263,31 @@ function convertBackendWorkoutToFrontend(w) { }; } +/** + * Серверный состав сетов → локальные setGroups. Участники приходят как + * sync_id упражнений тренировки; локальные id конвертируются из тех же + * sync_id, поэтому ссылка восстанавливается по месту. + */ +function serverSetGroupsToLocal(w) { + let sg = w.set_groups || []; + if (typeof sg === "string") { + try { sg = JSON.parse(sg); } catch { sg = []; } + } + if (!Array.isArray(sg)) return []; + + const known = new Set( + (w.workout_exercises || []).map((ex) => ex.sync_id).filter(Boolean) + ); + + return sg + .map((g) => ({ + id: g.sync_id || generateUUID(), + name: g.name || "Сет", + exerciseIds: (g.exercise_sync_ids || []).filter((sid) => known.has(sid)), + })) + .filter((g) => g.exerciseIds.length >= 2); +} + function convertBackendWorkout(w, workoutTypeNameById) { const workoutSyncId = w.sync_id || generateUUID(); @@ -278,6 +303,7 @@ function convertBackendWorkout(w, workoutTypeNameById) { : "", notes: w.notes || "", synced: true, + setGroups: serverSetGroupsToLocal(w), exercises: (w.workout_exercises || []).map((ex) => { const exSyncId = ex.sync_id || generateUUID(); @@ -723,6 +749,18 @@ function buildWorkoutsPayload(dirty) { end_time: w.endTime || null, notes: w.notes || "", + // Состав сетов: участники ссылками на sync_id упражнений этой тренировки + set_groups: (w.setGroups || []).map((g) => ({ + sync_id: g.id || null, + name: g.name || "Сет", + exercise_sync_ids: (g.exerciseIds || []) + .map((id) => { + const ex = (w.exercises || []).find((e) => e.id === id); + return ex ? ensureSyncId(ex) : null; + }) + .filter(Boolean), + })), + workout_exercises: buildWorkoutExercisesPayload(w.exercises), cardio_sessions: buildCardioPayload(w.cardio), }; @@ -775,9 +813,12 @@ export async function sync() { } const createdW = response.created?.workouts || 0; + const updatedW = response.updated?.workouts || 0; const createdM = response.created?.body_metrics || 0; - let message = `Синхронизировано:\nТренировок: ${createdW}\nЗамеров: ${createdM}`; + let message = `Синхронизировано:\nТренировок: ${createdW + updatedW}` + + (updatedW ? ` (новых ${createdW}, обновлено ${updatedW})` : "") + + `\nЗамеров: ${createdM}`; if (response.warnings?.length) { message += `\n\nПредупреждения:\n${response.warnings.join("\n")}`;