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); } window.EL = { addExercise, toggleExercise, deleteExercise, };