Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 232d03eebd | |||
| b19c864bbf | |||
| e3ec434f03 | |||
| 0968e2a86d | |||
| e6cc7eda0a | |||
| ec476f5ce6 | |||
| b72f5f8e36 |
@@ -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 для трекера тренировок с офлайн-синхронизацией и авторизацией",
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Dict, Optional, Tuple
|
||||
@@ -322,6 +323,47 @@ def sync_data(
|
||||
client_map: Dict[str, int] = {}
|
||||
exercise_map: Dict[str, int] = {}
|
||||
|
||||
deleted = {"workouts": 0}
|
||||
|
||||
# ========================================================
|
||||
# 0. Удаления (надгробия с клиента): снимаем тренировки по sync_id
|
||||
# вместе с упражнениями, сетами, дроп-сетами и кардио.
|
||||
# ========================================================
|
||||
for sid in payload.deleted_sync_ids or []:
|
||||
target = (
|
||||
db.query(models.Workout)
|
||||
.filter(
|
||||
models.Workout.sync_id == sid,
|
||||
models.Workout.owner_id == current_user.id,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not target:
|
||||
continue
|
||||
we_ids = [e.id for e in target.workout_exercises]
|
||||
if we_ids:
|
||||
set_ids = [
|
||||
s.id
|
||||
for s in db.query(models.Set)
|
||||
.filter(models.Set.workout_exercise_id.in_(we_ids))
|
||||
.all()
|
||||
]
|
||||
if set_ids:
|
||||
db.query(models.DropsetItem).filter(
|
||||
models.DropsetItem.set_id.in_(set_ids)
|
||||
).delete(synchronize_session=False)
|
||||
db.query(models.Set).filter(
|
||||
models.Set.workout_exercise_id.in_(we_ids)
|
||||
).delete(synchronize_session=False)
|
||||
db.query(models.WorkoutExercise).filter(
|
||||
models.WorkoutExercise.id.in_(we_ids)
|
||||
).delete(synchronize_session=False)
|
||||
db.query(models.Cardio).filter(
|
||||
models.Cardio.workout_id == target.id
|
||||
).delete(synchronize_session=False)
|
||||
db.delete(target)
|
||||
deleted["workouts"] += 1
|
||||
|
||||
# ========================================================
|
||||
# 1. Clients
|
||||
# ========================================================
|
||||
@@ -361,6 +403,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 +444,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,
|
||||
@@ -557,5 +606,6 @@ def sync_data(
|
||||
status="success",
|
||||
created=created,
|
||||
updated=updated,
|
||||
deleted=deleted,
|
||||
warnings=warnings,
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -337,10 +344,13 @@ class SyncPayload(BaseModel):
|
||||
exercises: List[ExerciseCreate] = Field(default_factory=list)
|
||||
workouts: List[WorkoutCreate] = Field(default_factory=list)
|
||||
body_metrics: List[BodyMetricCreate] = Field(default_factory=list)
|
||||
# Удалённые на клиенте тренировки (sync_id) — иначе bootstrap возвращает их обратно
|
||||
deleted_sync_ids: List[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class SyncResponse(BaseModel):
|
||||
status: str
|
||||
created: Dict[str, int]
|
||||
updated: Dict[str, int]
|
||||
deleted: Dict[str, int] = Field(default_factory=dict)
|
||||
warnings: List[str] = Field(default_factory=list)
|
||||
|
||||
@@ -4,10 +4,10 @@
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>График прогрессии (просмотр)</title>
|
||||
<link rel="stylesheet" href="styles/main.css">
|
||||
<link rel="stylesheet" href="styles/components.css">
|
||||
<link rel="stylesheet" href="styles/workout.css">
|
||||
<link rel="stylesheet" href="styles/modal.css">
|
||||
<link rel="stylesheet" href="styles/main.css?v=2">
|
||||
<link rel="stylesheet" href="styles/components.css?v=2">
|
||||
<link rel="stylesheet" href="styles/workout.css?v=2">
|
||||
<link rel="stylesheet" href="styles/modal.css?v=2">
|
||||
<style>
|
||||
.chart-page { max-width: 760px; margin: 0 auto; padding: 16px; }
|
||||
.chart-page h2 { margin: 14px 0 2px; }
|
||||
|
||||
@@ -26,12 +26,29 @@ export function showSettings() {
|
||||
? state.workoutTypes.map(wt => `<option value="${wt.name}">${wt.name}</option>`).join('')
|
||||
: '<option value="">(нет типов)</option>';
|
||||
|
||||
const goal = state.goal === 'endurance' ? 'endurance' : 'strength';
|
||||
|
||||
screen.innerHTML = `
|
||||
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;">
|
||||
<h2>⚙️ Настройки</h2>
|
||||
<button class="btn btn-small btn-secondary" onclick="App.backToMain()">← Назад</button>
|
||||
</div>
|
||||
|
||||
<!-- 0. ЦЕЛЬ ТРЕНИРОВОК -->
|
||||
<div class="card mb-10">
|
||||
<h3>🎯 Цель тренировок</h3>
|
||||
<p class="text-muted text-small mb-10">
|
||||
По цели графики определяют прогресс и откат: «Сила» — по максимальному весу за тренировку,
|
||||
«Выносливость» — по суммарному объёму (вес × повторы).
|
||||
</p>
|
||||
<div style="display:flex; gap:10px;">
|
||||
<button class="btn big-touch ${goal === 'strength' ? 'btn-primary' : 'btn-secondary'}"
|
||||
onclick="SettingsLogic.setGoal('strength')">💪 Сила</button>
|
||||
<button class="btn big-touch ${goal === 'endurance' ? 'btn-primary' : 'btn-secondary'}"
|
||||
onclick="SettingsLogic.setGoal('endurance')">🏃 Выносливость</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- КНОПКА ОБНОВЛЕНИЯ СПРАВОЧНИКОВ -->
|
||||
<div class="card mb-10" style="background: rgba(187, 134, 252, 0.1); border-color: var(--primary);">
|
||||
<div style="display:flex; justify-content:space-between; align-items:center;">
|
||||
@@ -750,6 +767,12 @@ window.SettingsLogic = {
|
||||
show: showSettings,
|
||||
refreshDicts, // <-- ДОБАВИЛИ В ЭКСПОРТ
|
||||
|
||||
setGoal(goal) {
|
||||
state.goal = goal === 'endurance' ? 'endurance' : 'strength';
|
||||
saveState();
|
||||
showSettings();
|
||||
},
|
||||
|
||||
// Metric Types
|
||||
showAddMetricTypeModal,
|
||||
submitMetricType,
|
||||
|
||||
@@ -43,6 +43,15 @@ export function finishWorkout(workoutId) {
|
||||
|
||||
export function deleteWorkout(workoutId) {
|
||||
if (!confirm('Удалить тренировку полностью?')) return;
|
||||
|
||||
// Надгробие: без него bootstrap вернёт удалённую тренировку с сервера
|
||||
const w = state.workouts.find(x => x.id === workoutId);
|
||||
const sid = w && (w.sync_id || w.id);
|
||||
if (sid) {
|
||||
if (!Array.isArray(state.deletedWorkouts)) state.deletedWorkouts = [];
|
||||
if (!state.deletedWorkouts.includes(sid)) state.deletedWorkouts.push(sid);
|
||||
}
|
||||
|
||||
state.workouts = state.workouts.filter(w => w.id !== workoutId);
|
||||
saveState();
|
||||
renderMainScreen();
|
||||
|
||||
@@ -28,14 +28,26 @@ export function showChartDialog(exerciseName, clientId = null) {
|
||||
const dayTop = p => byWeight ? p.maxWeight : Math.max(...p.sets.map(val), 0);
|
||||
const dayTopReps = p => byWeight ? p.topReps : 0;
|
||||
|
||||
// Прогресс вершины относительно предыдущей тренировки
|
||||
// Цель из настроек: «Сила» — по максимальному весу (тот же вес и больше
|
||||
// повторов — тоже прогресс, но суммарный объём не учитывается);
|
||||
// «Выносливость» — по суммарному объёму вес × повторы. По умолчанию — сила.
|
||||
const goal = state.goal === 'endurance' ? 'endurance' : 'strength';
|
||||
const volume = p => p.sets.reduce((a, s) => a + (s.weight || 0) * (s.reps || 0), 0);
|
||||
|
||||
const cls = i => {
|
||||
if (i === 0) return 'chart-flat';
|
||||
if (goal === 'endurance') {
|
||||
const cur = volume(points[i]), prev = volume(points[i - 1]);
|
||||
if (cur > prev) return 'chart-up';
|
||||
if (cur < prev) return 'chart-down';
|
||||
return 'chart-flat';
|
||||
}
|
||||
const cur = dayTop(points[i]), prev = dayTop(points[i - 1]);
|
||||
if (cur > prev) return 'chart-up';
|
||||
if (cur < prev) return 'chart-down';
|
||||
if (byWeight && dayTopReps(points[i]) > dayTopReps(points[i - 1])) return 'chart-up';
|
||||
if (byWeight && dayTopReps(points[i]) < dayTopReps(points[i - 1])) return 'chart-down';
|
||||
// Тот же максимальный вес: больше повторов — лучше, меньше — хуже
|
||||
if (dayTopReps(points[i]) > dayTopReps(points[i - 1])) return 'chart-up';
|
||||
if (dayTopReps(points[i]) < dayTopReps(points[i - 1])) return 'chart-down';
|
||||
return 'chart-flat';
|
||||
};
|
||||
const classes = points.map((_, i) => cls(i));
|
||||
@@ -98,7 +110,18 @@ export function showChartDialog(exerciseName, clientId = null) {
|
||||
|
||||
showModal(`
|
||||
<div class="modal-content modal-fullscreen">
|
||||
<div class="modal-header"><span class="modal-title">📈 ${escapeHtml(exerciseName)}</span><button class="btn-icon" onclick="closeModal()">✕</button></div>
|
||||
<div class="modal-header"><span class="modal-title">📈 ${escapeHtml(exerciseName)}</span></div>
|
||||
<div class="chart-legend-big">
|
||||
<span class="lg-line">— линия: максимум</span>
|
||||
<span class="lg-up">зелёный: прогресс</span>
|
||||
<span class="lg-down">красный: откат</span>
|
||||
<button class="lg-info" onclick="CM.toggleChartHint(this)">ⓘ</button>
|
||||
</div>
|
||||
<div class="chart-hint" style="display:none">${
|
||||
goal === 'endurance'
|
||||
? 'Прогресс и откат считаются по <b>суммарному объёму</b> (вес × повторы за тренировку). Цель: «🏃 Выносливость» — сменить на «💪 Сила» можно в ⚙️ Настройках. Тусклые точки — остальные подходы, ×N под датой — их число.'
|
||||
: 'Прогресс — <b>максимальный вес</b> за тренировку вырос (или тот же вес и больше повторов), откат — упал. Суммарный объём за тренировку не учитывается. Цель: «💪 Сила» — сменить на «🏃 Выносливость» можно в ⚙️ Настройках. Тусклые точки — остальные подходы, ×N под датой — их число.'
|
||||
}</div>
|
||||
<svg class="chart-svg" viewBox="0 0 ${W} ${H}">
|
||||
<line x1="${padL}" y1="${y(vMin).toFixed(1)}" x2="${W - padR}" y2="${y(vMin).toFixed(1)}" class="chart-axis"/>
|
||||
<line x1="${padL}" y1="${y(vMax).toFixed(1)}" x2="${W - padR}" y2="${y(vMax).toFixed(1)}" class="chart-axis"/>
|
||||
@@ -109,7 +132,6 @@ export function showChartDialog(exerciseName, clientId = null) {
|
||||
${verts}
|
||||
${counts}
|
||||
</svg>
|
||||
<div class="chart-sub chart-legend-bottom">линия — рабочий максимум «вес × повторы»: <b class="chart-up">зелёный — прогресс</b> (вес выше или тот же вес и больше повторов), <b class="chart-down">красный — откат</b>; тусклые точки — остальные подходы, ×N — их число</div>
|
||||
<div class="chart-list">${points.slice(-5).reverse().map((p, k) => {
|
||||
const i = points.length - 1 - k;
|
||||
return `<div class="chart-row"><span class="chart-date">${new Date(p.date).toLocaleDateString('ru-RU')}</span>` +
|
||||
@@ -117,14 +139,21 @@ export function showChartDialog(exerciseName, clientId = null) {
|
||||
`<span class="chart-sets">${p.sets.map(s => byWeight ? s.weight + '×' + s.reps : s.reps).join(' ')}` +
|
||||
` · <span class="chart-count-num">${p.sets.length}</span> подх.</span></div>`;
|
||||
}).join('')}</div>
|
||||
<div style="display:flex; gap:8px; margin-top:10px">
|
||||
<button class="btn btn-small btn-secondary" data-ex="${escapeHtml(exerciseName)}"
|
||||
onclick="EM.showSummaryFromBtn(this)">📋 Сводка по упражнению</button>
|
||||
<div class="modal-actions-row">
|
||||
<button class="btn btn-secondary big-touch" data-ex="${escapeHtml(exerciseName)}"
|
||||
onclick="EM.showSummaryFromBtn(this)">📋 Сводка</button>
|
||||
<button class="btn btn-primary big-touch" onclick="ModalBase.closeModal()">✕ Закрыть</button>
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
}
|
||||
|
||||
// Пояснение к легенде — по тапу на ⓘ (на телефоне наведение не работает)
|
||||
export function toggleChartHint(btn) {
|
||||
const hint = btn.closest('.chart-legend-big')?.nextElementSibling;
|
||||
if (hint) hint.style.display = hint.style.display === 'none' ? 'block' : 'none';
|
||||
}
|
||||
|
||||
// Клик с кнопки в карточке: имя берём из data-атрибута (без экранирования в JS-строке)
|
||||
export function showChartFromBtn(btn) {
|
||||
const name = btn.dataset.ex;
|
||||
@@ -132,4 +161,4 @@ export function showChartFromBtn(btn) {
|
||||
showChartDialog(name, w ? w.client_id : null);
|
||||
}
|
||||
|
||||
window.CM = { showChartDialog, showChartFromBtn };
|
||||
window.CM = { showChartDialog, showChartFromBtn, toggleChartHint };
|
||||
|
||||
@@ -34,10 +34,9 @@ export function showExerciseSummary(exerciseName, clientId = null) {
|
||||
).join('') || '<div class="history-hint">Пока нет данных по соседним упражнениям.</div>';
|
||||
|
||||
showModal(`
|
||||
<div class="modal-content">
|
||||
<div class="modal-content modal-fullscreen">
|
||||
<div class="modal-header">
|
||||
<span class="modal-title">📋 ${escapeHtml(exerciseName)}</span>
|
||||
<button class="btn-icon" onclick="closeModal()">✕</button>
|
||||
</div>
|
||||
<div class="chart-sub">
|
||||
${s.days} тренир.` +
|
||||
@@ -61,9 +60,10 @@ export function showExerciseSummary(exerciseName, clientId = null) {
|
||||
<div class="chart-list">${synergRows}</div>
|
||||
${s.synergicBest ? `<div class="chart-sub" style="margin-top:6px">Максимум среди синергичных: <b>${escapeHtml(s.synergicBest.name)} ${s.synergicBest.weight}×${s.synergicBest.reps}</b> (${fmtDate(s.synergicBest.date)})</div>` : ''}
|
||||
|
||||
<div style="display:flex; gap:8px; margin-top:12px">
|
||||
<button class="btn btn-small btn-secondary" data-ex="${escapeHtml(exerciseName)}"
|
||||
<div class="modal-actions-row">
|
||||
<button class="btn btn-secondary big-touch" data-ex="${escapeHtml(exerciseName)}"
|
||||
onclick="EM.showChartFrom(this)">📈 График</button>
|
||||
<button class="btn btn-primary big-touch" onclick="ModalBase.closeModal()">✕ Закрыть</button>
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
|
||||
@@ -74,6 +74,13 @@ export function stepValue(id, delta, adaptive = false) {
|
||||
input.dispatchEvent(new Event('change'));
|
||||
}
|
||||
|
||||
// Подложка модалки: закрытие по фону и по Esc; глобальный closeModal —
|
||||
// на него ссылаются onclick в разметке графиков и сводки
|
||||
window.closeModal = closeModal;
|
||||
document.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Escape" && container() && container().innerHTML) closeModal();
|
||||
});
|
||||
|
||||
window.ModalBase = {
|
||||
showModal,
|
||||
closeModal,
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
|
||||
import { state } from '../state.js';
|
||||
import { escapeHtml } from '../utils.js';
|
||||
import { drawExerciseProgress, drawBodyMetricsGraph } from './dashboard.js';
|
||||
import { drawBodyMetricsGraph } from './dashboard.js';
|
||||
import { showExerciseSummary } from '../modals/exercise-summary.js';
|
||||
import { showChartDialog } from '../modals/chart-modal.js';
|
||||
|
||||
const CHART_EX_KEY = 'gym_dash_char…ise';
|
||||
|
||||
@@ -22,16 +23,16 @@ export function renderDashboard() {
|
||||
<h3>💪 Прогресс упражнения</h3>
|
||||
<div class="field-group">
|
||||
<label>Выберите упражнение</label>
|
||||
<select id="dash-ex-select" onchange="DashboardLogic.updateExerciseChart()">
|
||||
<select id="dash-ex-select" onchange="DashboardLogic.rememberExercise()">
|
||||
<option value="">— Выберите —</option>
|
||||
${getUniqueExercises().map(ex => `<option value="${escapeHtml(ex)}">${escapeHtml(ex)}</option>`).join('')}
|
||||
</select>
|
||||
</div>
|
||||
<canvas id="chart-exercise" width="400" height="250" style="width:100%; background:#1e1e1e; border-radius:8px;"></canvas>
|
||||
<div style="margin-top:8px">
|
||||
<button class="btn btn-small btn-secondary" onclick="DashboardLogic.showExSummary()">📋 Сводка по упражнению</button>
|
||||
<div style="display:flex; gap:8px; flex-wrap:wrap">
|
||||
<button class="btn btn-primary" style="flex:1" onclick="DashboardLogic.openChart()">📈 Открыть график</button>
|
||||
<button class="btn btn-secondary" onclick="DashboardLogic.showExSummary()">📋 Сводка</button>
|
||||
</div>
|
||||
<p class="text-muted text-small mt-10">Главное — рабочий максимум «вес × повторы»: зелёный — прогресс (вес выше или тот же вес и больше повторов), красный — откат. Тусклые точки — остальные подходы, «×N» — их число. Последние 10 тренировок.</p>
|
||||
<p class="text-muted text-small mt-10">Главное — рабочий максимум «вес × повторы»: зелёный — прогресс (вес выше или тот же вес и больше повторов), красный — откат. Тусклые точки — остальные подходы, «×N» — их число.</p>
|
||||
</div>
|
||||
|
||||
<!-- Секция 2: Динамика тела -->
|
||||
@@ -57,20 +58,15 @@ export function renderDashboard() {
|
||||
`;
|
||||
|
||||
window.DashboardLogic = {
|
||||
updateExerciseChart: () => {
|
||||
const select = document.getElementById('dash-ex-select');
|
||||
const canvas = document.getElementById('chart-exercise');
|
||||
// Выбор упражнения запоминается и восстанавливается при следующем открытии
|
||||
rememberExercise: () => {
|
||||
localStorage.setItem(CHART_EX_KEY, document.getElementById('dash-ex-select').value);
|
||||
},
|
||||
openChart: () => {
|
||||
const select = document.getElementById('dash-ex-select');
|
||||
if (!select.value) { alert('Сначала выберите упражнение'); return; }
|
||||
localStorage.setItem(CHART_EX_KEY, select.value);
|
||||
if (select.value) {
|
||||
drawExerciseProgress(canvas, select.value);
|
||||
} else {
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.clearRect(0,0,canvas.width,canvas.height);
|
||||
ctx.fillStyle='#666';
|
||||
ctx.textAlign='center';
|
||||
ctx.fillText('Выберите упражнение выше', canvas.width/2, canvas.height/2);
|
||||
}
|
||||
showChartDialog(select.value);
|
||||
},
|
||||
showExSummary: () => {
|
||||
const select = document.getElementById('dash-ex-select');
|
||||
|
||||
@@ -27,6 +27,9 @@ function freshState() {
|
||||
|
||||
mode: "personal",
|
||||
currentClientId: null,
|
||||
|
||||
goal: "strength",
|
||||
deletedWorkouts: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+60
-6
@@ -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();
|
||||
@@ -521,10 +547,11 @@ export async function initAppData() {
|
||||
serverExercises
|
||||
);
|
||||
|
||||
// Тренировки
|
||||
const serverWorkouts = (data.workouts || []).map((w) =>
|
||||
convertBackendWorkout(w, workoutTypeNameById)
|
||||
);
|
||||
// Тренировки: серверные, которых нет в списке удалённых этим устройством
|
||||
const tombstones = new Set(Array.isArray(state.deletedWorkouts) ? state.deletedWorkouts : []);
|
||||
const serverWorkouts = (data.workouts || [])
|
||||
.map((w) => convertBackendWorkout(w, workoutTypeNameById))
|
||||
.filter((w) => !tombstones.has(w.sync_id));
|
||||
|
||||
state.workouts = mergeBySyncId(
|
||||
state.workouts || [],
|
||||
@@ -723,6 +750,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),
|
||||
};
|
||||
@@ -736,8 +775,9 @@ export async function sync() {
|
||||
// тоже должны уходить на сервер (upsert по sync_id идемпотентен)
|
||||
const dirtyWorkouts = state.workouts;
|
||||
const dirtyMetrics = getDirtyMetrics(); // Новая функция
|
||||
const tombstones = Array.isArray(state.deletedWorkouts) ? state.deletedWorkouts : [];
|
||||
|
||||
if (dirtyWorkouts.length === 0 && dirtyMetrics.length === 0) {
|
||||
if (dirtyWorkouts.length === 0 && dirtyMetrics.length === 0 && tombstones.length === 0) {
|
||||
alert("Нет данных для синхронизации");
|
||||
return;
|
||||
}
|
||||
@@ -757,6 +797,7 @@ export async function sync() {
|
||||
exercises: buildExercisesPayload(),
|
||||
workouts: buildWorkoutsPayload(dirtyWorkouts),
|
||||
body_metrics: buildMetricsPayload(dirtyMetrics), // Отправляем замеры
|
||||
deleted_sync_ids: tombstones.slice(), // удалённые тренировки
|
||||
};
|
||||
|
||||
console.log("📤 Sending sync payload:", payload);
|
||||
@@ -767,6 +808,10 @@ export async function sync() {
|
||||
// Помечаем все как синхронизированные
|
||||
dirtyWorkouts.forEach(w => w.synced = true);
|
||||
dirtyMetrics.forEach(m => m.synced = true);
|
||||
// Надгробия снимаем только если сервер умеет удалять (в ответе есть
|
||||
// счётчик deleted). Со старым бэкендом ответ 200, но удаления он
|
||||
// проигнорировал — оставляем список, уйдёт в следующем синке.
|
||||
if (response.deleted) state.deletedWorkouts = [];
|
||||
|
||||
saveState();
|
||||
|
||||
@@ -775,9 +820,18 @@ export async function sync() {
|
||||
}
|
||||
|
||||
const createdW = response.created?.workouts || 0;
|
||||
const updatedW = response.updated?.workouts || 0;
|
||||
const deletedW = response.deleted?.workouts || 0;
|
||||
const createdM = response.created?.body_metrics || 0;
|
||||
|
||||
let message = `Синхронизировано:\nТренировок: ${createdW}\nЗамеров: ${createdM}`;
|
||||
let message = `Синхронизировано:\nТренировок: ${createdW + updatedW}` +
|
||||
(updatedW ? ` (новых ${createdW}, обновлено ${updatedW})` : "") +
|
||||
(deletedW ? `\nУдалено: ${deletedW}` : "") +
|
||||
`\nЗамеров: ${createdM}`;
|
||||
|
||||
if (tombstones.length && !response.deleted) {
|
||||
message += "\n\n⚠️ Сервер не подтвердил удаления — на нём старый бэкенд. Пересоберите backend, удаления уйдут при следующем синке.";
|
||||
}
|
||||
|
||||
if (response.warnings?.length) {
|
||||
message += `\n\nПредупреждения:\n${response.warnings.join("\n")}`;
|
||||
|
||||
@@ -170,3 +170,63 @@ textarea { resize: vertical; min-height: 60px; }
|
||||
.sum-label { font-size: 0.72rem; color: var(--text-secondary, #888); margin-top: 2px; }
|
||||
.sum-sub { font-size: 0.68rem; color: var(--text-secondary, #888); margin-top: 2px; }
|
||||
.chart-legend-bottom { margin-top: 2px; }
|
||||
|
||||
/* Крупные кнопки под графиками и сводками — попадание в зале после подхода */
|
||||
.modal-actions-row {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
.big-touch {
|
||||
flex: 1;
|
||||
min-height: 56px;
|
||||
font-size: 17px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.modal-fullscreen .btn-icon {
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
min-width: 52px;
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
/* Легенда графика — крупная, над графиком (статистика записей остаётся внизу) */
|
||||
.chart-legend-top {
|
||||
font-size: 15px;
|
||||
line-height: 1.45;
|
||||
margin: 2px 2px 10px;
|
||||
}
|
||||
|
||||
/* Броская легенда графика: три коротких чипа + ⓘ с пояснением */
|
||||
.chart-legend-big {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 14px;
|
||||
font-size: 19px;
|
||||
font-weight: 700;
|
||||
margin: 2px 2px 8px;
|
||||
}
|
||||
.lg-line { color: #fff; }
|
||||
.lg-up { color: #3ddc55; }
|
||||
.lg-down { color: #ff5a5a; }
|
||||
.lg-info {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 50%;
|
||||
border: 1.5px solid #777;
|
||||
background: transparent;
|
||||
color: #ccc;
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
}
|
||||
.chart-hint {
|
||||
font-size: 14.5px;
|
||||
line-height: 1.5;
|
||||
color: #d5d5d5;
|
||||
background: rgba(255, 255, 255, 0.07);
|
||||
border-radius: 12px;
|
||||
padding: 10px 14px;
|
||||
margin: 0 2px 10px;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user