diff --git a/src/App.tsx b/src/App.tsx index d87b39a..472be98 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -31,6 +31,20 @@ function AppContent() { // 🔧 ФИКС (23.09.2026): STRICTMODE_DOUBLE_REGISTER — ref-флаг, // чтобы регистрация не вызывалась дважды в StrictMode. const registerAttemptedRef = useRef(false); + // 🔧 ФИКС (24.09.2026): REGISTER_FAILURE_NO_RETRY_IN_SESSION — + // счётчик попыток registerUser. + const registerRetryCountRef = useRef(0); + + // 🔧 ФИКС (24.09.2026): STALE_CLOSURE_NAVIGATE_SETLANG — + // navigate и setLang в useRef, чтобы избежать stale closure + // при useEffect с []. + const navigateRef = useRef(navigate); + const setLangRef = useRef(setLang); + + useEffect(() => { + navigateRef.current = navigate; + setLangRef.current = setLang; + }, [navigate, setLang]); useEffect(() => { // 🔧 ФИКС (23.09.2026): ADMIN_FLAG_FROM_LOCALSTORAGE — очищаем старый ключ, @@ -80,7 +94,11 @@ function AppContent() { registerUser() .then((data) => { - trackDailyLogin().catch(() => {}); + // 🔧 ФИКС (24.09.2026): SILENT_ERROR_SWALLOWING_APP — + // логируем ошибку трекинга логина. + trackDailyLogin().catch((e) => { + console.warn('[App] trackDailyLogin failed:', e); + }); // 🔧 ФИКС (23.09.2026): ADMIN_FLAG_FROM_LOCALSTORAGE — не пишем в localStorage. if (typeof data.is_admin === 'boolean') { @@ -90,22 +108,30 @@ function AppContent() { .then((adminData) => { setIsAdmin(adminData.is_admin); }) - .catch(() => {}); + .catch((e) => { + // 🔧 ФИКС (24.09.2026): SILENT_ERROR_SWALLOWING_APP + console.warn('[App] getIsAdmin failed:', e); + }); } const langFromStorage = localStorage.getItem('filwords_lang'); if (!langFromStorage) { - navigate('/language'); + navigateRef.current('/language'); } else if (data.app_language && data.app_language !== langFromStorage) { - setLang(data.app_language); + setLangRef.current(data.app_language); } }) .catch((err) => { - // 🔧 ФИКС (23.09.2026): SILENT_REGISTER_FAILURE — логируем ошибку, - // сбрасываем ref, чтобы можно было повторить при следующем визите. + // 🔧 ФИКС (23.09.2026): SILENT_REGISTER_FAILURE — логируем ошибку. console.error('registerUser failed:', err); registerAttemptedRef.current = false; + // 🔧 ФИКС (24.09.2026): REGISTER_FAILURE_NO_RETRY_IN_SESSION — + // повторяем попытку с backoff (макс 3 попытки). + if (registerRetryCountRef.current < 3) { + registerRetryCountRef.current++; + retryTimeoutId = setTimeout(tryRegister, 2000 * registerRetryCountRef.current); + } }); }; @@ -116,6 +142,7 @@ function AppContent() { return () => { if (retryTimeoutId) clearTimeout(retryTimeoutId); }; + // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // 🔧 Слушаем событие "open-dashboard" из MenuPage — открывает модалку дашборда diff --git a/src/api.ts b/src/api.ts index 9fe9554..48b005c 100644 --- a/src/api.ts +++ b/src/api.ts @@ -232,6 +232,17 @@ const fetchAPI = async (endpoint: string, options: RequestInit = {}) => { throw new Error(`API Error: ${res.status} - ${errorText}`); } + // 🔧 ФИКС (24.09.2026): FETCH_JSON_NO_CONTENT_TYPE_CHECK — + // проверяем content-type перед парсингом JSON, чтобы не получить + // неинформативный 'Unexpected token < in JSON' (captive portal, CF challenge). + const contentType = res.headers.get('content-type') || ''; + if (!contentType.includes('application/json')) { + const text = await res.text(); + throw new Error( + `API Error: expected JSON, got ${contentType}. Body: ${text.slice(0, 200)}` + ); + } + const data = await res.json(); return data; }; @@ -409,10 +420,39 @@ export const saveAnalyticsToHistory = (message: string): Promise<{ status: strin body: JSON.stringify({ message }), }); -export const getPersonalStats = (): Promise => +// 🔧 ФИКС (24.09.2026): ANY_TYPES_PERSONAL_STATS — +// типизируем ответ. Если поля изменятся, TS подсветит. +export interface PersonalStatsResponse { + current_level: string; + total_score: number; + achievements: number; + words_guessed: number; + bubble_levels: number; + completed_topics: number; + level_progress: Record; +} + +// 🔧 ФИКС (24.09.2026): ANY_TYPES_ADMIN_STATS_ASSISTANT +export interface AdminStatsResponse { + total_users: number; + new_today: number; + online_now: number; + language_counts: Record; + level_counts: Record; +} + +export const getPersonalStats = (): Promise => fetchAPI('/assistant/stats/personal'); -export const getAdminStatsFromAssistant = (): Promise => +export const getAdminStatsFromAssistant = (): Promise => fetchAPI('/assistant/stats/admin'); // ============ Уроки (Learning) ============ @@ -1150,12 +1190,71 @@ export const getLessonTopics = (level: string): Promise<{ level: string; topics: export const getLessonTopic = (topicId: string): Promise => fetchAPI(`/admin/content/lessons/topic/${encodeURIComponent(topicId)}`); +// 🔧 ФИКС (24.09.2026): ANY_TYPES_LESSON_FULL — +// типизируем lesson/examples/questions для WYSIWYG. +export interface LessonFullExample { + id?: number; + order_number?: number; + text_pl: string; + text_ru: string; + text_uk: string; + text_en: string; + audio_url?: string | null; +} + +export interface LessonFullOption { + option_key: string; + text_pl: string; + text_ru: string; + text_uk: string; + text_en: string; + is_correct: boolean; + wrong_because: string | null; + wrong_because_text?: string; +} + +export interface LessonFullQuestion { + question_id: string; + context_type: string; + question_type: string; + skill_tag: string; + difficulty: number; + prompt_pl: string; + prompt_ru: string; + prompt_uk: string; + prompt_en: string; + correct_answer: string; + hint_type: string | null; + hint_value: string | null; + options_language: string; + options: LessonFullOption[]; +} + +export interface LessonFullResponse { + lesson: { + lesson_id: string; + topic_id: string; + order_number: number; + skill_tag: string; + title_pl: string; + title_ru: string; + title_uk: string; + title_en: string; + objective_pl: string; + objective_ru: string; + objective_uk: string; + objective_en: string; + explanation_pl: string; + explanation_ru: string; + explanation_uk: string; + explanation_en: string; + }; + examples: LessonFullExample[]; + questions: LessonFullQuestion[]; +} + // Урок целиком (для WYSIWYG) -export const getLessonFull = (lessonId: string): Promise<{ - lesson: any; - examples: any[]; - questions: any[]; -}> => +export const getLessonFull = (lessonId: string): Promise => fetchAPI(`/admin/content/lessons/lesson/${encodeURIComponent(lessonId)}`); // Сохранить урок diff --git a/src/pages/BubbleWordsPage.tsx b/src/pages/BubbleWordsPage.tsx index 9d92fe9..12669e9 100644 --- a/src/pages/BubbleWordsPage.tsx +++ b/src/pages/BubbleWordsPage.tsx @@ -148,6 +148,10 @@ const BubbleWordsPage: React.FC = () => { const showMessage = (msg: string) => { if (!isMountedRef.current) return; + // 🔧 ФИКС (24.09.2026): BUBBLE_MESSAGE_OVERLAP — скрываем errorMessage + // при показе message (взаимоисключение). + setErrorMessage(null); + if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current); setMessage(msg); if (messageTimeoutRef.current) clearTimeout(messageTimeoutRef.current); messageTimeoutRef.current = setTimeout(() => { @@ -159,6 +163,10 @@ const BubbleWordsPage: React.FC = () => { // с автоскрытием через 2 секунды (по аналогии с showMessage). const showError = (msg: string) => { if (!isMountedRef.current) return; + // 🔧 ФИКС (24.09.2026): BUBBLE_MESSAGE_OVERLAP — скрываем message + // при показе errorMessage (взаимоисключение). + setMessage(null); + if (messageTimeoutRef.current) clearTimeout(messageTimeoutRef.current); setErrorMessage(msg); if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current); errorTimeoutRef.current = setTimeout(() => { @@ -496,7 +504,9 @@ const BubbleWordsPage: React.FC = () => { {errorMessage && (
{ } }; + // 🔧 ФИКС (24.09.2026): FLASHCARDS_RETRACK_ON_ACHIEVEMENT — + // вынесли трекинг в отдельный useEffect с [] (одноразовый), + // чтобы showAchievement не вызывал повторный трекинг при смене identity. useEffect(() => { window.scrollTo(0, 0); - isMountedRef.current = true; + return () => { + isMountedRef.current = false; + if (audioRef.current) { + audioRef.current.pause(); + audioRef.current = null; + } + if (audioUrlRef.current) { + try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ } + audioUrlRef.current = null; + } + if ('speechSynthesis' in window) { + window.speechSynthesis.cancel(); + } + }; + }, []); - // 🔧 ИСПРАВЛЕНО: Трекинг только для Алфавита (активная вкладка по умолчанию) + // Одноразовый трекинг при монтировании + useEffect(() => { trackAlphabetOpened() .then((data: any) => { if (data?.new_achievements && data.new_achievements.length > 0) { @@ -165,23 +183,8 @@ const FlashcardsPage: React.FC = () => { } }) .catch(() => {}); - - return () => { - isMountedRef.current = false; - if (audioRef.current) { - audioRef.current.pause(); - audioRef.current = null; - } - // 🔧 ФИКС (24.09.2026): URL_LEAK_FLASHCARDS — освобождаем URL при unmount - if (audioUrlRef.current) { - try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ } - audioUrlRef.current = null; - } - if ('speechSynthesis' in window) { - window.speechSynthesis.cancel(); - } - }; - }, [showAchievement]); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); // 🔧 ИСПРАВЛЕНО: switchTab теперь сбрасывает window scroll const switchTab = (tab: TabType) => { diff --git a/src/pages/LeaderboardPage.tsx b/src/pages/LeaderboardPage.tsx index fc81d1c..69e5075 100644 --- a/src/pages/LeaderboardPage.tsx +++ b/src/pages/LeaderboardPage.tsx @@ -127,7 +127,9 @@ const LeaderboardPage: React.FC = () => { const [error, setError] = useState(null); const [selectedAchievement, setSelectedAchievement] = useState(null); const [showAchievements, setShowAchievements] = useState(false); - const currentUserId = getUserId(); + // 🔧 ФИКС (24.09.2026): LEADERBOARD_GETUSERID_EVERY_RENDER — + // getUserId() один раз через useState (initializer), не на каждый рендер. + const [currentUserId] = useState(() => getUserId()); const brandColor = '#2ECC71'; const palette = { diff --git a/src/pages/MenuPage.tsx b/src/pages/MenuPage.tsx index 3c6b21d..6d0f291 100644 --- a/src/pages/MenuPage.tsx +++ b/src/pages/MenuPage.tsx @@ -168,7 +168,10 @@ const MenuPage: React.FC = () => { setTotalScore(0); }); - getLeaderboard(100) + // 🔧 ФИКС (24.09.2026): MENU_LEADERBOARD_HEAVY_FETCH — + // вместо 100 записей грузим 50 (в 2 раза меньше трафика). + // TODO: вынести в отдельный endpoint /leaderboard/my-rank. + getLeaderboard(50) .then((data) => { const leaderboard = data.leaderboard || []; const myEntry = leaderboard.find((entry: any) => diff --git a/src/pages/TeacherChatPage.tsx b/src/pages/TeacherChatPage.tsx index 324754f..2e9f57a 100644 --- a/src/pages/TeacherChatPage.tsx +++ b/src/pages/TeacherChatPage.tsx @@ -110,6 +110,11 @@ const TeacherChatPage: React.FC = () => { // на КАЖДЫЙ рендер — O(n) при длинном чате. Теперь useRef(0), // а актуальное значение ставится один раз при загрузке истории (в useEffect). const idRef = useRef(0); + // 🔧 ФИКС (24.09.2026): TEACHER_TOAST_NO_CLEANUP — + // храним таймер для очистки. + const toastTimeoutRef = useRef | null>(null); + // 🔧 ФИКС (24.09.2026): TEACHER_HISTORY_SAVE_EVERY_MESSAGE + const historySaveTimeoutRef = useRef | null>(null); const startTimeRef = useRef(Date.now()); const brandColor = '#2ECC71'; @@ -133,9 +138,11 @@ const TeacherChatPage: React.FC = () => { }; // 🔧 ФИКС (23.09.2026): ALERT_IN_TELEGRAM_MINIAPP — helper для toast вместо alert() + // 🔧 ФИКС (24.09.2026): TEACHER_TOAST_NO_CLEANUP — сохраняем таймер. const showToast = (msg: string) => { setToastMessage(msg); - setTimeout(() => { + if (toastTimeoutRef.current) clearTimeout(toastTimeoutRef.current); + toastTimeoutRef.current = setTimeout(() => { setToastMessage(null); }, 2500); }; @@ -240,15 +247,23 @@ const TeacherChatPage: React.FC = () => { .catch(() => {}); }, []); + // 🔧 ФИКС (24.09.2026): TEACHER_HISTORY_SAVE_EVERY_MESSAGE — + // дебаунсим сохранение истории на сервер (500мс), чтобы не долбить + // бэк при каждом новом сообщении. useEffect(() => { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(messages)); - if (messages.length > 0) { - saveTeacherHistory(messages).catch(() => {}); - } } catch (e) { // ignore } + if (messages.length === 0) return; + if (historySaveTimeoutRef.current) clearTimeout(historySaveTimeoutRef.current); + historySaveTimeoutRef.current = setTimeout(() => { + saveTeacherHistory(messages).catch(() => {}); + }, 500); + return () => { + if (historySaveTimeoutRef.current) clearTimeout(historySaveTimeoutRef.current); + }; }, [messages]); const extractPolishText = (text: string): string => { @@ -403,6 +418,11 @@ const TeacherChatPage: React.FC = () => { try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ } audioUrlRef.current = null; } + // 🔧 ФИКС (24.09.2026): TEACHER_TOAST_NO_CLEANUP + if (toastTimeoutRef.current) { + clearTimeout(toastTimeoutRef.current); + toastTimeoutRef.current = null; + } if ('speechSynthesis' in window) { window.speechSynthesis.cancel(); } diff --git a/src/pages/TestViewPage.tsx b/src/pages/TestViewPage.tsx index 5515f76..9af26d6 100644 --- a/src/pages/TestViewPage.tsx +++ b/src/pages/TestViewPage.tsx @@ -53,6 +53,9 @@ const TestViewPage: React.FC = () => { const [isStartingPractice, setIsStartingPractice] = useState(false); // 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — toast вместо alert(). const [toastMessage, setToastMessage] = useState(null); + // 🔧 ФИКС (24.09.2026): TESTVIEW_TOAST_NO_CLEANUP — + // храним таймер для очистки. + const toastTimeoutRef = useRef | null>(null); const audioRef = useRef(null); // 🔧 ФИКС (24.09.2026): URL_LEAK_TESTVIEW — храним URL для revoke. const audioUrlRef = useRef(null); @@ -73,9 +76,11 @@ const TestViewPage: React.FC = () => { }); // 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — helper для toast. + // 🔧 ФИКС (24.09.2026): TESTVIEW_TOAST_NO_CLEANUP — сохраняем таймер. const showToast = (msg: string) => { setToastMessage(msg); - setTimeout(() => setToastMessage(null), 2500); + if (toastTimeoutRef.current) clearTimeout(toastTimeoutRef.current); + toastTimeoutRef.current = setTimeout(() => setToastMessage(null), 2500); }; useEffect(() => { @@ -112,6 +117,11 @@ const TestViewPage: React.FC = () => { try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ } audioUrlRef.current = null; } + // 🔧 ФИКС (24.09.2026): TESTVIEW_TOAST_NO_CLEANUP + if (toastTimeoutRef.current) { + clearTimeout(toastTimeoutRef.current); + toastTimeoutRef.current = null; + } if ('speechSynthesis' in window) { window.speechSynthesis.cancel(); } @@ -165,24 +175,15 @@ const TestViewPage: React.FC = () => { startTimeRef.current = Date.now(); } else { setIsCompleting(true); - - // Сохраняем ответ последнего вопроса - const currentQ = questions[currentIndex]; - const answer = selectedAnswers[currentQ.question.question_id]; - - if (answer && sessionId) { - const timeTaken = Date.now() - startTimeRef.current; - try { - // 🔧 ФИКС (23.09.2026): TESTVIEW_SAVEANSWER_MISSING_PARAMS - await saveLearningAnswer(sessionId, currentQ.question.question_id, answer, timeTaken, true, false); - } catch (e) { - console.error('Error saving final answer:', e); - } - } - + + // 🔧 ФИКС (24.09.2026): TESTVIEW_DUPLICATE_SAVE — + // ответ последнего вопроса уже сохранён в handleAnswerSelect / + // handleTextInputBlur. Повторно НЕ сохраняем — убираем дубль. + // (как в PracticeViewPage) + // Небольшая задержка для сохранения await new Promise(resolve => setTimeout(resolve, 300)); - + if (sessionId) { try { const result = await completeLearningSession(sessionId);