wip: слияние прода-версии с портированными фичами (до merge iovi)

This commit is contained in:
Иван Овчинников
2026-11-20 01:06:17 +03:00
parent 83ff9ae6e4
commit c3a34192ab
13 changed files with 2557 additions and 728 deletions
+3
View File
@@ -1,2 +1,5 @@
__pycache__/ __pycache__/
*.pyc *.pyc
*.db
.venv/
+2 -1
View File
@@ -1,3 +1,4 @@
import os
import bcrypt import bcrypt
import jwt import jwt
from jwt.exceptions import PyJWTError from jwt.exceptions import PyJWTError
@@ -6,10 +7,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"))
+90
View File
@@ -0,0 +1,90 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Gym Bro 😈 (демо)</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/settings.css">
</head>
<body>
<header id="app-header"></header>
<main id="app" class="container"></main>
<div id="modal-container"></div>
<script>
// Демо-данные для просмотра (ключ v6 = текущая версия хранилища)
if (!localStorage.getItem('gym_tracker_v6')) {
localStorage.setItem('gym_tracker_v6', JSON.stringify({
workouts: [
{
id: '1', client_id: null, startTime: new Date().toISOString(), endTime: null,
type: 'спина-плечи',
exercises: [
{ id: 'e1', name: 'Косичка', sets: [
{ id: 's1', weight: 30, reps: 15, rating: 5, isDropset: false, timestamp: '2026-11-20T00:10:00+03:00' },
{ id: 's2', weight: 30, reps: 15, rating: 5, isDropset: false, timestamp: '2026-11-20T00:14:00+03:00' },
]},
{ id: 'e2', name: 'Разгибание на блоке', sets: [
{ id: 's3', weight: 25, reps: 15, rating: 4, isDropset: false, timestamp: '2026-11-20T00:12:00+03:00' },
{ id: 's4', weight: 25, reps: 15, rating: 5, isDropset: false, timestamp: '2026-11-20T00:16:00+03:00' },
]},
{ id: 'e3', name: 'Жим гантелей на лавке 30', sets: [
{ id: 's5', weight: 22, reps: 12, rating: 5, isDropset: false, timestamp: '2026-11-20T00:20:00+03:00' },
]},
{ id: 'e4', name: 'Молотки', sets: [] },
],
cardio: [{ id: 'c1', type: 'бег', purpose: 'warmup', duration: 10 }],
setGroups: [{ id: 'g1', name: 'суперсет на спину', exerciseIds: ['e1', 'e2'] }],
notes: '', synced: false,
},
{
id: '2', client_id: null, startTime: '2026-11-17T18:00:00+03:00', endTime: '2026-11-17T19:10:00+03:00',
type: 'грудь-руки',
exercises: [
{ id: 'e5', name: 'Жим гантелей на лавке 45', sets: [
{ id: 's6', weight: 24, reps: 10, rating: 5, isDropset: false, timestamp: '2026-11-17T18:30:00+03:00' },
{ id: 's7', weight: 24, reps: 10, rating: 4, isDropset: true, subSets: [{ weight: 24, reps: 6 }, { weight: 18, reps: 8 }], timestamp: '2026-11-17T18:40:00+03:00' },
]},
{ id: 'e6', name: 'Разводка', sets: [
{ id: 's8', weight: 10, reps: 15, rating: 5, isDropset: false, timestamp: '2026-11-17T18:50:00+03:00' },
]},
],
cardio: [], setGroups: [], notes: 'после паузы', synced: false,
},
{
id: '3', client_id: null, startTime: '2026-11-14T18:00:00+03:00', endTime: '2026-11-14T19:00:00+03:00',
type: 'грудь-руки',
exercises: [
{ id: 'e7', name: 'Жим гантелей на лавке 30', sets: [
{ id: 's9', weight: 20, reps: 12, rating: 5, isDropset: false, timestamp: '2026-11-14T18:30:00+03:00' },
]},
],
cardio: [], setGroups: [], notes: '', synced: true,
},
],
exerciseRef: [
{ id: 'r1', name: 'Косичка', workoutType: 'спина-плечи', group: '' },
{ id: 'r2', name: 'Разгибание на блоке', workoutType: 'спина-плечи', group: '' },
{ id: 'r3', name: 'Жим гантелей на лавке 30', workoutType: 'грудь-руки', group: 'жим гантелей на лавке' },
{ id: 'r4', name: 'Жим гантелей на лавке 45', workoutType: 'грудь-руки', group: 'жим гантелей на лавке' },
{ id: 'r5', name: 'Молотки', workoutType: 'грудь-руки', group: '' },
{ id: 'r6', name: 'Разводка', workoutType: 'грудь-руки', group: '' },
],
bodyMetrics: [],
workoutTypes: [{ id: 1, name: 'грудь-руки' }, { id: 2, name: 'ноги' }, { id: 3, name: 'спина-плечи' }],
metricTypes: [],
clients: [],
expandedWorkoutId: '1',
expandedExerciseId: null,
nextId: 100,
mode: 'personal',
currentClientId: null,
}));
}
</script>
<script type="module" src="js/app.js"></script>
</body>
</html>
+48 -27
View File
@@ -1,48 +1,69 @@
// frontend/js/api.js // frontend/js/api.js
import { apiFetch } from "./auth.js";
import { API_BASE } from "./config.js"; // <-- Добавили импорт
// УДАЛИТЬ эти строки из начала api.js: import { apiFetch } from "./auth.js";
// export const API_BASE = ...
async function jsonOrThrow(res, fallbackMessage) {
if (!res.ok) {
let detail = fallbackMessage;
try {
const err = await res.json();
if (typeof err.detail === "string") {
detail = err.detail;
} else if (Array.isArray(err.detail)) {
detail = err.detail
.map((d) => `${d.loc?.join(".") || ""}: ${d.msg || ""}`.trim())
.join("; ");
} else {
detail = JSON.stringify(err.detail || err);
}
} catch {
// ignore parse error
}
throw new Error(detail);
}
return await res.json();
}
export async function fetchBootstrapData() {
const res = await apiFetch("/bootstrap/");
return jsonOrThrow(res, "Failed to fetch bootstrap data");
}
export async function fetchWorkoutTypes() { export async function fetchWorkoutTypes() {
const res = await apiFetch("/workout-types/"); const res = await apiFetch("/workout-types/");
if (!res.ok) throw new Error('Failed to fetch workout types'); return jsonOrThrow(res, "Failed to fetch workout types");
return await res.json();
} }
export async function fetchMetricTypes() { export async function fetchMetricTypes() {
const res = await fetch(`${API_BASE}/metric-types/`); const res = await apiFetch("/metric-types/");
if (!res.ok) throw new Error('Failed to fetch metric types'); return jsonOrThrow(res, "Failed to fetch metric types");
return await res.json();
} }
export async function fetchClients() { export async function fetchClients() {
const res = await fetch(`${API_BASE}/clients/`); const res = await apiFetch("/clients/");
if (!res.ok) throw new Error('Failed to fetch clients'); return jsonOrThrow(res, "Failed to fetch clients");
return await res.json();
} }
export async function fetchExerciseHistory(exerciseName, clientId = null) { export async function fetchExerciseHistory(exerciseName, clientId = null) {
let url = `${API_BASE}/exercises/history/${encodeURIComponent(exerciseName)}?limit=10`; let path = `/exercises/history/${encodeURIComponent(exerciseName)}?limit=10`;
if (clientId) url += `&client_id=${clientId}`;
const res = await fetch(url); if (clientId) {
if (!res.ok) throw new Error('Failed to fetch history'); path += `&client_id=${clientId}`;
return await res.json(); }
const res = await apiFetch(path);
return jsonOrThrow(res, "Failed to fetch history");
} }
export async function syncData(payload) { export async function syncData(payload) {
const res = await fetch(`${API_BASE}/sync/`, { const res = await apiFetch("/sync/", {
method: 'POST', method: "POST",
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload),
body: JSON.stringify(payload)
}); });
if (!res.ok) { return jsonOrThrow(res, "Sync failed");
const err = await res.json();
console.error('❌ Sync API Error Detail:', err); // <-- Покажет, какое именно поле не прошло валидацию
throw new Error(err.detail ? JSON.stringify(err.detail) : 'Sync failed');
}
return await res.json();
} }
+206 -32
View File
@@ -1,68 +1,242 @@
import { loadState, saveState, state, updateSyncStatus } from './state.js'; import {
import { renderMainScreen } from './render/main-screen.js'; loadState,
import { sync, initAppData } from './sync.js'; saveState,
state,
setActiveUser,
getActiveUser,
resetState,
updateSyncStatus,
} from "./state.js";
import { renderMainScreen } from "./render/main-screen.js";
import { sync, initAppData } from "./sync.js";
import {
getToken,
getStoredUser,
clearSession,
login,
register,
me,
} from "./auth.js";
// Подключаем logic-модули // Подключаем logic-модули
import './logic/workout.js'; import "./logic/workout.js";
import './logic/exercise.js'; import "./logic/exercise.js";
import './logic/set.js'; import "./logic/set.js";
import './logic/cardio.js'; import "./logic/cardio.js";
import './logic/metrics.js'; import "./logic/metrics.js";
import './logic/settings.js'; import "./logic/settings.js";
import './logic/group.js'; import "./logic/group.js";
// Подключаем модалки // Подключаем модалки
import './modals/modal-base.js'; import "./modals/modal-base.js";
import './modals/exercise-modal.js'; import "./modals/exercise-modal.js";
import './modals/set-modal.js'; import "./modals/set-modal.js";
import './modals/cardio-modal.js'; import "./modals/cardio-modal.js";
import './modals/metrics-modal.js'; import "./modals/metrics-modal.js";
import './modals/client-select-modal.js'; import "./modals/edit-exercise-modal.js";
import './modals/edit-exercise-modal.js'; import "./modals/edit-workout-date-modal.js";
import './modals/edit-workout-date-modal.js'; import "./modals/client-select-modal.js";
import './modals/group-modal.js'; import "./modals/group-modal.js";
import './modals/chart-modal.js'; import "./modals/chart-modal.js";
function renderHeader() { function renderHeader() {
const modeLabel = state.mode === 'trainer' ? '👨‍🏫 Тренер' : '👤 Личный'; const user = getActiveUser();
document.getElementById('app-header').innerHTML = ` const modeLabel = state.mode === "trainer" ? "👨‍🏫 Тренер" : "👤 Личный";
document.getElementById("app-header").innerHTML = `
<div> <div>
<h2>Gym Bro 😈 <span style="font-size:0.8rem; color:var(--text-secondary); font-weight:400;">(${modeLabel})</span></h2> <h2>
Gym Bro 😈
<span style="font-size:0.8rem; color:var(--text-secondary); font-weight:400;">
(${modeLabel})
</span>
</h2>
<div id="sync-status" class="sync-status">● Локально</div> <div id="sync-status" class="sync-status">● Локально</div>
${user ? `<div class="text-small text-muted">${user.display_name || user.username}</div>` : ""}
</div> </div>
<div class="header-actions"> <div class="header-actions">
<button class="icon-btn header-btn" onclick="App.toggleMode()" title="Сменить режим">🔄</button> <button class="icon-btn header-btn" onclick="App.showDashboard()" title="Статистика">📊</button>
<button class="icon-btn header-btn" onclick="ML.showBodyMetrics()" title="Личные замеры">📏</button> <button class="icon-btn header-btn" onclick="ML.showBodyMetrics()" title="Личные замеры">📏</button>
<button class="icon-btn header-btn" onclick="SettingsLogic.show()" title="Настройки">⚙️</button> <button class="icon-btn header-btn" onclick="SettingsLogic.show()" title="Настройки">⚙️</button>
<button class="btn btn-small btn-secondary" onclick="AppSync.sync()" title="Синхронизация">🔄</button> <button class="btn btn-small btn-secondary" onclick="AppSync.sync()" title="Синхронизация">🔄</button>
<button class="icon-btn header-btn" onclick="AuthUI.logout()" title="Выйти">🚪</button>
</div> </div>
`; `;
} }
async function init() { function renderAuthScreen(message = "") {
const header = document.getElementById("app-header");
const app = document.getElementById("app");
header.innerHTML = `
<div>
<h2>Gym Bro 😈</h2>
<div class="sync-status">Требуется вход</div>
</div>
`;
app.innerHTML = `
<div class="card auth-card">
<h3>Вход / Регистрация</h3>
<div class="field-group">
<label>Логин</label>
<input type="text" id="auth-username" placeholder="username" autocomplete="username">
</div>
<div class="field-group">
<label>Пароль</label>
<input type="password" id="auth-password" placeholder="••••••" autocomplete="current-password">
</div>
<div class="field-group">
<label>Роль при регистрации</label>
<select id="auth-role">
<option value="personal">Личный трекер</option>
<option value="trainer">Тренер</option>
</select>
</div>
<div class="btn-row">
<button class="btn btn-secondary" onclick="AuthUI.doLogin()">Войти</button>
<button class="btn" onclick="AuthUI.doRegister()">Регистрация</button>
</div>
<div id="auth-error" class="auth-error">${message}</div>
</div>
`;
}
function showAuthError(text) {
const el = document.getElementById("auth-error");
if (el) el.textContent = text || "";
}
async function enterApp(user) {
setActiveUser(user);
loadState(); loadState();
// Если пользователь тренер и это его первое состояние — включаем тренерский режим
if (
user.role === "trainer" &&
state.workouts.length === 0 &&
state.clients.length === 0 &&
state.exerciseRef.length === 0
) {
state.mode = "trainer";
saveState();
}
renderHeader(); renderHeader();
renderMainScreen(); renderMainScreen();
updateSyncStatus(); updateSyncStatus();
// Загружаем справочники с бэкенда в фоне // ВАЖНО: Загружаем справочники ТОЛЬКО после успешного входа
await initAppData(); await initAppData();
} }
async function bootstrap() {
const token = getToken();
// 1. Если токена нет — сразу на экран входа
if (!token) {
renderAuthScreen();
return;
}
let user = getStoredUser();
// 2. Проверяем валидность токена на сервере
try {
const freshUser = await me();
if (freshUser) {
user = freshUser;
} else {
throw new Error("Invalid user response");
}
} catch (e) {
console.warn("Token invalid or expired", e);
clearSession();
renderAuthScreen("Сессия истекла. Войдите заново.");
return;
}
// 3. Если всё ок — входим в приложение
await enterApp(user);
}
window.AuthUI = {
async doLogin() {
const username = document.getElementById("auth-username")?.value.trim();
const password = document.getElementById("auth-password")?.value;
if (!username || !password) {
showAuthError("Введите логин и пароль");
return;
}
try {
showAuthError("");
const user = await login(username, password);
await enterApp(user);
} catch (e) {
showAuthError(e.message);
}
},
async doRegister() {
const username = document.getElementById("auth-username")?.value.trim();
const password = document.getElementById("auth-password")?.value;
const role = document.getElementById("auth-role")?.value || "personal";
if (!username || !password) {
showAuthError("Введите логин и пароль");
return;
}
try {
showAuthError("");
const user = await register(username, password, role);
await enterApp(user);
} catch (e) {
showAuthError(e.message);
}
},
logout() {
clearSession();
resetState();
renderAuthScreen("Вы вышли из системы");
},
};
window.addEventListener("auth:unauthorized", () => {
clearSession();
resetState();
renderAuthScreen("Сессия истекла. Войдите заново.");
});
window.App = { window.App = {
getWorkout: (id) => state.workouts.find(w => w.id === id), getWorkout: (id) => state.workouts.find((w) => w.id === id),
saveAndRender: () => { saveState(); }, saveAndRender: () => {
saveState();
},
toggleMode: () => { toggleMode: () => {
state.mode = state.mode === 'personal' ? 'trainer' : 'personal'; state.mode = state.mode === "personal" ? "trainer" : "personal";
saveState(); saveState();
renderHeader(); renderHeader();
renderMainScreen(); renderMainScreen();
}, },
showDashboard: () => {
import('./render/dashboard-screen.js').then(mod => mod.renderDashboard());
},
backToMain: () => renderMainScreen(), backToMain: () => renderMainScreen(),
}; };
window.AppSync = { sync }; window.AppSync = { sync };
// Делаем renderMainScreen доступным глобально
window.renderMainScreen = renderMainScreen; window.renderMainScreen = renderMainScreen;
window.state = state;
document.addEventListener('DOMContentLoaded', init); document.addEventListener("DOMContentLoaded", bootstrap);
+23 -34
View File
@@ -5,16 +5,10 @@ import { API_BASE } from "./config.js";
const TOKEN_KEY = "gym_auth_token"; const TOKEN_KEY = "gym_auth_token";
const USER_KEY = "gym_auth_user"; const USER_KEY = "gym_auth_user";
/**
* Получить сохранённый токен
*/
export function getToken() { export function getToken() {
return localStorage.getItem(TOKEN_KEY); return localStorage.getItem(TOKEN_KEY);
} }
/**
* Получить сохранённого пользователя
*/
export function getStoredUser() { export function getStoredUser() {
try { try {
const raw = localStorage.getItem(USER_KEY); const raw = localStorage.getItem(USER_KEY);
@@ -24,17 +18,19 @@ export function getStoredUser() {
} }
} }
/**
* Сохранить сессию (токен + данные пользователя)
*/
export function setSession(token, user) { export function setSession(token, user) {
// Гарантируем, что данные записаны синхронно
localStorage.setItem(TOKEN_KEY, token); localStorage.setItem(TOKEN_KEY, token);
localStorage.setItem(USER_KEY, JSON.stringify(user)); localStorage.setItem(USER_KEY, JSON.stringify(user));
// Принудительно обновляем UI статус, если элемент существует
const statusEl = document.getElementById('sync-status');
if (statusEl) {
statusEl.textContent = '● Авторизовано';
statusEl.className = 'sync-status synced';
}
} }
/**
* Очистить сессию (Logout)
*/
export function clearSession() { export function clearSession() {
localStorage.removeItem(TOKEN_KEY); localStorage.removeItem(TOKEN_KEY);
localStorage.removeItem(USER_KEY); localStorage.removeItem(USER_KEY);
@@ -42,19 +38,21 @@ export function clearSession() {
/** /**
* Защищённый Fetch wrapper. * Защищённый Fetch wrapper.
* Автоматически добавляет Authorization header.
* При получении 401 очищает сессию и вызывает событие 'auth:unauthorized'.
*/ */
export async function apiFetch(path, options = {}) { export async function apiFetch(path, options = {}) {
const token = getToken(); const token = getToken();
const headers = new Headers(options.headers || {}); // Критическая проверка: если токена нет, не идем на сервер
if (!token) {
if (token) { console.warn(`⚠️ [AUTH] No token found for request: ${path}. Skipping.`);
headers.set("Authorization", `Bearer ${token}`); throw new Error("Not authenticated");
} }
// Если есть тело запроса и Content-Type не задан явно — ставим JSON const headers = new Headers(options.headers || {});
// Всегда добавляем Authorization, перезаписывая любые существующие
headers.set("Authorization", `Bearer ${token}`);
if (options.body && !headers.has("Content-Type")) { if (options.body && !headers.has("Content-Type")) {
headers.set("Content-Type", "application/json"); headers.set("Content-Type", "application/json");
} }
@@ -66,23 +64,22 @@ export async function apiFetch(path, options = {}) {
headers, headers,
}); });
} catch (e) { } catch (e) {
// Сеть недоступна или другая ошибка транспорта console.error(`❌ [NETWORK] Failed to reach ${path}:`, e);
// Не логаутим автоматически, просто пробрасываем ошибку
throw e; throw e;
} }
// Если сервер ответил 401 Unauthorized — токен протух или неверный // Если 401 — очищаем сессию и кидаем событие
if (res.status === 401) { if (res.status === 401) {
console.error(`❌ [AUTH] Received 401 Unauthorized for ${path}. Clearing session.`);
clearSession(); clearSession();
window.dispatchEvent(new Event("auth:unauthorized")); window.dispatchEvent(new Event("auth:unauthorized"));
// Пробрасываем ошибку, чтобы вызывающий код знал, что произошло
throw new Error("Unauthorized");
} }
return res; return res;
} }
/**
* Логин пользователя
*/
export async function login(username, password) { export async function login(username, password) {
const res = await fetch(`${API_BASE}/auth/login`, { const res = await fetch(`${API_BASE}/auth/login`, {
method: "POST", method: "POST",
@@ -100,9 +97,6 @@ export async function login(username, password) {
return data.user; return data.user;
} }
/**
* Регистрация нового пользователя
*/
export async function register(username, password, role = "personal") { export async function register(username, password, role = "personal") {
const res = await fetch(`${API_BASE}/auth/register`, { const res = await fetch(`${API_BASE}/auth/register`, {
method: "POST", method: "POST",
@@ -120,18 +114,13 @@ export async function register(username, password, role = "personal") {
return data.user; return data.user;
} }
/**
* Проверка токена / получение текущего пользователя
*/
export async function me() { export async function me() {
// Используем apiFetch, чтобы автоматически добавить токен
const res = await apiFetch("/auth/me"); const res = await apiFetch("/auth/me");
if (!res.ok) return null; if (!res.ok) return null;
return await res.json(); return await res.json();
} }
/**
* Хелпер для парсинга ошибок FastAPI/Pydantic
*/
async function parseError(res, fallbackMessage) { async function parseError(res, fallbackMessage) {
try { try {
const err = await res.json(); const err = await res.json();
+62 -23
View File
@@ -1,51 +1,90 @@
import { state, saveState, genId } from '../state.js'; // frontend/js/logic/metrics.js
import { state, saveState, genId, generateUUID } from '../state.js';
import { renderMainScreen } from '../render/main-screen.js'; import { renderMainScreen } from '../render/main-screen.js';
import { showBodyMetricsDialog } from '../modals/metrics-modal.js'; import { showBodyMetricsDialog } from '../modals/metrics-modal.js';
/**
* Показывает модалку добавления/редактирования личных замеров
*/
export function showBodyMetrics() { export function showBodyMetrics() {
// В личном режиме — замеры без клиента // Фильтруем только личные замеры (без client_id)
const personalMetrics = state.bodyMetrics.filter(m => !m.client_id); const personalMetrics = state.bodyMetrics.filter(m => !m.client_id);
showBodyMetricsDialog(personalMetrics, (newMetric) => { showBodyMetricsDialog(personalMetrics, (newMetricData, isEdit) => {
if (!newMetric) return; if (!newMetricData) return;
newMetric.id = genId();
newMetric.client_id = null; // личный замер if (isEdit && newMetricData.id) {
state.bodyMetrics.unshift(newMetric); // Редактирование существующего
const existing = state.bodyMetrics.find(m => m.id === newMetricData.id);
if (existing) {
Object.assign(existing, newMetricData);
existing.synced = false; // Помечаем как измененный
}
} else {
// Создание нового
const metric = {
id: generateUUID(), // Используем UUID сразу для стабильности
sync_id: generateUUID(),
date: newMetricData.date,
notes: newMetricData.notes || "",
values: newMetricData.values || [],
client_id: null, // Личный замер
synced: false, // Не синхронизирован
};
state.bodyMetrics.unshift(metric);
}
// Сортировка по дате (новые сверху)
state.bodyMetrics.sort((a, b) => new Date(b.date) - new Date(a.date)); state.bodyMetrics.sort((a, b) => new Date(b.date) - new Date(a.date));
saveState(); saveState();
renderMainScreen(); renderMainScreen();
alert('Замеры сохранены!'); alert('Замер сохранен локально. Нажмите 🔄 для синхронизации.');
}); });
} }
/**
* Редактирование конкретного замера
*/
export function editBodyMetric(metricId) { export function editBodyMetric(metricId) {
const metric = state.bodyMetrics.find(m => m.id === metricId); const metric = state.bodyMetrics.find(m => m.id === metricId);
if (!metric) return; if (!metric) return;
showBodyMetricsDialog(state.bodyMetrics, (updatedData) => {
// Передаем данные в диалог. Диалог должен вернуть объект с теми же ID/sync_id, но новыми значениями
showBodyMetricsDialog([metric], (updatedData, isEdit) => {
if (!updatedData) return; if (!updatedData) return;
Object.assign(metric, updatedData);
// Обновляем поля
metric.date = updatedData.date;
metric.notes = updatedData.notes;
metric.values = updatedData.values;
metric.synced = false; // Помечаем как измененный
state.bodyMetrics.sort((a, b) => new Date(b.date) - new Date(a.date)); state.bodyMetrics.sort((a, b) => new Date(b.date) - new Date(a.date));
saveState(); saveState();
// Обновляем список в настройках, если он открыт
const list = document.getElementById('body-metrics-list');
if (list && typeof window.SettingsLogic !== 'undefined') {
window.SettingsLogic._renderPersonalMetricsList();
} else {
renderMainScreen(); renderMainScreen();
} alert('Изменения сохранены. Нажмите 🔄 для синхронизации.');
}, metric); }, metric);
} }
/**
* Удаление замера
*/
export function deleteMetric(id) { export function deleteMetric(id) {
if (!confirm('Удалить замер?')) return; if (!confirm('Удалить этот замер?')) return;
// Для простоты MVP удаляем локально.
// На сервере удаление через API /body-metrics/{id} можно добавить позже.
// Сейчас просто убираем из стейта.
state.bodyMetrics = state.bodyMetrics.filter(m => m.id !== id); state.bodyMetrics = state.bodyMetrics.filter(m => m.id !== id);
saveState(); saveState();
const list = document.getElementById('body-metrics-list');
if (list && typeof window.SettingsLogic !== 'undefined') {
window.SettingsLogic._renderPersonalMetricsList();
} else {
renderMainScreen(); renderMainScreen();
}
} }
window.ML = { showBodyMetrics, editBodyMetric, deleteMetric }; window.ML = {
showBodyMetrics,
editBodyMetric,
deleteMetric
};
File diff suppressed because it is too large Load Diff
+132 -33
View File
@@ -1,44 +1,143 @@
// frontend/js/modals/metrics-modal.js
import { showModal, closeModal, stepperHtml } from './modal-base.js'; import { showModal, closeModal, stepperHtml } from './modal-base.js';
import { state } from '../state.js';
import { toDatetimeLocal } from '../utils.js'; import { toDatetimeLocal } from '../utils.js';
let _cb = null; let _cb = null;
let _types = [];
let _isEdit = false;
export function showBodyMetricsDialog(metrics, callback, editing = null) { function stepForUnit(unit) {
_cb = callback; const u = String(unit || '').toLowerCase();
const src = editing || metrics[0] || {}; if (u.includes('кг') || u.includes('%')) return 0.1;
const isEdit = !!editing; if (u.includes('см') || u.includes('мм')) return 0.5;
const dateVal = src.date ? toDatetimeLocal(src.date) : toDatetimeLocal(new Date().toISOString()); return 1;
showModal(`<div class="modal-content">
<h3 class="modal-title">📏 Замеры ${isEdit ? '(ред.)' : ''}</h3>
<div class="field-group"><label>📅 Дата</label><input type="datetime-local" id="m-md" value="${dateVal}"></div>
<div class="field-row">
<div class="field-group"><label>⚖️ Вес</label>${stepperHtml('m-mw', src.weight??'', 0.1, 'кг')}</div>
<div class="field-group"><label>📏 Грудь</label>${stepperHtml('m-mc', src.chest??'', 1, 'см', 'numeric')}</div></div>
<div class="field-row">
<div class="field-group"><label>📏 Талия</label>${stepperHtml('m-mwa', src.waist??'', 1, 'см', 'numeric')}</div>
<div class="field-group"><label>📏 Бёдра</label>${stepperHtml('m-mh', src.hips??'', 1, 'см', 'numeric')}</div></div>
<div class="field-row">
<div class="field-group"><label>💪 Руки</label>${stepperHtml('m-ma', src.arms??'', 0.5, 'см')}</div>
<div class="field-group"><label>🦵 Ноги</label>${stepperHtml('m-ml', src.legs??'', 0.5, 'см')}</div></div>
<div class="btn-row">
<button class="btn btn-secondary" onclick="ModalBase.closeOnBg({target:document.querySelector('.modal-overlay')})">Отмена</button>
<button class="btn btn-success" onclick="MetricsModal.submit(${isEdit})">Сохранить</button></div>
</div>`);
} }
export function submit(isEdit) { export function showBodyMetricsDialog(existingMetrics, callback, editing = null) {
const r = { _cb = callback;
date: new Date(document.getElementById('m-md').value).toISOString(), _isEdit = !!editing;
weight: parseFloat(document.getElementById('m-mw').value)||null,
chest: parseInt(document.getElementById('m-mc').value)||null, // Берем типы из состояния (загруженные с бэкенда)
waist: parseInt(document.getElementById('m-mwa').value)||null, _types = [...(state.metricTypes || [])].sort((a, b) => {
hips: parseInt(document.getElementById('m-mh').value)||null, const orderDiff = (a.sort_order || 0) - (b.sort_order || 0);
arms: parseFloat(document.getElementById('m-ma').value)||null, if (orderDiff !== 0) return orderDiff;
legs: parseFloat(document.getElementById('m-ml').value)||null, return String(a.name || '').localeCompare(String(b.name || ''));
});
if (_types.length === 0) {
showModal(`
<div class="modal-content">
<h3 class="modal-title">📏 Нет типов замеров</h3>
<p class="text-muted">
В настройках не добавлено ни одного типа замера.<br>
Перейдите в ⚙️ Настройки → 📏 Типы замеров и добавьте нужные метрики (Вес, Талия, Бицепс...).
</p>
<div class="btn-row">
<button class="btn btn-secondary" onclick="ModalBase.closeModal()">Закрыть</button>
<button class="btn" onclick="ModalBase.closeModal(); SettingsLogic.show();">⚙️ В настройки</button>
</div>
</div>
`);
return;
}
const source = editing || (existingMetrics && existingMetrics[0]) || {};
const dateValue = source.date ? toDatetimeLocal(source.date) : toDatetimeLocal(new Date().toISOString());
// Генерируем HTML для каждого типа замера динамически
const fieldsHtml = _types.map(mt => {
const id = `m-metric-${mt.id}`;
const step = stepForUnit(mt.unit);
// Ищем значение в объекте замера
// Новый формат: values: [{ metric_type_id, value }]
let value = '';
if (Array.isArray(source.values)) {
const valObj = source.values.find(v => v.metric_type_id == mt.id);
value = valObj ? valObj.value : '';
} else {
// Legacy fallback (если вдруг остались старые данные)
const legacyMap = {
weight: 'weight', chest: 'chest', waist: 'waist',
hips: 'hips', arms: 'arms', legs: 'legs'
}; };
if (!Object.values(r).some((v,i) => i>0 && v!==null)) { alert('Заполните поле'); return; } // Пытаемся угадать поле по имени или единице измерения, если нет ID
closeModal(); _cb?.(r, isEdit); // Но лучше всего полагаться на новый формат
}
return `
<div class="field-group">
<label>${mt.name} <span class="text-muted">(${mt.unit})</span></label>
${stepperHtml(id, value, step, mt.unit || '', 'decimal')}
</div>
`;
}).join('');
showModal(`
<div class="modal-content">
<h3 class="modal-title">📏 Замеры ${_isEdit ? '(ред.)' : ''}</h3>
<div class="field-group">
<label>📅 Дата</label>
<input type="datetime-local" id="m-metric-date" value="${dateValue}">
</div>
<!-- Динамические поля здесь -->
<div style="max-height: 50vh; overflow-y: auto;">
${fieldsHtml}
</div>
<div class="field-group">
<label>Комментарий</label>
<input type="text" id="m-metric-notes" value="${source.notes || ''}" placeholder="Например: утром натощак">
</div>
<div class="btn-row">
<button class="btn btn-secondary" onclick="ModalBase.closeModal()">Отмена</button>
<button class="btn btn-success" onclick="MetricsModal.submit()">Сохранить</button>
</div>
</div>
`);
}
export function submit() {
const dateInput = document.getElementById('m-metric-date');
const notesInput = document.getElementById('m-metric-notes');
if (!dateInput || !dateInput.value) {
alert('Укажите дату');
return;
}
// Собираем значения только тех полей, которые были заполнены
const values = _types.map(mt => {
const input = document.getElementById(`m-metric-${mt.id}`);
if (!input) return null;
const rawVal = parseFloat(input.value);
if (isNaN(rawVal)) return null;
return {
metric_type_id: mt.id,
value: rawVal
};
}).filter(Boolean);
if (values.length === 0) {
alert('Заполните хотя бы одно поле');
return;
}
const result = {
date: new Date(dateInput.value).toISOString(),
notes: notesInput.value.trim(),
values: values // Отправляем массив пар {type_id, value}
};
closeModal();
if (_cb) _cb(result, _isEdit);
} }
window.MetricsModal = { submit }; window.MetricsModal = { submit };
+96
View File
@@ -0,0 +1,96 @@
// frontend/js/render/dashboard-screen.js
import { state } from '../state.js';
import { drawExerciseProgress, drawBodyMetricsGraph } from './dashboard.js';
export function renderDashboard() {
const app = document.getElementById('app');
if (!app) return;
app.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>
<!-- Секция 1: Прогресс упражнений -->
<div class="card mb-20">
<h3>💪 Прогресс упражнения</h3>
<div class="field-group">
<label>Выберите упражнение</label>
<select id="dash-ex-select" onchange="DashboardLogic.updateExerciseChart()">
<option value="">— Выберите —</option>
${getUniqueExercises().map(ex => `<option value="${ex}">${ex}</option>`).join('')}
</select>
</div>
<canvas id="chart-exercise" width="400" height="200" style="width:100%; background:#1e1e1e; border-radius:8px;"></canvas>
<p class="text-muted text-small mt-10">Показаны макс. вес и повторения за последние 10 тренировок.</p>
</div>
<!-- Секция 2: Динамика тела -->
<div class="card">
<h3>⚖️ Динамика тела</h3>
<div class="field-row">
<div class="field-group">
<label>Клиент (если тренер)</label>
<select id="dash-client-select" onchange="DashboardLogic.updateBodyChart()">
<option value="">Личные замеры</option>
${state.clients.map(c => `<option value="${c.id}">${c.full_name}</option>`).join('')}
</select>
</div>
<div class="field-group">
<label>Тип замера</label>
<select id="dash-metric-select" onchange="DashboardLogic.updateBodyChart()">
${state.metricTypes.map(mt => `<option value="${mt.id}">${mt.name} (${mt.unit})</option>`).join('')}
</select>
</div>
</div>
<canvas id="chart-body" width="400" height="200" style="width:100%; background:#1e1e1e; border-radius:8px;"></canvas>
</div>
`;
window.DashboardLogic = {
updateExerciseChart: () => {
const select = document.getElementById('dash-ex-select');
const canvas = document.getElementById('chart-exercise');
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);
}
},
updateBodyChart: () => {
const clientSel = document.getElementById('dash-client-select');
const metricSel = document.getElementById('dash-metric-select');
const canvas = document.getElementById('chart-body');
const clientId = clientSel.value ? parseInt(clientSel.value) : null;
const metricId = metricSel.value ? parseInt(metricSel.value) : null;
if (metricId) {
drawBodyMetricsGraph(canvas, clientId, metricId);
}
}
};
// Первичная отрисовка (пустые состояния)
DashboardLogic.updateExerciseChart();
if(state.metricTypes.length > 0) {
document.getElementById('dash-metric-select').value = state.metricTypes[0].id;
DashboardLogic.updateBodyChart();
}
}
function getUniqueExercises() {
const set = new Set();
state.workouts.forEach(w => {
w.exercises.forEach(ex => {
set.add(ex.name);
});
});
return Array.from(set).sort();
}
+381
View File
@@ -0,0 +1,381 @@
// frontend/js/render/dashboard.js
import { state } from '../state.js';
import { formatDate } from '../utils.js';
/**
* Рисует линейный график прогресса упражнения
* @param {HTMLCanvasElement} canvas
* @param {string} exerciseName
*/
export function drawExerciseProgress(canvas, exerciseName) {
const ctx = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;
ctx.clearRect(0, 0, width, height);
const history = getCumulativeExerciseHistory(exerciseName);
if (history.length < 2) {
drawEmptyState(ctx, width, height, "Недостаточно данных\nНужно минимум 2 тренировки");
return;
}
// Находим максимальный ИТОГОВЫЙ объем для масштабирования оси Y
const maxVolume = Math.max(...history.map(h => h.totalVolume));
const padding = { top: 20, right: 20, bottom: 30, left: 40 };
const chartW = width - padding.left - padding.right;
const chartH = height - padding.top - padding.bottom;
// Рисуем сетку (используем maxVolume для оси Y)
drawGridAndAxes(ctx, padding, chartW, chartH, maxVolume, 'Дата', 'Общий вес (кг)');
// Рисуем новый график со стеком
drawCumulativeVolumeChart(ctx, history, padding, chartW, chartH, maxVolume);
// Легенда (обновленная)
drawLegend(ctx, width, [
{ color: '#bb86fc', label: 'Итоговый объем' },
{ color: 'rgba(187, 134, 252, 0.4)', label: 'Накопление по подходам' }
]);
}
/**
* Рисует график динамики телесных замеров
* @param {HTMLCanvasElement} canvas
* @param {number|null} clientId - null для личных замеров
* @param {number} metricTypeId - ID типа замера (например, вес)
*/
export function drawBodyMetricsGraph(canvas, clientId, metricTypeId) {
const ctx = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;
ctx.clearRect(0, 0, width, height);
// Фильтруем замеры
const metrics = state.bodyMetrics
.filter(m => m.client_id == clientId)
.sort((a, b) => new Date(a.date) - new Date(b.date));
// Извлекаем значения конкретного типа
const dataPoints = [];
metrics.forEach(m => {
const valObj = m.values?.find(v => v.metric_type_id == metricTypeId);
if (valObj && valObj.value !== undefined && valObj.value !== null) {
dataPoints.push({ date: new Date(m.date), value: parseFloat(valObj.value) });
}
});
if (dataPoints.length < 2) {
drawEmptyState(ctx, width, height, "Недостаточно данных\nНужно минимум 2 замера");
return;
}
const minVal = Math.min(...dataPoints.map(p => p.value));
const maxVal = Math.max(...dataPoints.map(p => p.value));
const range = maxVal - minVal || 1; // Защита от деления на ноль
const padding = { top: 20, right: 20, bottom: 30, left: 40 };
const chartW = width - padding.left - padding.right;
const chartH = height - padding.top - padding.bottom;
// Простая ось Y (значения)
ctx.strokeStyle = '#333';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(padding.left, padding.top);
ctx.lineTo(padding.left, height - padding.bottom);
ctx.stroke();
// Подписи осей Y
ctx.fillStyle = '#b0b0b0';
ctx.font = '10px sans-serif';
ctx.textAlign = 'right';
for (let i = 0; i <= 4; i++) {
const y = height - padding.bottom - (i / 4) * chartH;
const val = minVal + (range * i / 4);
ctx.fillText(val.toFixed(1), padding.left - 5, y + 3);
// Горизонтальная линия сетки
ctx.strokeStyle = '#2c2c2c';
ctx.beginPath();
ctx.moveTo(padding.left, y);
ctx.lineTo(width - padding.right, y);
ctx.stroke();
}
// Рисуем точку начала и конца по X (дата)
const firstDate = dataPoints[0].date.getTime();
const lastDate = dataPoints[dataPoints.length - 1].date.getTime();
const timeRange = lastDate - firstDate || 1;
ctx.strokeStyle = '#bb86fc'; // Цвет линии графика
ctx.lineWidth = 2;
ctx.beginPath();
dataPoints.forEach((p, index) => {
const x = padding.left + ((p.date.getTime() - firstDate) / timeRange) * chartW;
const y = height - padding.bottom - ((p.value - minVal) / range) * chartH;
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
// Точки
ctx.fillStyle = '#fff';
ctx.fillRect(x - 2, y - 2, 4, 4);
});
ctx.stroke();
// Подпись даты слева и справа
ctx.fillStyle = '#b0b0b0';
ctx.textAlign = 'left';
ctx.fillText(formatShortDate(dataPoints[0].date.toISOString()), padding.left, height - 10);
ctx.textAlign = 'right';
ctx.fillText(formatShortDate(dataPoints[dataPoints.length-1].date.toISOString()), width - padding.right, height - 10);
}
/**
* Собирает историю с накопительным весом по каждому подходу
*/
function getCumulativeExerciseHistory(name) {
const normalized = name.trim().toLowerCase();
const history = [];
state.workouts.forEach(w => {
w.exercises.forEach(ex => {
if (ex.name.trim().toLowerCase() === normalized && ex.sets.length > 0) {
let currentCumulativeWeight = 0;
const cumulativePoints = [];
ex.sets.forEach(s => {
// Учитываем вес подхода (для дроп-сетов можно брать средний или максимальный, здесь берем основной)
const setWeight = s.isDropset && s.subSets
? Math.max(...s.subSets.map(ss => ss.weight))
: s.weight;
// Объем подхода = вес * повторения (или просто вес, если вы считаете тоннаж)
// В вашем примере (15, 30, 45, 60) вы суммируете именно вес подходов.
// Если нужно суммировать тоннаж (вес * повторы), замените на: setWeight * s.reps
const volume = setWeight * s.reps;
currentCumulativeWeight += volume;
cumulativePoints.push(currentCumulativeWeight);
});
history.push({
date: new Date(w.startTime),
cumulativePoints: cumulativePoints, // [15, 30, 45, 60]
totalVolume: currentCumulativeWeight // 60
});
}
});
});
history.sort((a, b) => a.date - b.date);
return history.slice(-10); // Последние 10 тренировок
}
// --- Вспомогательные функции ---
function getExerciseHistoryData(name) {
const normalized = name.trim().toLowerCase();
const history = [];
// Собираем из всех тренировок текущего пользователя (или клиента, если режим тренера реализован глобально)
// Здесь упрощение: берем все тренировки из state.workouts
state.workouts.forEach(w => {
w.exercises.forEach(ex => {
if (ex.name.trim().toLowerCase() === normalized && ex.sets.length > 0) {
history.push({
date: new Date(w.startTime),
sets: ex.sets
});
}
});
});
// Сортируем по дате
history.sort((a, b) => a.date - b.date);
return history.slice(-10); // Берем последние 10 тренировок для читаемости
}
function getMaxWeightInSet(historyItem) {
let max = 0;
historyItem.sets.forEach(s => {
if (s.isDropset && s.subSets) {
s.subSets.forEach(ss => { if (ss.weight > max) max = ss.weight; });
} else if (s.weight > max) {
max = s.weight;
}
});
return max;
}
function getMaxRepsInSet(historyItem) {
let max = 0;
historyItem.sets.forEach(s => {
if (s.isDropset && s.subSets) {
s.subSets.forEach(ss => { if (ss.reps > max) max = ss.reps; });
} else if (s.reps > max) {
max = s.reps;
}
});
return max;
}
function drawGridAndAxes(ctx, pad, cw, ch, maxY, maxXAxisLabel, yAxisLabel) {
ctx.strokeStyle = '#333';
ctx.lineWidth = 1;
// Ось Y
ctx.beginPath();
ctx.moveTo(pad.left, pad.top);
ctx.lineTo(pad.left, ch + pad.top);
ctx.stroke();
// Ось X
ctx.beginPath();
ctx.moveTo(pad.left, ch + pad.top);
ctx.lineTo(cw + pad.left, ch + pad.top);
ctx.stroke();
// Подписи Y
ctx.fillStyle = '#b0b0b0';
ctx.font = '10px sans-serif';
ctx.textAlign = 'right';
for(let i=0; i<=4; i++) {
const val = (maxY * i / 4).toFixed(0);
const y = ch + pad.top - (ch * i / 4);
ctx.fillText(val, pad.left - 5, y + 3);
// Сетка
ctx.strokeStyle = '#2c2c2c';
ctx.beginPath();
ctx.moveTo(pad.left, y);
ctx.lineTo(cw + pad.left, y);
ctx.stroke();
}
// Заголовок оси Y
ctx.save();
ctx.translate(15, ch/2 + pad.top);
ctx.rotate(-Math.PI/2);
ctx.textAlign = 'center';
ctx.fillText(yAxisLabel, 0, 0);
ctx.restore();
}
function drawLineChart(ctx, data, pad, cw, ch, maxY, getValueFn, color, lineWidth) {
if (!data.length) return;
ctx.strokeStyle = color;
ctx.lineWidth = lineWidth;
ctx.beginPath();
data.forEach((item, index) => {
const val = getValueFn(item);
const x = pad.left + (index / (data.length - 1)) * cw;
const y = pad.top + ch - (val / maxY) * ch;
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
// Точка
ctx.fillStyle = '#fff';
ctx.fillRect(x-2, y-2, 4, 4);
});
ctx.stroke();
}
/**
* Рисует график прогресса с вертикальным стеком накопительного веса
*/
function drawCumulativeVolumeChart(ctx, data, pad, cw, ch, maxY) {
if (!data.length) return;
// 1. Сначала рисуем соединительную линию для ОБЩИХ итогов (тренд)
ctx.strokeStyle = '#bb86fc'; // Основной цвет (например, фиолетовый)
ctx.lineWidth = 2;
ctx.beginPath();
data.forEach((item, index) => {
const x = pad.left + (index / (data.length - 1 || 1)) * cw;
const y = pad.top + ch - (item.totalVolume / maxY) * ch;
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
// 2. Рисуем вертикальные стеки точек для каждой даты
data.forEach((item, index) => {
const x = pad.left + (index / (data.length - 1 || 1)) * cw;
item.cumulativePoints.forEach((cumWeight, pointIndex) => {
const isLast = pointIndex === item.cumulativePoints.length - 1;
const y = pad.top + ch - (cumWeight / maxY) * ch;
ctx.beginPath();
if (isLast) {
// Финальная точка: крупная, непрозрачная, с белой обводкой для контраста
ctx.fillStyle = '#bb86fc';
ctx.arc(x, y, 5, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = '#ffffff';
ctx.lineWidth = 1.5;
ctx.stroke();
} else {
// Промежуточные точки: полупрозрачные, поменьше
ctx.fillStyle = 'rgba(187, 134, 252, 0.4)'; // Тот же цвет, но 40% непрозрачности
ctx.arc(x, y, 3, 0, Math.PI * 2);
ctx.fill();
}
});
// Опционально: провести бледную вертикальную линию от 0 до итоговой точки,
// чтобы визуально связать подходы в один "столбик"
if (item.cumulativePoints.length > 1) {
const bottomY = pad.top + ch; // Ось X
const topY = pad.top + ch - (item.totalVolume / maxY) * ch;
ctx.strokeStyle = 'rgba(187, 134, 252, 0.15)';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(x, bottomY);
ctx.lineTo(x, topY);
ctx.stroke();
}
});
}
function drawLegend(ctx, width, items) {
ctx.font = '10px sans-serif';
ctx.textAlign = 'left';
let xOffset = 10;
items.forEach(item => {
ctx.fillStyle = item.color;
ctx.fillRect(xOffset, 10, 10, 10);
ctx.fillStyle = '#fff';
ctx.fillText(item.label, xOffset + 15, 19);
xOffset += ctx.measureText(item.label).width + 30;
});
}
function drawEmptyState(ctx, w, h, text) {
ctx.fillStyle = '#666';
ctx.font = '14px sans-serif';
ctx.textAlign = 'center';
const lines = text.split('\n');
lines.forEach((line, i) => {
ctx.fillText(line, w/2, h/2 + (i * 20) - (lines.length*10)/2);
});
}
function formatShortDate(isoString) {
return new Date(isoString).toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit' });
}
+124 -45
View File
@@ -1,60 +1,118 @@
const STORAGE_KEY = 'gym_tracker_v6'; // frontend/js/state.js
// Палитра из 16 контрастных цветов для клиентов const CURRENT_STORAGE_PREFIX = "gym_tracker_v7_user_";
export const CLIENT_COLORS = [ const GUEST_STORAGE_KEY = "gym_tracker_v7_guest";
'#bb86fc', // фиолетовый (дефолтный для личного режима)
'#03dac6', // бирюзовый const LEGACY_KEYS = [
'#fbbc04', // жёлтый "gym_tracker_v6",
'#cf6679', // розовый "gym_tracker_v5",
'#64b5f6', // голубой "gym_tracker_v4",
'#81c784', // зелёный
'#ffb74d', // оранжевый
'#ba68c8', // светло-фиолетовый
'#4dd0e1', // циан
'#e57373', // красный
'#aed581', // салатовый
'#ffd54f', // янтарный
'#9575cd', // пурпурный
'#4db6ac', // тиловый
'#f06292', // малиновый
'#7986cb', // индиго
]; ];
export const DEFAULT_COLOR = CLIENT_COLORS[0]; const MIGRATION_FLAG = "gym_tracker_legacy_migrated_to_user";
export const state = { function freshState() {
return {
workouts: [], workouts: [],
exerciseRef: [], exerciseRef: [],
bodyMetrics: [], bodyMetrics: [],
workoutTypes: [], workoutTypes: [],
metricTypes: [], metricTypes: [],
clients: [], // каждый клиент: {id, sync_id, full_name, birth_date, goal, color} clients: [],
expandedWorkoutId: null, expandedWorkoutId: null,
expandedExerciseId: null, expandedExerciseId: null,
nextId: 1, nextId: 1,
mode: 'personal', mode: "personal",
currentClientId: null, // больше не используется глобально, но оставим для совместимости currentClientId: null,
}; };
}
export const state = freshState();
// Внутренняя переменная для хранения текущего пользователя (не сохраняется в localStorage напрямую)
let activeUser = null;
/**
* Установить текущего пользователя после логина
*/
export function setActiveUser(user) {
activeUser = user;
}
/**
* Получить данные текущего пользователя
*/
export function getActiveUser() {
return activeUser;
}
/**
* Сбросить состояние при логауте
*/
export function resetState() {
Object.assign(state, freshState());
activeUser = null;
}
function storageKey() {
return activeUser
? `${CURRENT_STORAGE_PREFIX}${activeUser.id}`
: GUEST_STORAGE_KEY;
}
export function migrateLegacyStateForUser() {
if (!activeUser) return;
// Уже мигрировали — не трогаем
if (localStorage.getItem(MIGRATION_FLAG)) return;
const key = storageKey();
// Если у пользователя уже есть данные — просто помечаем миграцию выполненной
if (localStorage.getItem(key)) {
localStorage.setItem(MIGRATION_FLAG, String(activeUser.id));
return;
}
// Ищем старые данные и переносим первому вошедшему пользователю
for (const legacyKey of LEGACY_KEYS) {
const raw = localStorage.getItem(legacyKey);
if (raw) {
localStorage.setItem(key, raw);
localStorage.setItem(MIGRATION_FLAG, String(activeUser.id));
return;
}
}
}
export function loadState() { export function loadState() {
const saved = localStorage.getItem(STORAGE_KEY); migrateLegacyStateForUser();
if (saved) {
const raw = localStorage.getItem(storageKey());
Object.assign(state, freshState());
if (raw) {
try { try {
const parsed = JSON.parse(saved); const parsed = JSON.parse(raw);
// Объединяем, чтобы не потерять новые поля при обновлении версии
Object.assign(state, parsed); Object.assign(state, parsed);
if (!state.workoutTypes) state.workoutTypes = [];
if (!state.metricTypes) state.metricTypes = [];
if (!state.clients) state.clients = [];
if (!state.mode) state.mode = 'personal';
normalizeWorkouts();
} catch (e) { } catch (e) {
console.error('Failed to load state', e); console.error("Failed to load state", e);
} }
} }
if (!Array.isArray(state.workouts)) state.workouts = [];
if (!Array.isArray(state.exerciseRef)) state.exerciseRef = [];
if (!Array.isArray(state.bodyMetrics)) state.bodyMetrics = [];
if (!Array.isArray(state.workoutTypes)) state.workoutTypes = [];
if (!Array.isArray(state.metricTypes)) state.metricTypes = [];
if (!Array.isArray(state.clients)) state.clients = [];
if (!state.mode) state.mode = "personal";
normalizeWorkouts();
} }
// Допиваем поля, которых может не быть в сохранении старой версии // Допиваем поля, которых может не быть в сохранении старой версии
@@ -70,7 +128,7 @@ function normalizeWorkouts() {
} }
export function saveState() { export function saveState() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(state)); localStorage.setItem(storageKey(), JSON.stringify(state));
updateSyncStatus(); updateSyncStatus();
} }
@@ -78,24 +136,45 @@ export function genId() {
return (state.nextId++).toString(); return (state.nextId++).toString();
} }
// Генерация UUID v4 для sync_id (идемпотентность на бэкенде)
export function generateUUID() { export function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0; const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8); const v = c === "x" ? r : (r & 0x3) | 0x8;
return v.toString(16); return v.toString(16);
}); });
} }
export function updateSyncStatus() { export function updateSyncStatus() {
const dirty = state.workouts.filter(w => !w.synced); const dirty = state.workouts.filter((w) => !w.synced);
const el = document.getElementById('sync-status'); const el = document.getElementById("sync-status");
if (!el) return; if (!el) return;
if (dirty.length === 0) { if (dirty.length === 0) {
el.textContent = '● Всё синхронизировано'; el.textContent = "● Всё синхронизировано";
el.className = 'sync-status synced'; el.className = "sync-status synced";
} else { } else {
el.textContent = `● ${dirty.length} не сохран.`; el.textContent = `● ${dirty.length} не сохран.`;
el.className = 'sync-status pending'; el.className = "sync-status pending";
} }
} }
export const CLIENT_COLORS = [
"#bb86fc",
"#03dac6",
"#fbbc04",
"#cf6679",
"#64b5f6",
"#81c784",
"#ffb74d",
"#ba68c8",
"#4dd0e1",
"#e57373",
"#aed581",
"#ffd54f",
"#9575cd",
"#4db6ac",
"#f06292",
"#7986cb",
];
export const DEFAULT_COLOR = CLIENT_COLORS[0];
+687 -70
View File
@@ -1,23 +1,37 @@
import { state, saveState, generateUUID } from "./state.js"; // frontend/js/sync.js
import { syncData } from "./api.js";
import { state, saveState, generateUUID, DEFAULT_COLOR } from "./state.js";
import {
fetchBootstrapData,
fetchWorkoutTypes,
fetchMetricTypes,
syncData,
} from "./api.js";
import { renderMainScreen } from "./render/main-screen.js"; import { renderMainScreen } from "./render/main-screen.js";
export async function initAppData() { // ============================================================
try { // Хелперы
const { fetchWorkoutTypes, fetchMetricTypes } = await import("./api.js"); // ============================================================
state.workoutTypes = await fetchWorkoutTypes(); function asString(value) {
state.metricTypes = await fetchMetricTypes(); if (value === undefined || value === null) return "";
saveState(); return String(value);
console.log("Справочники загружены с бэкенда");
} catch (e) {
console.warn("Не удалось загрузить справочники (возможно, бэк недоступен):", e);
}
} }
export function getDirtyWorkouts() { function normalizeName(value) {
return state.workouts.filter((w) => !w.synced); return String(value || "").trim().toLowerCase();
}
function toNumberOrNull(value) {
if (value === "" || value === null || value === undefined) return null;
const n = Number(value);
return Number.isFinite(n) ? n : null;
}
function toIntOrNull(value) {
if (value === "" || value === null || value === undefined) return null;
const n = Number(value);
return Number.isFinite(n) ? Math.trunc(n) : null;
} }
function ensureSyncId(obj) { function ensureSyncId(obj) {
@@ -28,32 +42,574 @@ function ensureSyncId(obj) {
return obj.sync_id; return obj.sync_id;
} }
// ============================================================
// Миграция локальных ID в sync_id
// ============================================================
/**
* Делает локальные ID совместимыми с серверными sync_id.
*
* Важно:
* - тренировки, упражнения, подходы, кардио, замеры, справочник упражнений
* переводим на sync_id как основной локальный id;
* - клиенты остаются с числовым server_id, если он есть, потому что
* API клиентов использует /clients/{id} с числовым id.
*/
function migrateLocalIdsToSyncId() {
const clientOldToNew = new Map();
// Клиенты
for (const client of state.clients || []) {
const oldId = asString(client.id);
if (!client.sync_id) {
client.sync_id = generateUUID();
}
// Если клиент уже синхронизирован, используем серверный числовой id
if (client.server_id) {
client.id = asString(client.server_id);
} else if (!client.id) {
client.id = asString(client.sync_id);
}
const newId = asString(client.id);
if (oldId && newId && oldId !== newId) {
clientOldToNew.set(oldId, newId);
}
}
// Тренировки
for (const workout of state.workouts || []) {
const oldClientKey = asString(workout.client_id);
if (oldClientKey && clientOldToNew.has(oldClientKey)) {
workout.client_id = clientOldToNew.get(oldClientKey);
}
if (!workout.sync_id) {
workout.sync_id = generateUUID();
}
const oldWorkoutId = asString(workout.id);
const newWorkoutId = asString(workout.sync_id);
workout.id = newWorkoutId;
if (asString(state.expandedWorkoutId) === oldWorkoutId) {
state.expandedWorkoutId = newWorkoutId;
}
for (const exercise of workout.exercises || []) {
if (!exercise.sync_id) {
exercise.sync_id = generateUUID();
}
const oldExerciseId = asString(exercise.id);
const newExerciseId = asString(exercise.sync_id);
exercise.id = newExerciseId;
if (asString(state.expandedExerciseId) === oldExerciseId) {
state.expandedExerciseId = newExerciseId;
}
for (const set of exercise.sets || []) {
if (!set.sync_id) {
set.sync_id = generateUUID();
}
set.id = asString(set.sync_id);
}
}
for (const cardio of workout.cardio || []) {
if (!cardio.sync_id) {
cardio.sync_id = generateUUID();
}
cardio.id = asString(cardio.sync_id);
}
}
// Замеры
for (const metric of state.bodyMetrics || []) {
const oldClientKey = asString(metric.client_id);
if (oldClientKey && clientOldToNew.has(oldClientKey)) {
metric.client_id = clientOldToNew.get(oldClientKey);
}
if (!metric.sync_id) {
metric.sync_id = generateUUID();
}
metric.id = asString(metric.sync_id);
}
// Справочник упражнений
for (const exercise of state.exerciseRef || []) {
if (!exercise.sync_id) {
exercise.sync_id = generateUUID();
}
exercise.id = asString(exercise.sync_id);
}
}
// ============================================================
// Конвертация backend -> frontend
// ============================================================
function convertBackendClient(c) {
const syncId = c.sync_id || generateUUID();
const serverId = asString(c.id);
return {
id: serverId || syncId,
sync_id: syncId,
server_id: serverId || null,
full_name: c.full_name || "",
birth_date: c.birth_date || "",
goal: c.goal || "",
notes: c.notes || "",
color: c.color || DEFAULT_COLOR,
is_active: c.is_active ?? 1,
};
}
function convertBackendExercise(e, workoutTypeNameById) {
const syncId = e.sync_id || generateUUID();
return {
id: syncId,
sync_id: syncId,
server_id: e.id ?? null,
name: e.name || "",
workoutType: e.workout_type_id
? workoutTypeNameById[asString(e.workout_type_id)] || ""
: "",
};
}
function convertBackendWorkoutToFrontend(w) {
const workoutSyncId = w.sync_id || generateUUID();
// Используем подготовленное имя типа из бэкенда, если оно есть, иначе ищем по ID
let typeStr = w.workout_type_name;
if (!typeStr && w.workout_type_id) {
const wt = state.workoutTypes.find(t => String(t.id) === String(w.workout_type_id));
typeStr = wt ? wt.name : "";
}
return {
id: workoutSyncId,
sync_id: workoutSyncId,
server_id: w.id ?? null,
client_id: w.client_id ? asString(w.client_id) : null,
startTime: w.start_time || new Date().toISOString(),
endTime: w.end_time || null,
type: typeStr || "", // Имя типа тренировки
notes: w.notes || "",
synced: true,
exercises: (w.workout_exercises || []).map((ex) => {
const exSyncId = ex.sync_id || generateUUID();
return {
id: exSyncId,
sync_id: exSyncId,
server_id: ex.id ?? null,
exercise_id: ex.exercise_id ?? null,
name: ex.exercise_name || "",
sort_order: ex.sort_order ?? 0,
sets: (ex.sets || []).map((s) => {
const setSyncId = s.sync_id || generateUUID();
return {
id: setSyncId,
sync_id: setSyncId,
server_id: s.id ?? null,
isDropset: !!s.is_dropset,
weight: s.weight ?? null,
reps: s.reps ?? null,
rating: s.rating ?? 5,
notes: s.notes || "",
timestamp: s.timestamp || w.start_time || new Date().toISOString(),
sort_order: s.sort_order ?? 0,
subSets: (s.dropset_items || []).map((di) => ({
weight: di.weight ?? 0,
reps: di.reps ?? 0,
sort_order: di.sort_order ?? 0,
})),
};
}),
};
}),
cardio: (w.cardio_sessions || []).map((c) => {
const cardioSyncId = c.sync_id || generateUUID();
return {
id: cardioSyncId,
sync_id: cardioSyncId,
server_id: c.id ?? null,
type: c.cardio_type || "",
purpose: c.purpose || "separate",
duration: c.duration ?? null,
distance: c.distance ?? null,
speed: c.speed ?? null,
incline: c.incline ?? null,
resistance: c.resistance ?? null,
notes: c.notes || "",
sort_order: c.sort_order ?? 0,
};
}),
};
}
function convertBackendWorkout(w, workoutTypeNameById) {
const workoutSyncId = w.sync_id || generateUUID();
return {
id: workoutSyncId,
sync_id: workoutSyncId,
server_id: w.id ?? null,
client_id: w.client_id ? asString(w.client_id) : null,
startTime: w.start_time || new Date().toISOString(),
endTime: w.end_time || null,
type: w.workout_type_id
? workoutTypeNameById[asString(w.workout_type_id)] || ""
: "",
notes: w.notes || "",
synced: true,
exercises: (w.workout_exercises || []).map((ex) => {
const exSyncId = ex.sync_id || generateUUID();
return {
id: exSyncId,
sync_id: exSyncId,
server_id: ex.id ?? null,
exercise_id: ex.exercise_id ?? null,
name: ex.exercise_name || "",
sort_order: ex.sort_order ?? 0,
sets: (ex.sets || []).map((s) => {
const setSyncId = s.sync_id || generateUUID();
return {
id: setSyncId,
sync_id: setSyncId,
server_id: s.id ?? null,
isDropset: !!s.is_dropset,
weight: s.weight ?? null,
reps: s.reps ?? null,
rating: s.rating ?? 5,
notes: s.notes || "",
timestamp: s.timestamp || w.start_time || new Date().toISOString(),
sort_order: s.sort_order ?? 0,
subSets: (s.dropset_items || []).map((di) => ({
weight: di.weight ?? 0,
reps: di.reps ?? 0,
sort_order: di.sort_order ?? 0,
})),
};
}),
};
}),
cardio: (w.cardio_sessions || []).map((c) => {
const cardioSyncId = c.sync_id || generateUUID();
return {
id: cardioSyncId,
sync_id: cardioSyncId,
server_id: c.id ?? null,
type: c.cardio_type || "",
purpose: c.purpose || "separate",
duration: c.duration ?? null,
distance: c.distance ?? null,
speed: c.speed ?? null,
incline: c.incline ?? null,
resistance: c.resistance ?? null,
notes: c.notes || "",
sort_order: c.sort_order ?? 0,
};
}),
};
}
function convertBackendMetric(m) {
const metricSyncId = m.sync_id || generateUUID();
return {
id: metricSyncId,
sync_id: metricSyncId,
server_id: m.id ?? null,
client_id: m.client_id ? asString(m.client_id) : null,
date: m.metric_date || new Date().toISOString(),
notes: m.notes || "",
values: (m.values || []).map((v) => ({
metric_type_id: v.metric_type_id,
value: v.value,
})),
};
}
// ============================================================
// Merge локальных и серверных данных
// ============================================================
function mergeBySyncId(localItems, serverItems, options = {}) {
const map = new Map();
// Сначала серверные данные
for (const item of serverItems || []) {
const key = item?.sync_id;
if (key) {
map.set(key, item);
}
}
// Потом локальные
for (const item of localItems || []) {
const key = item?.sync_id;
if (!key) {
// На всякий случай: если вдруг нет sync_id, сохраняем локальное по id
map.set(`local:${item?.id}`, item);
continue;
}
const shouldKeepLocal =
options.localWinsIfDirty && item.synced === false;
if (shouldKeepLocal) {
// Несинхронизированная локальная тренировка важнее серверной копии
map.set(key, item);
} else if (!map.has(key)) {
map.set(key, item);
}
}
return Array.from(map.values());
}
function mergeClients(localItems, serverItems) {
// 1. Merge по sync_id
const bySync = new Map();
for (const item of serverItems || []) {
if (item?.sync_id) {
bySync.set(item.sync_id, item);
}
}
for (const item of localItems || []) {
if (!item?.sync_id) continue;
// Серверный клиент важнее локального с тем же sync_id
if (!bySync.has(item.sync_id)) {
bySync.set(item.sync_id, item);
}
}
// 2. Deduplicate по id, чтобы не было двух клиентов с одним числовым id
const byId = new Map();
for (const item of bySync.values()) {
const id = asString(item.id);
if (!id) continue;
const existing = byId.get(id);
if (!existing) {
byId.set(id, item);
} else if (item.server_id && !existing.server_id) {
// Серверный клиент побеждает локальный при конфликте id
byId.set(id, item);
}
}
return Array.from(byId.values());
}
function mergeExerciseRef(localItems, serverItems) {
// Справочник упражнений лучше мержить по имени,
// иначе могут появиться дубли "Жим лежа" с разными sync_id.
const map = new Map();
for (const item of serverItems || []) {
const key = normalizeName(item.name);
if (key) {
map.set(key, item);
}
}
for (const item of localItems || []) {
const key = normalizeName(item.name);
if (key && !map.has(key)) {
map.set(key, item);
}
}
return Array.from(map.values()).sort((a, b) =>
String(a.name || "").localeCompare(String(b.name || ""))
);
}
function resolveClientId(rawId, clients) {
const key = asString(rawId);
if (!key) return null;
// Ищем по id
const byId = (clients || []).find((c) => asString(c.id) === key);
if (byId) return asString(byId.id);
// Ищем по sync_id
const bySync = (clients || []).find((c) => asString(c.sync_id) === key);
if (bySync) return asString(bySync.id);
// Если не нашли — оставляем как есть
return key;
}
function reconcileClientReferences() {
for (const workout of state.workouts || []) {
workout.client_id = resolveClientId(workout.client_id, state.clients);
}
for (const metric of state.bodyMetrics || []) {
metric.client_id = resolveClientId(metric.client_id, state.clients);
}
}
// ============================================================
// Загрузка данных пользователя с сервера
// ============================================================
export async function initAppData() {
try {
console.log("🔄 Загружаем bootstrap-данные с сервера...");
const data = await fetchBootstrapData();
// Сначала нормализуем локальные ID, чтобы корректно смержить
migrateLocalIdsToSyncId();
// Справочники
state.workoutTypes = Array.isArray(data.workout_types)
? data.workout_types
: [];
state.metricTypes = Array.isArray(data.metric_types)
? data.metric_types
: [];
const workoutTypeNameById = {};
for (const wt of state.workoutTypes || []) {
workoutTypeNameById[asString(wt.id)] = wt.name;
}
// Клиенты
const serverClients = (data.clients || []).map(convertBackendClient);
state.clients = mergeClients(state.clients || [], serverClients);
// Упражнения / справочник
const serverExercises = (data.exercises || []).map((e) =>
convertBackendExercise(e, workoutTypeNameById)
);
state.exerciseRef = mergeExerciseRef(
state.exerciseRef || [],
serverExercises
);
// Тренировки
const serverWorkouts = (data.workouts || []).map((w) =>
convertBackendWorkout(w, workoutTypeNameById)
);
state.workouts = mergeBySyncId(
state.workouts || [],
serverWorkouts,
{ localWinsIfDirty: true }
);
// Замеры
const serverMetrics = (data.body_metrics || []).map(convertBackendMetric);
state.bodyMetrics = mergeBySyncId(
state.bodyMetrics || [],
serverMetrics
);
// Чиним ссылки на клиентов после merge
reconcileClientReferences();
saveState();
renderMainScreen();
console.log(
`✅ Bootstrap загружен: тренировок ${state.workouts.length}, клиентов ${state.clients.length}, замеров ${state.bodyMetrics.length}`
);
} catch (e) {
console.warn("❌ Bootstrap не удался, пробуем загрузить только справочники:", e);
try {
const [workoutTypes, metricTypes] = await Promise.all([
fetchWorkoutTypes(),
fetchMetricTypes(),
]);
state.workoutTypes = Array.isArray(workoutTypes) ? workoutTypes : [];
state.metricTypes = Array.isArray(metricTypes) ? metricTypes : [];
saveState();
renderMainScreen();
console.log("✅ Справочники загружены отдельно");
} catch (e2) {
console.warn("❌ Не удалось загрузить даже справочники:", e2);
if (!Array.isArray(state.workoutTypes)) state.workoutTypes = [];
if (!Array.isArray(state.metricTypes)) state.metricTypes = [];
}
}
}
// ============================================================
// Синхронизация frontend -> backend
// ============================================================
export function getDirtyWorkouts() {
return state.workouts.filter((w) => !w.synced);
}
function findWorkoutTypeByName(name) { function findWorkoutTypeByName(name) {
if (!name) return null; if (!name) return null;
return state.workoutTypes.find((t) => t.name === name) || null; return state.workoutTypes.find((t) => t.name === name) || null;
} }
function findExerciseRefByName(name) { function findExerciseRefByName(name) {
const normalized = String(name || "").trim().toLowerCase(); const normalized = normalizeName(name);
if (!normalized) return null; if (!normalized) return null;
return ( return (
state.exerciseRef.find( state.exerciseRef.find(
(e) => String(e.name || "").trim().toLowerCase() === normalized (e) => normalizeName(e.name) === normalized
) || null ) || null
); );
} }
function findClientByLocalId(clientId) { function findClientByLocalId(clientId) {
if (clientId === undefined || clientId === null || clientId === "") return null; const key = asString(clientId);
if (!key) return null;
return ( return (
state.clients.find((c) => String(c.id) === String(clientId)) || null state.clients.find(
(c) => asString(c.id) === key || asString(c.sync_id) === key
) || null
); );
} }
function buildClientsPayload() { function buildClientsPayload() {
return state.clients.map((c) => { return (state.clients || []).map((c) => {
ensureSyncId(c); ensureSyncId(c);
return { return {
@@ -69,7 +625,7 @@ function buildClientsPayload() {
} }
function buildExercisesPayload() { function buildExercisesPayload() {
return state.exerciseRef.map((e) => { return (state.exerciseRef || []).map((e) => {
ensureSyncId(e); ensureSyncId(e);
const wt = findWorkoutTypeByName(e.workoutType); const wt = findWorkoutTypeByName(e.workoutType);
@@ -91,18 +647,21 @@ function buildSetsPayload(sets) {
return { return {
sync_id: s.sync_id, sync_id: s.sync_id,
is_dropset: isDropset ? 1 : 0, is_dropset: isDropset ? 1 : 0,
weight: isDropset ? null : (parseFloat(s.weight) || null), weight: isDropset ? null : toNumberOrNull(s.weight),
reps: isDropset ? null : (parseInt(s.reps, 10) || null), reps: isDropset ? null : toIntOrNull(s.reps),
rating: s.rating || 5, rating: toIntOrNull(s.rating) ?? 5,
notes: s.notes || "", notes: s.notes || "",
sort_order: s.sort_order ?? setIndex, sort_order: s.sort_order ?? setIndex,
timestamp: s.timestamp || new Date().toISOString(), timestamp: s.timestamp || new Date().toISOString(),
dropset_items: isDropset dropset_items: isDropset
? (s.subSets || []).map((item, itemIndex) => ({ ? (s.subSets || [])
weight: parseFloat(item.weight) || 0, .map((item, itemIndex) => ({
reps: parseInt(item.reps, 10) || 0, weight: toNumberOrNull(item.weight) ?? 0,
reps: toIntOrNull(item.reps) ?? 0,
sort_order: item.sort_order ?? itemIndex, sort_order: item.sort_order ?? itemIndex,
})) }))
.filter((item) => item.weight > 0 && item.reps > 0)
: [], : [],
}; };
}); });
@@ -117,7 +676,7 @@ function buildWorkoutExercisesPayload(exercises) {
return { return {
sync_id: ex.sync_id, sync_id: ex.sync_id,
exercise_sync_id: exerciseRef ? exerciseRef.sync_id : null, exercise_sync_id: exerciseRef ? exerciseRef.sync_id : null,
exercise_id: ex.exercise_id || null, exercise_id: ex.exercise_id || ex.server_id || null,
exercise_name: ex.name, exercise_name: ex.name,
sort_order: ex.sort_order ?? exIndex, sort_order: ex.sort_order ?? exIndex,
sets: buildSetsPayload(ex.sets), sets: buildSetsPayload(ex.sets),
@@ -133,11 +692,11 @@ function buildCardioPayload(cardioList) {
sync_id: c.sync_id, sync_id: c.sync_id,
cardio_type: c.type || "другое", cardio_type: c.type || "другое",
purpose: c.purpose || "separate", purpose: c.purpose || "separate",
duration: c.duration || null, duration: toIntOrNull(c.duration),
distance: c.distance || null, distance: toNumberOrNull(c.distance),
speed: c.speed || null, speed: toNumberOrNull(c.speed),
incline: c.incline || null, incline: toNumberOrNull(c.incline),
resistance: c.resistance || null, resistance: toIntOrNull(c.resistance),
notes: c.notes || "", notes: c.notes || "",
sort_order: c.sort_order ?? cIndex, sort_order: c.sort_order ?? cIndex,
}; };
@@ -153,25 +712,32 @@ function buildWorkoutsPayload(dirty) {
return { return {
sync_id: w.sync_id, sync_id: w.sync_id,
// Для клиентов отправляем именно sync_id,
// потому что локальный id может отличаться на разных устройствах.
client_id: null, client_id: null,
client_sync_id: client ? client.sync_id : null, client_sync_id: client ? client.sync_id : null,
workout_type_id: wt ? wt.id : null, workout_type_id: wt ? wt.id : null,
start_time: w.startTime, start_time: w.startTime,
end_time: w.endTime || null, end_time: w.endTime || null,
notes: w.notes || "", notes: w.notes || "",
workout_exercises: buildWorkoutExercisesPayload(w.exercises), workout_exercises: buildWorkoutExercisesPayload(w.exercises),
cardio_sessions: buildCardioPayload(w.cardio), cardio_sessions: buildCardioPayload(w.cardio),
}; };
}); });
} }
export async function sync() { // ... предыдущие импорты и хелперы остаются ...
// Отправляем ВСЕ тренировки, а не только новые: правки, внесённые после
// прошлой синхронизации (в т.ч. во время тренировки), должны уходить на бэкенд.
// Идемпотентность обеспечивает upsert по sync_id.
const all = state.workouts;
if (all.length === 0) { export async function sync() {
// Отправляем все тренировки: правки в уже синхронизированной тренировке
// тоже должны уходить на сервер (upsert по sync_id идемпотентен)
const dirtyWorkouts = state.workouts;
const dirtyMetrics = getDirtyMetrics(); // Новая функция
if (dirtyWorkouts.length === 0 && dirtyMetrics.length === 0) {
alert("Нет данных для синхронизации"); alert("Нет данных для синхронизации");
return; return;
} }
@@ -183,57 +749,42 @@ export async function sync() {
} }
try { try {
// Генерируем sync_id локально и сохраняем, чтобы при повторе не плодить дубли // Генерируем sync_id для всего необходимого
state.clients.forEach(ensureSyncId); ensureSyncIds(dirtyWorkouts, dirtyMetrics);
state.exerciseRef.forEach(ensureSyncId);
all.forEach((w) => {
ensureSyncId(w);
(w.exercises || []).forEach((ex) => {
ensureSyncId(ex);
(ex.sets || []).forEach(ensureSyncId);
});
(w.cardio || []).forEach(ensureSyncId);
});
saveState();
const payload = { const payload = {
clients: buildClientsPayload(), clients: buildClientsPayload(),
exercises: buildExercisesPayload(), exercises: buildExercisesPayload(),
workouts: buildWorkoutsPayload(all), workouts: buildWorkoutsPayload(dirtyWorkouts),
body_metrics: [], // динамические замеры подключим следующим этапом body_metrics: buildMetricsPayload(dirtyMetrics), // Отправляем замеры
}; };
console.log("📤 Отправляем на синхронизацию:", payload); console.log("📤 Sending sync payload:", payload);
const response = await syncData(payload); const response = await syncData(payload);
console.log("✅ Ответ синхронизации:", response); console.log("✅ Sync response:", response);
all.forEach((w) => { // Помечаем все как синхронизированные
w.synced = true; dirtyWorkouts.forEach(w => w.synced = true);
}); dirtyMetrics.forEach(m => m.synced = true);
saveState(); saveState();
if (typeof window.renderMainScreen === "function") { if (typeof window.renderMainScreen === "function") {
window.renderMainScreen(); window.renderMainScreen();
} else {
renderMainScreen();
} }
const createdWorkouts = response.created?.workouts || 0; const createdW = response.created?.workouts || 0;
const updatedWorkouts = response.updated?.workouts || 0; const createdM = response.created?.body_metrics || 0;
const warnings = response.warnings || [];
let message = `Синхронизировано: создано ${createdWorkouts}, обновлено ${updatedWorkouts}`; let message = `Синхронизировано:\nТренировок: ${createdW}\nЗамеров: ${createdM}`;
if (warnings.length) {
message += `\n\nПредупреждения:\n${warnings.join("\n")}`; if (response.warnings?.length) {
message += `\n\nПредупреждения:\n${response.warnings.join("\n")}`;
} }
alert(message); alert(message);
} catch (e) { } catch (e) {
console.error("❌ Sync error:", e); console.error("❌ Sync error:", e);
alert("Ошибка синхронизации: " + e.message); alert("Ошибка синхронизации: " + e.message);
@@ -244,3 +795,69 @@ export async function sync() {
} }
} }
} }
// --- НОВЫЕ ХЕЛПЕРЫ ДЛЯ ЗАМЕРОВ ---
function getDirtyMetrics() {
return state.bodyMetrics.filter(m => !m.synced);
}
function ensureSyncIds(workouts, metrics) {
// Тренировки
workouts.forEach(w => {
if (!w.sync_id) w.sync_id = generateUUID();
(w.exercises || []).forEach(ex => {
if (!ex.sync_id) ex.sync_id = generateUUID();
(ex.sets || []).forEach(s => {
if (!s.sync_id) s.sync_id = generateUUID();
});
});
(w.cardio || []).forEach(c => {
if (!c.sync_id) c.sync_id = generateUUID();
});
});
// Замеры
metrics.forEach(m => {
if (!m.sync_id) m.sync_id = generateUUID();
});
}
function buildMetricsPayload(metrics) {
return metrics.map(m => {
// Ищем server_id клиента, если есть
let clientServerId = null;
if (m.client_id) {
const client = state.clients.find(c => String(c.id) === String(m.client_id));
if (client && client.server_id) {
clientServerId = client.server_id;
} else if (client && client.sync_id) {
// Если нет server_id, но есть sync_id, бэк может найти его по sync_id
// Но в нашей схеме BodyMetricCreate ожидает client_id (int) или client_sync_id (str)?
// Смотрим schemas.py: BodyMetricCreate имеет client_id: Optional[int] и client_sync_id: Optional[str]
// Лучше отправить sync_id, если server_id неизвестен
return {
sync_id: m.sync_id,
client_sync_id: client.sync_id,
metric_date: m.date,
notes: m.notes || "",
values: (m.values || []).map(v => ({
metric_type_id: v.metric_type_id,
value: v.value
}))
};
}
}
return {
sync_id: m.sync_id,
client_id: clientServerId, // Числовой ID, если известен
metric_date: m.date,
notes: m.notes || "",
values: (m.values || []).map(v => ({
metric_type_id: v.metric_type_id,
value: v.value
}))
};
});
}