🌊 Волна 7: frontend качество кода (8 багов)
Типизация: - untyped_any_in_useLocalized: generic <T extends Record<string, unknown>> (useLocalized.ts) - ANY_TYPES_IN_API + MISSING_RETURN_TYPES: интерфейсы для критичных функций (api.ts) - SENTRY_ERROR_FIELD_IN_SUCCESS: разделение success/error (api.ts) Производительность: - context_value_not_memoized: useMemo + useCallback (LanguageContext.tsx) Логика: - TESTVIEW_SAVEANSWER_MISSING_PARAMS: единая сигнатура saveAnswer (TestViewPage.tsx) - LESSON_HARDCODED_SKILL_TAG: optionsLanguage вместо хардкода (LessonViewPage.tsx) - silent_error_swallow_setLanguage: логирование ошибки (LanguageContext.tsx) Аудит: Issue #3, frontend 8/34 задач
This commit is contained in:
+181
-30
@@ -7,6 +7,173 @@ const API_BASE = 'https://api.filwordspl.com';
|
||||
// запрос висел бесконечно, UI оставался в состоянии загрузки.
|
||||
const FETCH_TIMEOUT_MS = 15000;
|
||||
|
||||
// ============ 🔧 ТИПЫ ОТВЕТОВ (23.09.2026) ============
|
||||
// Fix: ANY_TYPES_IN_API + MISSING_RETURN_TYPES + SENTRY_ERROR_FIELD_IN_SUCCESS
|
||||
|
||||
export interface Achievement {
|
||||
code: string;
|
||||
icon: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface GameProgress {
|
||||
last_completed_level: number;
|
||||
total_score: number;
|
||||
current_level?: string;
|
||||
}
|
||||
|
||||
export interface GameLevel {
|
||||
level: {
|
||||
id: number;
|
||||
level_number: number;
|
||||
grid_size: number;
|
||||
grid_letters: string[][];
|
||||
word_paths: Record<string, [number, number][]>;
|
||||
level: string;
|
||||
};
|
||||
words: Array<{ word_pl: string; translation: string }>;
|
||||
progress: {
|
||||
completed: boolean;
|
||||
hints_used: number;
|
||||
score: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface CheckWordResponse {
|
||||
status: string;
|
||||
found: boolean;
|
||||
word?: string;
|
||||
new_achievements?: Achievement[];
|
||||
}
|
||||
|
||||
export interface CompleteLevelResponse {
|
||||
status: string;
|
||||
score: number;
|
||||
already_completed: boolean;
|
||||
new_achievements?: Achievement[];
|
||||
}
|
||||
|
||||
export interface NextSentenceResponse {
|
||||
completed?: boolean;
|
||||
message?: string;
|
||||
id?: number;
|
||||
sentence_number?: number;
|
||||
words?: string[];
|
||||
correct_words?: string[];
|
||||
translation?: string;
|
||||
difficulty?: number;
|
||||
level?: string;
|
||||
}
|
||||
|
||||
export interface CheckSentenceResponse {
|
||||
correct: boolean;
|
||||
correct_words?: string[];
|
||||
already_completed?: boolean;
|
||||
score?: number;
|
||||
completed_at?: string;
|
||||
new_achievements?: Achievement[];
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface NextQuizResponse {
|
||||
correct_polish: string;
|
||||
translation: string;
|
||||
options: string[];
|
||||
difficulty: string;
|
||||
}
|
||||
|
||||
export interface CheckQuizResponse {
|
||||
correct: boolean;
|
||||
score?: number;
|
||||
correct_streak: number;
|
||||
new_achievements?: Achievement[];
|
||||
consolation_score?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface BubbleLevelResponse {
|
||||
words: Array<{ word_pl: string; translation: string; parts: string[] }>;
|
||||
bubbles: Array<{ text: string; word_pl: string }>;
|
||||
level: number;
|
||||
}
|
||||
|
||||
export interface CompleteBubbleResponse {
|
||||
status: string;
|
||||
score: number;
|
||||
completion_time?: number;
|
||||
new_achievements?: Achievement[];
|
||||
}
|
||||
|
||||
export interface LearningLevel {
|
||||
code: string;
|
||||
name_pl: string;
|
||||
name_ru: string;
|
||||
name_uk: string;
|
||||
name_en: string;
|
||||
sort_order: number;
|
||||
is_active: boolean;
|
||||
}
|
||||
|
||||
export interface LearningLevelsResponse {
|
||||
levels: LearningLevel[];
|
||||
}
|
||||
|
||||
export interface AchievementListItem {
|
||||
id: number;
|
||||
code: string;
|
||||
category: string;
|
||||
icon: string;
|
||||
name_pl: string;
|
||||
name_ru: string;
|
||||
name_uk: string;
|
||||
name_en: string;
|
||||
description_pl: string;
|
||||
description_ru: string;
|
||||
description_uk: string;
|
||||
description_en: string;
|
||||
unlocked: boolean;
|
||||
unlocked_at: string | null;
|
||||
}
|
||||
|
||||
export interface AchievementsListResponse {
|
||||
achievements: AchievementListItem[];
|
||||
unlocked: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface TrackLoginResponse {
|
||||
status?: string;
|
||||
new_achievements?: Achievement[];
|
||||
}
|
||||
|
||||
// 🔧 ФИКС (23.09.2026): SENTRY_ERROR_FIELD_IN_SUCCESS —
|
||||
// разделили success и error-типы. error теперь отдельно, не в success.
|
||||
export interface SentryError {
|
||||
id: string;
|
||||
short_id: string;
|
||||
title: string;
|
||||
culprit: string;
|
||||
level: string;
|
||||
count: number;
|
||||
user_count: number;
|
||||
first_seen: string;
|
||||
last_seen: string;
|
||||
permalink: string;
|
||||
priority: string;
|
||||
}
|
||||
|
||||
export interface SentryErrorsSuccess {
|
||||
errors: SentryError[];
|
||||
count?: number;
|
||||
}
|
||||
|
||||
export interface SentryErrorsError {
|
||||
error: string;
|
||||
}
|
||||
|
||||
export type SentryErrorsResponse = SentryErrorsSuccess | SentryErrorsError;
|
||||
|
||||
// ============ FETCH WRAPPER ============
|
||||
const fetchAPI = async (endpoint: string, options: RequestInit = {}) => {
|
||||
const initData = getInitData();
|
||||
|
||||
@@ -72,40 +239,24 @@ export const getAdminDashboard = (): Promise<{
|
||||
}> =>
|
||||
fetchAPI('/admin/dashboard');
|
||||
|
||||
export const getSentryErrors = (): Promise<{
|
||||
errors: Array<{
|
||||
id: string;
|
||||
short_id: string;
|
||||
title: string;
|
||||
culprit: string;
|
||||
level: string;
|
||||
count: number;
|
||||
user_count: number;
|
||||
first_seen: string;
|
||||
last_seen: string;
|
||||
permalink: string;
|
||||
priority: string;
|
||||
}>;
|
||||
count?: number;
|
||||
error?: string;
|
||||
}> =>
|
||||
export const getSentryErrors = (): Promise<SentryErrorsResponse> =>
|
||||
fetchAPI('/admin/sentry-errors');
|
||||
|
||||
// ============ Прогресс ============
|
||||
export const fetchProgress = (): Promise<{ last_completed_level: number; total_score: number; current_level?: string }> =>
|
||||
export const fetchProgress = (): Promise<GameProgress> =>
|
||||
fetchAPI('/game/progress');
|
||||
|
||||
// ============ Игра ============
|
||||
export const getLevel = (levelNumber: number) =>
|
||||
export const getLevel = (levelNumber: number): Promise<GameLevel> =>
|
||||
fetchAPI(`/game/level/${levelNumber}`);
|
||||
|
||||
export const checkWord = (levelId: number, cells: number[][]) =>
|
||||
export const checkWord = (levelId: number, cells: number[][]): Promise<CheckWordResponse> =>
|
||||
fetchAPI('/game/check-word', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ level_id: levelId, cells }),
|
||||
});
|
||||
|
||||
export const completeLevel = (levelId: number, hintsUsed: number, completionTime?: number, perfectStreak?: number) =>
|
||||
export const completeLevel = (levelId: number, hintsUsed: number, completionTime?: number, perfectStreak?: number): Promise<CompleteLevelResponse> =>
|
||||
fetchAPI('/game/complete-level', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
@@ -131,10 +282,10 @@ export const getAdminStats = () =>
|
||||
fetchAPI('/leaderboard/admin/stats');
|
||||
|
||||
// ============ Предложения ============
|
||||
export const getNextSentence = () =>
|
||||
export const getNextSentence = (): Promise<NextSentenceResponse> =>
|
||||
fetchAPI('/sentences/next');
|
||||
|
||||
export const checkSentence = (sentenceId: number, words: string[], completionTime?: number) =>
|
||||
export const checkSentence = (sentenceId: number, words: string[], completionTime?: number): Promise<CheckSentenceResponse> =>
|
||||
fetchAPI('/sentences/check', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
@@ -148,10 +299,10 @@ export const getSentenceHint = (sentenceId: number) =>
|
||||
fetchAPI(`/sentences/${sentenceId}/hint`);
|
||||
|
||||
// ============ Word Quiz ============
|
||||
export const getNextQuiz = () =>
|
||||
export const getNextQuiz = (): Promise<NextQuizResponse> =>
|
||||
fetchAPI('/wordquiz/next');
|
||||
|
||||
export const checkQuizAnswer = (correctPolish: string, answer: string, mistakes: number, completionTime?: number) =>
|
||||
export const checkQuizAnswer = (correctPolish: string, answer: string, mistakes: number, completionTime?: number): Promise<CheckQuizResponse> =>
|
||||
fetchAPI('/wordquiz/check', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
@@ -166,10 +317,10 @@ export const getQuizProgress = () =>
|
||||
fetchAPI('/wordquiz/progress');
|
||||
|
||||
// ============ Bubble Words ============
|
||||
export const getBubbleLevel = () =>
|
||||
export const getBubbleLevel = (): Promise<BubbleLevelResponse> =>
|
||||
fetchAPI('/bubblewords/next');
|
||||
|
||||
export const completeBubbleLevel = (hintsUsed: number, wordsCount: number, completionTime?: number) =>
|
||||
export const completeBubbleLevel = (hintsUsed: number, wordsCount: number, completionTime?: number): Promise<CompleteBubbleResponse> =>
|
||||
fetchAPI('/bubblewords/complete', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
@@ -244,7 +395,7 @@ export const getAdminStatsFromAssistant = (): Promise<any> =>
|
||||
fetchAPI('/assistant/stats/admin');
|
||||
|
||||
// ============ Уроки (Learning) ============
|
||||
export const getLearningLevels = () =>
|
||||
export const getLearningLevels = (): Promise<LearningLevelsResponse> =>
|
||||
fetchAPI('/learning/levels');
|
||||
|
||||
export const getLearningTopics = (level: string) =>
|
||||
@@ -314,13 +465,13 @@ export const getTypingProgress = (): Promise<{ total: number; completed: number;
|
||||
fetchAPI('/typing/progress');
|
||||
|
||||
// ============ Достижения ============
|
||||
export const getAllAchievements = () =>
|
||||
export const getAllAchievements = (): Promise<AchievementsListResponse> =>
|
||||
fetchAPI('/achievements');
|
||||
|
||||
export const getUserAchievements = () =>
|
||||
fetchAPI('/achievements/user');
|
||||
|
||||
export const trackLogin = () =>
|
||||
export const trackLogin = (): Promise<TrackLoginResponse> =>
|
||||
fetchAPI('/achievements/track-login', { method: 'POST' });
|
||||
|
||||
export const trackTeacherMenuOpened = () =>
|
||||
|
||||
@@ -16,10 +16,17 @@ import { useLanguage } from '../i18n/LanguageContext';
|
||||
export const useLocalized = () => {
|
||||
const { language } = useLanguage();
|
||||
|
||||
return (item: any, field: string): string => {
|
||||
// 🔧 ФИКС (23.09.2026): untyped_any_in_useLocalized — используем generic <T>,
|
||||
// без требования index signature. Это позволяет передавать любые интерфейсы
|
||||
// (Lesson, AlphabetLetter, GrammarRule, ...) без ошибок TS.
|
||||
// Внутри — приводим к Record<string, unknown> через `as`.
|
||||
return <T,>(item: T | null | undefined, field: string): string => {
|
||||
if (!item) return '';
|
||||
const obj = item as Record<string, unknown>;
|
||||
const key = `${field}_${language}`;
|
||||
const fallback = `${field}_en`;
|
||||
return item[key] || item[fallback] || '';
|
||||
const value = obj[key];
|
||||
const fallbackValue = obj[fallback];
|
||||
return (typeof value === 'string' ? value : '') || (typeof fallbackValue === 'string' ? fallbackValue : '') || '';
|
||||
};
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { createContext, useContext, useState, useEffect, type ReactNode } from 'react';
|
||||
import React, { createContext, useContext, useState, useEffect, useMemo, useCallback, type ReactNode } from 'react';
|
||||
import { getTranslation } from './translations';
|
||||
import { setLanguage } from '../api';
|
||||
import { getUserId } from '../telegram';
|
||||
@@ -40,22 +40,35 @@ export const LanguageProvider: React.FC<{ children: ReactNode }> = ({ children }
|
||||
return;
|
||||
}
|
||||
if (getUserId()) {
|
||||
setLanguage(language).catch(() => {});
|
||||
// 🔧 ФИКС (23.09.2026): silent_error_swallow_setLanguage — логируем ошибку,
|
||||
// чтобы при сбое сети было понятно, что язык на сервере не обновился.
|
||||
setLanguage(language).catch((err) => {
|
||||
console.warn('[LanguageContext] Failed to sync language to server:', err);
|
||||
});
|
||||
}
|
||||
}, [language]);
|
||||
|
||||
const setLang = (lang: string) => {
|
||||
// 🔧 ФИКС (23.09.2026): context_value_not_memoized — setLang стабилен,
|
||||
// создаётся один раз.
|
||||
const setLang = useCallback((lang: string) => {
|
||||
if (['pl', 'ru', 'uk', 'en'].includes(lang)) {
|
||||
setLanguageState(lang);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const t = (key: string): string => {
|
||||
// 🔧 ФИКС (23.09.2026): context_value_not_memoized — t и value мемоизированы,
|
||||
// чтобы потребители useLanguage() не ререндерились при каждом рендере провайдера.
|
||||
const t = useCallback((key: string): string => {
|
||||
return getTranslation(language, key);
|
||||
};
|
||||
}, [language]);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({ language, setLang, t }),
|
||||
[language, t]
|
||||
);
|
||||
|
||||
return (
|
||||
<LanguageContext.Provider value={{ language, setLang, t }}>
|
||||
<LanguageContext.Provider value={value}>
|
||||
{children}
|
||||
</LanguageContext.Provider>
|
||||
);
|
||||
|
||||
@@ -199,7 +199,16 @@ const LessonViewPage: React.FC = () => {
|
||||
const isLastQuestion = currentQuestionIndex === lesson.questions.length - 1;
|
||||
const isProduction = currentQuestion?.question.question_type === 'production';
|
||||
const isCurrentAnswered = currentQuestion ? !!selectedAnswers[currentQuestion.question.question_id] : false;
|
||||
const isTranslationQuestion = currentQuestion?.question.skill_tag === 'how_are_you';
|
||||
|
||||
// 🔧 ФИКС (23.09.2026): LESSON_HARDCODED_SKILL_TAG — используем optionsLanguage
|
||||
// из данных вопроса (как в TeacherChatPage), а не хардкод skill_tag.
|
||||
// Для любого навыка с optionsLanguage='user' варианты локализуются.
|
||||
const optionsLanguage = (currentQuestion?.question as any)?.options_language;
|
||||
// Fallback: если поле отсутствует — оставляем старое поведение
|
||||
const isTranslationQuestion =
|
||||
optionsLanguage === 'user' ||
|
||||
(optionsLanguage === undefined && currentQuestion?.question.skill_tag === 'how_are_you');
|
||||
|
||||
const isHintUsed = currentQuestion ? !!hintUsed[currentQuestion.question.question_id] : false;
|
||||
const correctOption = currentQuestion?.options.find(o => o.is_correct);
|
||||
|
||||
|
||||
@@ -91,13 +91,22 @@ const TestViewPage: React.FC = () => {
|
||||
}
|
||||
}, [topicId]);
|
||||
|
||||
const saveAnswer = async (questionId: string, answer: string) => {
|
||||
// 🔧 ФИКС (23.09.2026): TESTVIEW_SAVEANSWER_MISSING_PARAMS — сигнатура
|
||||
// приведена к общему виду (isFinalAnswer, usedHint) — как в LessonViewPage
|
||||
// и PracticeViewPage. Раньше тест не передавал usedHint, и статистика
|
||||
// по подсказкам в тесте не собиралась.
|
||||
const saveAnswer = async (
|
||||
questionId: string,
|
||||
answer: string,
|
||||
isFinalAnswer: boolean = true,
|
||||
usedHint: boolean = false,
|
||||
) => {
|
||||
const timeTaken = Date.now() - startTimeRef.current;
|
||||
startTimeRef.current = Date.now();
|
||||
|
||||
if (sessionId) {
|
||||
try {
|
||||
await saveLearningAnswer(sessionId, questionId, answer, timeTaken, true);
|
||||
await saveLearningAnswer(sessionId, questionId, answer, timeTaken, isFinalAnswer, usedHint);
|
||||
} catch (e) {
|
||||
console.error('Error saving answer:', e);
|
||||
}
|
||||
@@ -106,7 +115,8 @@ const TestViewPage: React.FC = () => {
|
||||
|
||||
const handleAnswerSelect = async (questionId: string, optionKey: string) => {
|
||||
setSelectedAnswers(prev => ({ ...prev, [questionId]: optionKey }));
|
||||
await saveAnswer(questionId, optionKey);
|
||||
// 🔧 ФИКС (23.09.2026): обычный ответ — isFinalAnswer=true, usedHint=false
|
||||
await saveAnswer(questionId, optionKey, true, false);
|
||||
};
|
||||
|
||||
const handleTextInputChange = async (questionId: string, value: string) => {
|
||||
@@ -116,7 +126,8 @@ const TestViewPage: React.FC = () => {
|
||||
|
||||
const handleTextInputBlur = async (questionId: string) => {
|
||||
if (textInputValue.trim()) {
|
||||
await saveAnswer(questionId, textInputValue.trim());
|
||||
// 🔧 ФИКС (23.09.2026): обычный ответ — isFinalAnswer=true, usedHint=false
|
||||
await saveAnswer(questionId, textInputValue.trim(), true, false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -135,7 +146,8 @@ const TestViewPage: React.FC = () => {
|
||||
if (answer && sessionId) {
|
||||
const timeTaken = Date.now() - startTimeRef.current;
|
||||
try {
|
||||
await saveLearningAnswer(sessionId, currentQ.question.question_id, answer, timeTaken, true);
|
||||
// 🔧 ФИКС (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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user