fix(sync): состав сетов ездит на сервер — колонка set_groups, upsert, bootstrap; счётчик синка считает и обновления

This commit is contained in:
Иван Овчинников
2026-11-22 00:53:32 +03:00
parent d7b9d0fa2d
commit b72f5f8e36
6 changed files with 83 additions and 1 deletions
+14
View File
@@ -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) 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( app = FastAPI(
title="Gym Bro API", title="Gym Bro API",
description="API для трекера тренировок с офлайн-синхронизацией и авторизацией", description="API для трекера тренировок с офлайн-синхронизацией и авторизацией",
+3
View File
@@ -95,6 +95,9 @@ class Workout(Base):
start_time = Column(String, nullable=False) start_time = Column(String, nullable=False)
end_time = Column(String) end_time = Column(String)
notes = Column(String, default="") notes = Column(String, default="")
# Состав сетов (JSON: [{"sync_id","name","exercise_sync_ids":[...]}]) —
# плоским полем, т.к. структура целиком принадлежит клиенту
set_groups = Column(String, default="[]")
synced = Column(Integer, default=0) synced = Column(Integer, default=0)
created_at = Column(String) created_at = Column(String)
+9
View File
@@ -1,5 +1,7 @@
# backend/routers/bootstrap.py # backend/routers/bootstrap.py
import json
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session, joinedload from sqlalchemy.orm import Session, joinedload
from sqlalchemy import or_ from sqlalchemy import or_
@@ -65,6 +67,12 @@ def get_bootstrap_data(
def serialize_workout(w): def serialize_workout(w):
wt_name = w.workout_type.name if w.workout_type else "" wt_name = w.workout_type.name if w.workout_type else ""
client_name = w.client.full_name if w.client else None 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 { return {
"id": w.id, "id": w.id,
@@ -75,6 +83,7 @@ def get_bootstrap_data(
"start_time": w.start_time, "start_time": w.start_time,
"end_time": w.end_time, "end_time": w.end_time,
"notes": w.notes, "notes": w.notes,
"set_groups": set_groups,
"synced": w.synced, "synced": w.synced,
"created_at": w.created_at, "created_at": w.created_at,
"updated_at": w.updated_at, "updated_at": w.updated_at,
+8
View File
@@ -1,3 +1,4 @@
import json
import uuid import uuid
from datetime import datetime from datetime import datetime
from typing import Dict, Optional, Tuple 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.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.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.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.synced = 1
existing.updated_at = timestamp existing.updated_at = timestamp
@@ -398,6 +403,9 @@ def sync_data(
start_time=workout_data.start_time, start_time=workout_data.start_time,
end_time=workout_data.end_time, end_time=workout_data.end_time,
notes=workout_data.notes or "", 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, synced=1,
created_at=timestamp, created_at=timestamp,
updated_at=timestamp, updated_at=timestamp,
+7
View File
@@ -252,10 +252,17 @@ class WorkoutBase(BaseModel):
workout_type_id: Optional[int] = None 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): class WorkoutCreate(WorkoutBase):
sync_id: Optional[str] = None sync_id: Optional[str] = None
client_id: Optional[int] = None client_id: Optional[int] = None
client_sync_id: Optional[str] = None client_sync_id: Optional[str] = None
set_groups: Optional[List[SetGroupData]] = None
workout_exercises: List[WorkoutExerciseCreate] = Field(default_factory=list) workout_exercises: List[WorkoutExerciseCreate] = Field(default_factory=list)
cardio_sessions: List[CardioCreate] = Field(default_factory=list) cardio_sessions: List[CardioCreate] = Field(default_factory=list)
+42 -1
View File
@@ -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) { function convertBackendWorkout(w, workoutTypeNameById) {
const workoutSyncId = w.sync_id || generateUUID(); const workoutSyncId = w.sync_id || generateUUID();
@@ -278,6 +303,7 @@ function convertBackendWorkout(w, workoutTypeNameById) {
: "", : "",
notes: w.notes || "", notes: w.notes || "",
synced: true, synced: true,
setGroups: serverSetGroupsToLocal(w),
exercises: (w.workout_exercises || []).map((ex) => { exercises: (w.workout_exercises || []).map((ex) => {
const exSyncId = ex.sync_id || generateUUID(); const exSyncId = ex.sync_id || generateUUID();
@@ -723,6 +749,18 @@ function buildWorkoutsPayload(dirty) {
end_time: w.endTime || null, end_time: w.endTime || null,
notes: w.notes || "", 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), workout_exercises: buildWorkoutExercisesPayload(w.exercises),
cardio_sessions: buildCardioPayload(w.cardio), cardio_sessions: buildCardioPayload(w.cardio),
}; };
@@ -775,9 +813,12 @@ export async function sync() {
} }
const createdW = response.created?.workouts || 0; const createdW = response.created?.workouts || 0;
const updatedW = response.updated?.workouts || 0;
const createdM = response.created?.body_metrics || 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) { if (response.warnings?.length) {
message += `\n\nПредупреждения:\n${response.warnings.join("\n")}`; message += `\n\nПредупреждения:\n${response.warnings.join("\n")}`;