Files
gym-bro/frontend/js/logic/exercise.js

302 lines
11 KiB
JavaScript

import { state, saveState, genId } from '../state.js';
import { renderMainScreen } from '../render/main-screen.js';
import { showExerciseDialog } from '../modals/exercise-modal.js';
function normalizeName(name) {
return String(name || '').trim().toLowerCase();
}
function normalizeClientId(id) {
if (id === undefined || id === null || id === '') return null;
return String(id);
}
function isSameClient(a, b) {
return normalizeClientId(a) === normalizeClientId(b);
}
export function addExercise(workoutId) {
const w = state.workouts.find(x => x.id === workoutId);
if (!w) return;
showExerciseDialog(w.type, (name) => {
if (!name) return;
const ex = {
id: genId(),
name,
sets: [],
};
w.exercises.push(ex);
addToRef(name, w.type);
state.expandedExerciseId = ex.id;
saveState();
renderMainScreen();
});
}
export function addToRef(name, workoutType = '', group = '') {
const normalizedName = normalizeName(name);
const exists = state.exerciseRef.find(
e => normalizeName(e.name) === normalizedName
);
if (!exists) {
state.exerciseRef.push({
id: genId(),
name: String(name).trim(),
workoutType,
group: String(group || '').trim(),
});
} else {
if (!exists.workoutType && workoutType) exists.workoutType = workoutType;
if (!exists.group && group) exists.group = String(group).trim();
}
}
export function toggleExercise(exerciseId) {
state.expandedExerciseId =
state.expandedExerciseId === exerciseId ? null : exerciseId;
renderMainScreen();
}
export function deleteExercise(workoutId, exerciseId) {
if (!confirm('Удалить упражнение?')) return;
const w = state.workouts.find(x => x.id === workoutId);
if (!w) return;
w.exercises = w.exercises.filter(e => e.id !== exerciseId);
// Упражнение удалилось — чистим сеты, где оно состояло
if (Array.isArray(w.setGroups)) {
w.setGroups = w.setGroups
.map(g => ({ ...g, exerciseIds: g.exerciseIds.filter(id => id !== exerciseId) }))
.filter(g => g.exerciseIds.length >= 2);
}
saveState();
renderMainScreen();
}
/**
* Имена упражнений-вариантов в справочнике: та же «группа вариантов»
* и тот же тип тренировки (пустой тип ни у одной из записей не препятствие).
*/
function refVariantNames(exerciseName) {
const norm = normalizeName(exerciseName);
const names = new Set([norm]);
const entry = state.exerciseRef.find(e => normalizeName(e.name) === norm);
const group = String(entry?.group || '').trim().toLowerCase();
if (!group) return names;
const entryType = String(entry.workoutType || '').trim().toLowerCase();
for (const e of state.exerciseRef) {
if (String(e.group || '').trim().toLowerCase() !== group) continue;
const eType = String(e.workoutType || '').trim().toLowerCase();
if (entryType && eType && entryType !== eType) continue;
names.add(normalizeName(e.name));
}
return names;
}
/**
* Локальная история упражнения.
*
* @param {string} exerciseName
* @param {string|number|null} clientId - если тренировка принадлежит клиенту, история берётся только для этого клиента
* @param {string|number|null} excludeWorkoutId - чтобы не показывать текущую тренировку как "прошлую"
*/
export function getExerciseHistory(exerciseName, clientId = null, excludeWorkoutId = null) {
const variantNames = refVariantNames(exerciseName);
const targetClient = normalizeClientId(clientId);
const history = [];
for (const w of state.workouts) {
// Не показываем текущую тренировку в истории
if (excludeWorkoutId && String(w.id) === String(excludeWorkoutId)) {
continue;
}
// Если у тренировки есть клиент — сравниваем клиентов
// Если клиента нет — показываем только личные тренировки без клиента
if (!isSameClient(w.client_id, targetClient)) {
continue;
}
for (const ex of w.exercises || []) {
if (
variantNames.has(normalizeName(ex.name)) &&
Array.isArray(ex.sets) &&
ex.sets.length > 0
) {
history.push({
date: w.startTime,
name: ex.name,
sets: ex.sets,
});
}
}
}
history.sort((a, b) => new Date(b.date) - new Date(a.date));
return history.slice(0, 5);
}
/**
* Полная история для графика (без среза в 5 записей): варианты из одной
* группы складывают в одну прогрессию.
*/
export function getExerciseChart(exerciseName, clientId = null) {
const variantNames = refVariantNames(exerciseName);
const targetClient = normalizeClientId(clientId);
const points = [];
for (const w of state.workouts) {
if (!isSameClient(w.client_id, targetClient)) continue;
if (!w.endTime) continue; // активная тренировка ещё не результат
for (const ex of w.exercises || []) {
if (!variantNames.has(normalizeName(ex.name))) continue;
let maxWeight = 0, totalReps = 0;
const sets = []; // каждый подход отдельно: точка на графике
for (const s of ex.sets || []) {
const parts = s.isDropset && s.subSets?.length
? s.subSets
: [s];
for (const p of parts) {
const wgt = parseFloat(p.weight) || 0;
const rps = parseInt(p.reps) || 0;
if (wgt > 0 || rps > 0) sets.push({ weight: wgt, reps: rps });
if (wgt > maxWeight) maxWeight = wgt;
totalReps += rps;
}
}
// повторы, взятые на максимальном весе — по ним видно прогресс при том же весе
let topReps = 0;
for (const st of sets) {
if (st.weight === maxWeight && st.reps > topReps) topReps = st.reps;
}
if (maxWeight > 0 || totalReps > 0) {
points.push({ date: w.startTime, name: ex.name, maxWeight, topReps, totalReps, sets });
}
}
}
points.sort((a, b) => new Date(a.date) - new Date(b.date));
return points;
}
/**
* Сводка по упражнению (все завершённые тренировки): рекорды, средние за
* тренировку и за всё время, синергичные упражнения (делались в тот же день)
* и максимальный вес среди них. Варианты из одной группы считаются вместе.
*/
export function getExerciseSummary(exerciseName, clientId = null) {
const variantNames = refVariantNames(exerciseName);
const targetClient = normalizeClientId(clientId);
let best = null; // {weight, reps, date, variant}
let maxSetsDay = null; // {count, date}
let totalSets = 0, totalVolume = 0, totalReps = 0, totalRating = 0;
let sumTopWeight = 0, days = 0;
let from = null, to = null;
const variantsSeen = new Set();
const synergic = new Map(); // нормализованное имя -> {name, count, best}
for (const w of state.workouts) {
if (!isSameClient(w.client_id, targetClient)) continue;
if (!w.endTime) continue;
const hits = (w.exercises || []).filter(ex => variantNames.has(normalizeName(ex.name)));
if (!hits.length) continue;
days++;
if (!from || new Date(w.startTime) < new Date(from)) from = w.startTime;
if (!to || new Date(w.startTime) > new Date(to)) to = w.startTime;
let daySets = 0, dayVolume = 0, dayTop = 0;
for (const ex of hits) {
variantsSeen.add(ex.name);
for (const s of ex.sets || []) {
const parts = s.isDropset && s.subSets?.length ? s.subSets : [s];
for (const p of parts) {
const wgt = parseFloat(p.weight) || 0;
const rps = parseInt(p.reps) || 0;
if (!wgt && !rps) continue;
daySets++; totalSets++;
dayVolume += wgt * rps; totalVolume += wgt * rps;
totalReps += rps;
if ((parseFloat(s.rating) || 5) > 0) totalRating += (parseFloat(s.rating) || 5);
if (wgt > dayTop) dayTop = wgt;
if (!best || wgt > best.weight || (wgt === best.weight && rps > best.reps)) {
best = { weight: wgt, reps: rps, date: w.startTime, variant: ex.name };
}
}
}
}
sumTopWeight += dayTop;
if (!maxSetsDay || daySets > maxSetsDay.count) maxSetsDay = { count: daySets, date: w.startTime };
// Синергичные: другие упражнения этих же тренировок
for (const ex of w.exercises || []) {
if (variantNames.has(normalizeName(ex.name))) continue;
const key = normalizeName(ex.name);
const rec = synergic.get(key) || { name: ex.name, count: 0, best: null };
rec.count++;
for (const s of ex.sets || []) {
const parts = s.isDropset && s.subSets?.length ? s.subSets : [s];
for (const p of parts) {
const wgt = parseFloat(p.weight) || 0;
const rps = parseInt(p.reps) || 0;
if (!wgt) continue;
if (!rec.best || wgt > rec.best.weight || (wgt === rec.best.weight && rps > rec.best.reps)) {
rec.best = { weight: wgt, reps: rps, date: w.startTime };
}
}
}
synergic.set(key, rec);
}
}
const synergicList = Array.from(synergic.values())
.sort((a, b) => b.count - a.count || (b.best?.weight || 0) - (a.best?.weight || 0));
let synergicBest = null;
for (const s of synergicList) {
if (s.best && (!synergicBest || s.best.weight > synergicBest.weight)) {
synergicBest = { ...s.best, name: s.name };
}
}
return {
days,
variants: Array.from(variantsSeen),
period: from ? { from, to } : null,
best,
maxSetsDay,
totals: { sets: totalSets, volume: totalVolume, reps: totalReps },
avg: days ? {
topWeight: Math.round(sumTopWeight / days * 10) / 10,
sets: Math.round(totalSets / days * 10) / 10,
volume: Math.round(totalVolume / days),
reps: Math.round(totalReps / days),
rating: Math.round(totalRating / totalSets * 10) / 10 || 0,
} : null,
synergic: synergicList,
synergicBest,
};
}
window.EL = {
addExercise,
toggleExercise,
deleteExercise,
};