Files
gym-bro/frontend/js/sync.js

864 lines
26 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// frontend/js/sync.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";
// ============================================================
// Хелперы
// ============================================================
function asString(value) {
if (value === undefined || value === null) return "";
return String(value);
}
function normalizeName(value) {
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) {
if (!obj) return null;
if (!obj.sync_id) {
obj.sync_id = generateUUID();
}
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) {
if (!name) return null;
return state.workoutTypes.find((t) => t.name === name) || null;
}
function findExerciseRefByName(name) {
const normalized = normalizeName(name);
if (!normalized) return null;
return (
state.exerciseRef.find(
(e) => normalizeName(e.name) === normalized
) || null
);
}
function findClientByLocalId(clientId) {
const key = asString(clientId);
if (!key) return null;
return (
state.clients.find(
(c) => asString(c.id) === key || asString(c.sync_id) === key
) || null
);
}
function buildClientsPayload() {
return (state.clients || []).map((c) => {
ensureSyncId(c);
return {
sync_id: c.sync_id,
full_name: c.full_name || "Без имени",
birth_date: c.birth_date || null,
goal: c.goal || "",
notes: c.notes || "",
color: c.color || null,
is_active: c.is_active === undefined ? 1 : c.is_active,
};
});
}
function buildExercisesPayload() {
return (state.exerciseRef || []).map((e) => {
ensureSyncId(e);
const wt = findWorkoutTypeByName(e.workoutType);
return {
sync_id: e.sync_id,
name: e.name,
workout_type_id: wt ? wt.id : null,
};
});
}
function buildSetsPayload(sets) {
return (sets || []).map((s, setIndex) => {
ensureSyncId(s);
const isDropset = !!s.isDropset;
return {
sync_id: s.sync_id,
is_dropset: isDropset ? 1 : 0,
weight: isDropset ? null : toNumberOrNull(s.weight),
reps: isDropset ? null : toIntOrNull(s.reps),
rating: toIntOrNull(s.rating) ?? 5,
notes: s.notes || "",
sort_order: s.sort_order ?? setIndex,
timestamp: s.timestamp || new Date().toISOString(),
dropset_items: isDropset
? (s.subSets || [])
.map((item, itemIndex) => ({
weight: toNumberOrNull(item.weight) ?? 0,
reps: toIntOrNull(item.reps) ?? 0,
sort_order: item.sort_order ?? itemIndex,
}))
.filter((item) => item.weight > 0 && item.reps > 0)
: [],
};
});
}
function buildWorkoutExercisesPayload(exercises) {
return (exercises || []).map((ex, exIndex) => {
ensureSyncId(ex);
const exerciseRef = findExerciseRefByName(ex.name);
return {
sync_id: ex.sync_id,
exercise_sync_id: exerciseRef ? exerciseRef.sync_id : null,
exercise_id: ex.exercise_id || ex.server_id || null,
exercise_name: ex.name,
sort_order: ex.sort_order ?? exIndex,
sets: buildSetsPayload(ex.sets),
};
});
}
function buildCardioPayload(cardioList) {
return (cardioList || []).map((c, cIndex) => {
ensureSyncId(c);
return {
sync_id: c.sync_id,
cardio_type: c.type || "другое",
purpose: c.purpose || "separate",
duration: toIntOrNull(c.duration),
distance: toNumberOrNull(c.distance),
speed: toNumberOrNull(c.speed),
incline: toNumberOrNull(c.incline),
resistance: toIntOrNull(c.resistance),
notes: c.notes || "",
sort_order: c.sort_order ?? cIndex,
};
});
}
function buildWorkoutsPayload(dirty) {
return dirty.map((w) => {
ensureSyncId(w);
const client = findClientByLocalId(w.client_id);
const wt = findWorkoutTypeByName(w.type);
return {
sync_id: w.sync_id,
// Для клиентов отправляем именно sync_id,
// потому что локальный id может отличаться на разных устройствах.
client_id: null,
client_sync_id: client ? client.sync_id : null,
workout_type_id: wt ? wt.id : null,
start_time: w.startTime,
end_time: w.endTime || null,
notes: w.notes || "",
workout_exercises: buildWorkoutExercisesPayload(w.exercises),
cardio_sessions: buildCardioPayload(w.cardio),
};
});
}
// ... предыдущие импорты и хелперы остаются ...
export async function sync() {
// Отправляем все тренировки: правки в уже синхронизированной тренировке
// тоже должны уходить на сервер (upsert по sync_id идемпотентен)
const dirtyWorkouts = state.workouts;
const dirtyMetrics = getDirtyMetrics(); // Новая функция
if (dirtyWorkouts.length === 0 && dirtyMetrics.length === 0) {
alert("Нет данных для синхронизации");
return;
}
const btn = document.querySelector(".header-actions .btn-secondary");
if (btn) {
btn.disabled = true;
btn.textContent = "⏳";
}
try {
// Генерируем sync_id для всего необходимого
ensureSyncIds(dirtyWorkouts, dirtyMetrics);
const payload = {
clients: buildClientsPayload(),
exercises: buildExercisesPayload(),
workouts: buildWorkoutsPayload(dirtyWorkouts),
body_metrics: buildMetricsPayload(dirtyMetrics), // Отправляем замеры
};
console.log("📤 Sending sync payload:", payload);
const response = await syncData(payload);
console.log("✅ Sync response:", response);
// Помечаем все как синхронизированные
dirtyWorkouts.forEach(w => w.synced = true);
dirtyMetrics.forEach(m => m.synced = true);
saveState();
if (typeof window.renderMainScreen === "function") {
window.renderMainScreen();
}
const createdW = response.created?.workouts || 0;
const createdM = response.created?.body_metrics || 0;
let message = `Синхронизировано:\nТренировок: ${createdW}\nЗамеров: ${createdM}`;
if (response.warnings?.length) {
message += `\n\nПредупреждения:\n${response.warnings.join("\n")}`;
}
alert(message);
} catch (e) {
console.error("❌ Sync error:", e);
alert("Ошибка синхронизации: " + e.message);
} finally {
if (btn) {
btn.disabled = false;
btn.textContent = "🔄";
}
}
}
// --- НОВЫЕ ХЕЛПЕРЫ ДЛЯ ЗАМЕРОВ ---
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
}))
};
});
}