diff --git a/src/pages/Exercise.tsx b/src/pages/Exercise.tsx index 44ae574..5b8f96a 100644 --- a/src/pages/Exercise.tsx +++ b/src/pages/Exercise.tsx @@ -41,6 +41,7 @@ export const Exercise = () => { const { courseId, exerciseId, exerciseIndex } = useParams() const location = useLocation() + const [course_exercises, setCourseExercises] = useState([]) const [actualExerciseId, setActualExerciseId] = useState("") const [currentDay, setCurrentDay] = useState(null) @@ -70,10 +71,6 @@ export const Exercise = () => { const [totalRestTime] = useState(60) const [isRestPaused, setIsRestPaused] = useState(false) - // ========== НОВЫЕ СОСТОЯНИЯ ДЛЯ ЗАВЕРШЕНИЯ ДНЯ ========== - const [completedExercisesInDay, setCompletedExercisesInDay] = useState(0) // Сколько упражнений уже завершено в текущем дне - const [totalExercisesInDay, setTotalExercisesInDay] = useState(0) // Общее количество упражнений в текущем дне - useEffect(() => { const loadCourseExercises = async () => { if (!courseId) return @@ -120,26 +117,6 @@ export const Exercise = () => { setLoading(false) return } - - const exercisesForCurrentDay = exercises.filter((ex: any) => ex.day === fixedDay) - setTotalExercisesInDay(exercisesForCurrentDay.length) - - // Подсчитываем завершенные упражнения из localStorage - let completedCount = 0 - exercisesForCurrentDay.forEach((ex: any) => { - const storageKey = `exerciseProgress_${courseId}_${ex.id_exercise}_day_${fixedDay}` - const savedProgress = localStorage.getItem(storageKey) - if (savedProgress) { - const progress = JSON.parse(savedProgress) - if (progress.status === 1) { - // 1 означает полностью завершено - completedCount++ - } - } - }) - setCompletedExercisesInDay(completedCount) - - console.log(`[v0] День ${fixedDay}: завершено ${completedCount} из ${exercisesForCurrentDay.length} упражнений`) } catch (error) { console.error("Ошибка при загрузке упражнений курса:", error) setError("Ошибка при загрузке упражнений") @@ -150,6 +127,7 @@ export const Exercise = () => { loadCourseExercises() }, [courseId, exerciseId, exerciseIndex, location.search]) + // ========== ЗАГРУЗКА ДАННЫХ УПРАЖНЕНИЯ С СЕРВЕРА ========== useEffect(() => { if (!actualExerciseId || !courseId) return @@ -206,6 +184,7 @@ export const Exercise = () => { }) }, [courseId, actualExerciseId]) + // ========== ФУНКЦИЯ ЗАГРУЗКИ ПРОГРЕССА С СЕРВЕРА ========== const loadProgressFromServer = async () => { try { console.log(`Загружаем прогресс для курса ${courseId}, упражнения ${actualExerciseId}, день ${currentDay}`) @@ -219,6 +198,7 @@ export const Exercise = () => { }, }) + console.log("Ответ сервера с прогрессом:", response.data) if ( @@ -297,6 +277,7 @@ export const Exercise = () => { } } + // ========== ФУНКЦИЯ КОНВЕРТАЦИИ ВРЕМЕНИ ИЗ MM:SS В СЕКУНДЫ ========== const convertTimeToSeconds = (timeString: string): number => { try { const parts = timeString.split(":") @@ -318,6 +299,7 @@ export const Exercise = () => { } } + // ========== ФУНКЦИЯ СОХРАНЕНИЯ ПРОГРЕССА ПОДХОДА НА СЕРВЕР ========== const saveSetProgress = async (setNumber: number, timeString: string, status: number) => { try { const dayToSave = currentDay || 1 @@ -346,10 +328,20 @@ export const Exercise = () => { } + + console.log("TEST DAY COMPLETE", course_exercises) + console.log("Всего упражнений в курсе", course_exercises.length) + + + + + + // ========== ФУНКЦИЯ перехода к след упражнению ========== const goToNextExercise = () => { console.log("Переходим к следующему упражнению") + if (exerciseIndex !== undefined) { const currentIndex = Number.parseInt(exerciseIndex) const nextIndex = currentIndex + 1 @@ -357,13 +349,16 @@ export const Exercise = () => { const dayParam = selectedDay ? `?day=${selectedDay}` : "" history.push(`/course/${courseId}/exercise/${nextIndex}${dayParam}`) + + } else { const currentExerciseNum = Number.parseInt(actualExerciseId) const nextExerciseId = currentExerciseNum + 1 history.push(`/course/${courseId}/${nextExerciseId}`) - } + } } + // ========== ФУНКЦИЯ ЗАВЕРШЕНИЯ ТЕКУЩЕГО ПОДХОДА ========== const handleCompleteSet = async () => { console.log("Пользователь завершает подход", currentSet, "из", totalSets) @@ -388,6 +383,7 @@ export const Exercise = () => { } } + // ========== ФУНКЦИЯ ПОЛНОГО ЗАВЕРШЕНИЯ УПРАЖНЕНИЯ ========== const handleComplete = async (completedSetsArray = completedSets) => { console.log("УПРАЖНЕНИЕ ПОЛНОСТЬЮ ЗАВЕРШЕНО! Все подходы выполнены.") @@ -403,15 +399,13 @@ export const Exercise = () => { day: currentDay, position: totalTime, set: totalSets, - status: 1, // 1 = полностью завершено + status: 1, totalTime: totalTime, completedSets: completedSetsArray, completedAt: new Date().toISOString(), }), ) - setCompletedExercisesInDay((prev) => prev + 1) - setIsCompleted(true) setCurrentTime(totalTime) setIsPlaying(false) @@ -421,6 +415,7 @@ export const Exercise = () => { setCompletedSets(completedSetsArray) } + // ========== ФУНКЦИЯ ПАУЗЫ И СОХРАНЕНИЯ ПРОГРЕССА ========== const handlePause = async ( completedSetsArray = completedSets, setNumber = currentSet, @@ -455,6 +450,7 @@ export const Exercise = () => { setHasSavedProgress(true) } + // ========== ВОССТАНОВЛЕНИЕ ПРОГРЕССА ПРИ ЗАГРУЗКЕ СТРАНИЦЫ ========== useEffect(() => { const loadProgress = async () => { if (!actualExerciseId) return @@ -507,6 +503,7 @@ export const Exercise = () => { loadProgress() }, [courseId, actualExerciseId, currentDay, totalTime, totalSets]) + // ========== ОСНОВНОЙ ТАЙМЕР ДЛЯ УПРАЖНЕНИЯ ========== useEffect(() => { let interval: NodeJS.Timeout | undefined @@ -540,6 +537,7 @@ export const Exercise = () => { } }, [isPlaying, totalTime, isCompleted, isResting, currentSet, completedSets]) + // ========== ТАЙМЕР ДЛЯ ОТДЫХА МЕЖДУ ПОДХОДАМИ ========== useEffect(() => { let restInterval: NodeJS.Timeout | undefined @@ -573,6 +571,7 @@ export const Exercise = () => { } }, [isResting, restTime, isRestPaused, currentSet]) + // ========== ФУНКЦИИ ДЛЯ АНИМАЦИИ КНОПКИ СБРОСА ========== const handleClick = () => { console.log("Запускаем анимацию кнопки сброса") setIsRotating(true) @@ -583,14 +582,17 @@ export const Exercise = () => { setIsRotating(false) } + // ========== ФУНКЦИЯ ФОРМАТИРОВАНИЯ ВРЕМЕНИ ========== const formatTime = (seconds: number) => { const mins = Math.floor(seconds / 60) const secs = seconds % 60 return `${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}` } + // ========== РАСЧЕТ ПРОГРЕССА ДЛЯ ПОЛОСКИ ========== const progress = isResting ? ((totalRestTime - restTime) / totalRestTime) * 100 : (currentTime / totalTime) * 100 + // ========== ИКОНКИ ДЛЯ КНОПОК ========== const PlayIcon = () => ( @@ -618,6 +620,7 @@ export const Exercise = () => { ) + // ========== ИНФОРМАЦИЯ ОБ УПРАЖНЕНИИ ДЛЯ ОТОБРАЖЕНИЯ ========== const exerciseSteps = [ { title: "Описание упражнения", @@ -641,7 +644,7 @@ export const Exercise = () => { }, ] - + // ========== ЭКРАНЫ ЗАГРУЗКИ И ОШИБОК ========== if (loading) { return (
@@ -697,6 +700,7 @@ export const Exercise = () => { ) } + // ========== ОСНОВНОЙ ИНТЕРФЕЙС УПРАЖНЕНИЯ ========== return (
@@ -729,10 +733,11 @@ export const Exercise = () => { @@ -787,8 +792,9 @@ export const Exercise = () => { return (
{setNumber}
@@ -823,12 +829,13 @@ export const Exercise = () => {
{isCompleted @@ -845,12 +852,13 @@ export const Exercise = () => {
@@ -858,25 +866,14 @@ export const Exercise = () => {
{isCompleted ? ( <> - {completedExercisesInDay + 1 >= totalExercisesInDay ? ( - - ) : ( - - )} + +
Завершено @@ -889,10 +886,11 @@ export const Exercise = () => { setIsRestPaused(!isRestPaused) handlePause(completedSets, currentSet, true, restTime, !isRestPaused) }} - className={`flex-1 font-bold py-3 px-4 rounded-xl transition-all duration-300 flex items-center justify-center space-x-2 ${isRestPaused + className={`flex-1 font-bold py-3 px-4 rounded-xl transition-all duration-300 flex items-center justify-center space-x-2 ${ + isRestPaused ? "bg-yellow-500 hover:bg-yellow-600 text-white" : "bg-[#2BACBE] hover:bg-[#2099A8] text-white" - }`} + }`} > {isRestPaused ? ( <> @@ -932,10 +930,11 @@ export const Exercise = () => { setIsPlaying(false) } }} - className={`flex-1 font-bold py-3 px-4 rounded-xl transition-all duration-300 transform hover:scale-105 flex items-center justify-center space-x-2 cursor-pointer ${isPlaying + className={`flex-1 font-bold py-3 px-4 rounded-xl transition-all duration-300 transform hover:scale-105 flex items-center justify-center space-x-2 cursor-pointer ${ + isPlaying ? "bg-yellow-500 hover:bg-yellow-600 text-white shadow-lg" : "bg-[#2BACBE] hover:bg-[#2099A8] text-white shadow-lg" - }`} + }`} > {isPlaying ? ( <>