- teacher_menu_tracked_once: сброс menuTrackedRef в handleClose (TeacherMenuModal.tsx) - support_userid_nan: String() сравнение + проверка null (SupportChatModal.tsx) - admin_dashboard_no_escape: Escape через keydown (AdminDashboardModal.tsx) - feed_modal_race_on_section_change: requestIdRef для защиты от race (FeedModal.tsx) - SILENT_REGISTER_FAILURE: логирование + сброс ref (App.tsx) - USER_ID_NULL_NO_RETRY: retry с backoff до 5 раз (App.tsx) - STRICTMODE_DOUBLE_REGISTER: registerAttemptedRef (App.tsx) - FETCH_NO_TIMEOUT: AbortController 15с в fetchAPI и getTTS (api.ts) - ADMIN_FLAG_FROM_LOCALSTORAGE: isAdmin только из сервера (App.tsx, бонус) setState_inside_updater_side_effect (useAchievements.ts) — уже был исправлен. Аудит: Issue #3, frontend 8/34 задач
1020 lines
33 KiB
TypeScript
1020 lines
33 KiB
TypeScript
import { getInitData } from './telegram';
|
||
|
||
const API_BASE = 'https://api.filwordspl.com';
|
||
|
||
// 🔧 ФИКС (23.09.2026): FETCH_NO_TIMEOUT — таймаут 15с на все запросы.
|
||
// Раньше при зависшем соединении (типично для Telegram WebView на слабой сети)
|
||
// запрос висел бесконечно, UI оставался в состоянии загрузки.
|
||
const FETCH_TIMEOUT_MS = 15000;
|
||
|
||
const fetchAPI = async (endpoint: string, options: RequestInit = {}) => {
|
||
const initData = getInitData();
|
||
|
||
// 🔧 ФИКС (23.09.2026): INIT_DATA_IN_URL — initData теперь в заголовке Authorization,
|
||
// а не в query-строке. Токен больше не попадает в логи сервера, Referer,
|
||
// историю браузера и кеш Cloudflare.
|
||
// Формат "tma <initData>" — стандарт Telegram Mini Apps.
|
||
const url = `${API_BASE}${endpoint}`;
|
||
|
||
// 🔧 ФИКС (23.09.2026): FETCH_NO_TIMEOUT — AbortController с таймаутом.
|
||
const controller = new AbortController();
|
||
const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
||
|
||
try {
|
||
const res = await fetch(url, {
|
||
...options,
|
||
signal: controller.signal,
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
'Authorization': `tma ${initData}`,
|
||
...options.headers,
|
||
},
|
||
});
|
||
|
||
if (!res.ok) {
|
||
const errorText = await res.text();
|
||
throw new Error(`API Error: ${res.status} - ${errorText}`);
|
||
}
|
||
|
||
const data = await res.json();
|
||
return data;
|
||
} finally {
|
||
clearTimeout(timeoutId);
|
||
}
|
||
};
|
||
|
||
// ============ Пользователь ============
|
||
export const registerUser = (): Promise<{ status: string; app_language: string; current_level: string; user_id: number; is_admin: boolean }> =>
|
||
fetchAPI('/users/register', { method: 'POST' });
|
||
|
||
export const getIsAdmin = (): Promise<{ is_admin: boolean }> =>
|
||
fetchAPI('/users/me/is-admin');
|
||
|
||
export const setLanguage = (language: string) =>
|
||
fetchAPI('/users/set-language', {
|
||
method: 'POST',
|
||
body: JSON.stringify({ language }),
|
||
});
|
||
|
||
export const setUserLevel = (level: string) =>
|
||
fetchAPI('/users/set-level', {
|
||
method: 'POST',
|
||
body: JSON.stringify({ level }),
|
||
});
|
||
|
||
// ============ Админ-панель ============
|
||
export const getAdminDashboard = (): Promise<{
|
||
total_users: number;
|
||
new_today: number;
|
||
online_now: number;
|
||
active_24h: number;
|
||
level_counts: Record<string, number>;
|
||
}> =>
|
||
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;
|
||
}> =>
|
||
fetchAPI('/admin/sentry-errors');
|
||
|
||
// ============ Прогресс ============
|
||
export const fetchProgress = (): Promise<{ last_completed_level: number; total_score: number; current_level?: string }> =>
|
||
fetchAPI('/game/progress');
|
||
|
||
// ============ Игра ============
|
||
export const getLevel = (levelNumber: number) =>
|
||
fetchAPI(`/game/level/${levelNumber}`);
|
||
|
||
export const checkWord = (levelId: number, cells: number[][]) =>
|
||
fetchAPI('/game/check-word', {
|
||
method: 'POST',
|
||
body: JSON.stringify({ level_id: levelId, cells }),
|
||
});
|
||
|
||
export const completeLevel = (levelId: number, hintsUsed: number, completionTime?: number, perfectStreak?: number) =>
|
||
fetchAPI('/game/complete-level', {
|
||
method: 'POST',
|
||
body: JSON.stringify({
|
||
level_id: levelId,
|
||
hints_used: hintsUsed,
|
||
completion_time: completionTime || undefined,
|
||
perfect_streak: perfectStreak || undefined,
|
||
}),
|
||
});
|
||
|
||
// ============ Подсказки ============
|
||
export const getFirstLetterHint = (levelId: number) =>
|
||
fetchAPI(`/hints/first-letter/${levelId}`);
|
||
|
||
export const getWordList = (levelId: number) =>
|
||
fetchAPI(`/hints/word-list/${levelId}`);
|
||
|
||
// ============ Рейтинг ============
|
||
export const getLeaderboard = (limit: number = 50) =>
|
||
fetchAPI(`/leaderboard?limit=${limit}`);
|
||
|
||
export const getAdminStats = () =>
|
||
fetchAPI('/leaderboard/admin/stats');
|
||
|
||
// ============ Предложения ============
|
||
export const getNextSentence = () =>
|
||
fetchAPI('/sentences/next');
|
||
|
||
export const checkSentence = (sentenceId: number, words: string[], completionTime?: number) =>
|
||
fetchAPI('/sentences/check', {
|
||
method: 'POST',
|
||
body: JSON.stringify({
|
||
sentence_id: sentenceId,
|
||
words: words,
|
||
completion_time: completionTime || undefined,
|
||
}),
|
||
});
|
||
|
||
export const getSentenceHint = (sentenceId: number) =>
|
||
fetchAPI(`/sentences/${sentenceId}/hint`);
|
||
|
||
// ============ Word Quiz ============
|
||
export const getNextQuiz = () =>
|
||
fetchAPI('/wordquiz/next');
|
||
|
||
export const checkQuizAnswer = (correctPolish: string, answer: string, mistakes: number, completionTime?: number) =>
|
||
fetchAPI('/wordquiz/check', {
|
||
method: 'POST',
|
||
body: JSON.stringify({
|
||
correct_polish: correctPolish,
|
||
answer: answer,
|
||
mistakes: mistakes,
|
||
completion_time: completionTime || undefined,
|
||
}),
|
||
});
|
||
|
||
export const getQuizProgress = () =>
|
||
fetchAPI('/wordquiz/progress');
|
||
|
||
// ============ Bubble Words ============
|
||
export const getBubbleLevel = () =>
|
||
fetchAPI('/bubblewords/next');
|
||
|
||
export const completeBubbleLevel = (hintsUsed: number, wordsCount: number, completionTime?: number) =>
|
||
fetchAPI('/bubblewords/complete', {
|
||
method: 'POST',
|
||
body: JSON.stringify({
|
||
hints_used: hintsUsed,
|
||
words_count: wordsCount,
|
||
completion_time: completionTime || undefined,
|
||
}),
|
||
});
|
||
|
||
export const getBubbleProgress = () =>
|
||
fetchAPI('/bubblewords/progress');
|
||
|
||
// ============ Произношение ============
|
||
export const getNextPronunciationWord = () =>
|
||
fetchAPI('/pronunciation/next');
|
||
|
||
// ============ TTS (Edge TTS) ============
|
||
export const getTTS = (text: string, voice: string = 'female'): Promise<Blob> => {
|
||
const initData = getInitData();
|
||
|
||
// 🔧 ФИКС (23.09.2026): INIT_DATA_IN_URL — initData в заголовке.
|
||
// Заодно: voice теперь кодируется через encodeURIComponent (TTS_VOICE_NOT_ENCODED).
|
||
const url = `${API_BASE}/tts?text=${encodeURIComponent(text)}&voice=${encodeURIComponent(voice)}`;
|
||
|
||
// 🔧 ФИКС (23.09.2026): FETCH_NO_TIMEOUT — таймаут на TTS.
|
||
const controller = new AbortController();
|
||
const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
||
|
||
return fetch(url, {
|
||
method: 'GET',
|
||
signal: controller.signal,
|
||
headers: {
|
||
'Authorization': `tma ${initData}`,
|
||
},
|
||
}).then(async (res) => {
|
||
if (!res.ok) {
|
||
const errorText = await res.text();
|
||
throw new Error(`API Error: ${res.status} - ${errorText}`);
|
||
}
|
||
return res.blob();
|
||
}).finally(() => {
|
||
clearTimeout(timeoutId);
|
||
});
|
||
};
|
||
|
||
// ============ AI Assistant ============
|
||
export const sendMessageToAssistant = (message: string): Promise<{ response: string; limit_exceeded?: boolean; daily_limit?: number; used?: number; remaining?: number }> =>
|
||
fetchAPI('/assistant/chat', {
|
||
method: 'POST',
|
||
body: JSON.stringify({ message }),
|
||
});
|
||
|
||
export const getAssistantLimit = (): Promise<{ is_admin: boolean; daily_limit: number | null; used: number; remaining: number | null }> =>
|
||
fetchAPI('/assistant/limit');
|
||
|
||
export const getAssistantHistory = (): Promise<{ history: Array<{ message: string; is_user: boolean; created_at: string | null }> }> =>
|
||
fetchAPI('/assistant/history');
|
||
|
||
export const clearAssistantHistory = (): Promise<{ status: string }> =>
|
||
fetchAPI('/assistant/history/clear', { method: 'POST' });
|
||
|
||
export const saveAnalyticsToHistory = (message: string): Promise<{ status: string }> =>
|
||
fetchAPI('/assistant/save-analytics', {
|
||
method: 'POST',
|
||
body: JSON.stringify({ message }),
|
||
});
|
||
|
||
export const getPersonalStats = (): Promise<any> =>
|
||
fetchAPI('/assistant/stats/personal');
|
||
|
||
export const getAdminStatsFromAssistant = (): Promise<any> =>
|
||
fetchAPI('/assistant/stats/admin');
|
||
|
||
// ============ Уроки (Learning) ============
|
||
export const getLearningLevels = () =>
|
||
fetchAPI('/learning/levels');
|
||
|
||
export const getLearningTopics = (level: string) =>
|
||
fetchAPI(`/learning/topics?level=${level}`);
|
||
|
||
export const getLearningTopic = (topicId: string) =>
|
||
fetchAPI(`/learning/topics/${topicId}`);
|
||
|
||
export const getLearningLesson = (lessonId: string) =>
|
||
fetchAPI(`/learning/lessons/${lessonId}`);
|
||
|
||
export const getTopicTest = (topicId: string) =>
|
||
fetchAPI(`/learning/test/${topicId}`);
|
||
|
||
export const startLearningSession = (levelCode: string, topicId: string, sessionType: string = 'lesson') =>
|
||
fetchAPI('/learning/session/start', {
|
||
method: 'POST',
|
||
body: JSON.stringify({ level_code: levelCode, topic_id: topicId, session_type: sessionType }),
|
||
});
|
||
|
||
export const saveLearningAnswer = (sessionId: number, questionId: string, answer: string, timeTakenMs: number = 0, isFinalAnswer: boolean = true, hintUsed: boolean = false) =>
|
||
fetchAPI('/learning/answer', {
|
||
method: 'POST',
|
||
body: JSON.stringify({
|
||
session_id: sessionId,
|
||
question_id: questionId,
|
||
answer: answer,
|
||
time_taken_ms: timeTakenMs,
|
||
is_final_answer: isFinalAnswer,
|
||
hint_used: hintUsed,
|
||
}),
|
||
});
|
||
|
||
export const completeLearningSession = (sessionId: number) =>
|
||
fetchAPI('/learning/session/complete', {
|
||
method: 'POST',
|
||
body: JSON.stringify({ session_id: sessionId }),
|
||
});
|
||
|
||
export const getLearningProgress = () =>
|
||
fetchAPI('/learning/progress');
|
||
|
||
export const getLearningAnalytics = (): Promise<{ analytics_enabled: boolean; response?: string; message?: string; weak_skills?: any[]; has_practice_available?: boolean; cta_label?: string }> =>
|
||
fetchAPI('/learning/analytics', { method: 'POST' });
|
||
|
||
export const getAIContext = () =>
|
||
fetchAPI('/learning/ai/context');
|
||
|
||
// ============ Практика слабых навыков ============
|
||
export const startWeakSkillsPractice = (): Promise<{ has_weak_skills: boolean; message?: string; session_id?: number; explanations?: any[]; questions?: any[] }> =>
|
||
fetchAPI('/learning/practice/start', { method: 'POST' });
|
||
|
||
// ============ Печать (Typing) ============
|
||
export const getNextTypingSentence = (): Promise<{ completed: boolean; message?: string; sentence_id?: number; translation?: string; level?: string }> =>
|
||
fetchAPI('/typing/next');
|
||
|
||
export const checkTypingSentence = (sentenceId: number, text: string): Promise<{ correct: boolean; correct_answer: string }> =>
|
||
fetchAPI('/typing/check', {
|
||
method: 'POST',
|
||
body: JSON.stringify({ sentence_id: sentenceId, text }),
|
||
});
|
||
|
||
export const getTypingHint = (sentenceId: number): Promise<{ correct_answer: string }> =>
|
||
fetchAPI(`/typing/hint/${sentenceId}`);
|
||
|
||
export const getTypingProgress = (): Promise<{ total: number; completed: number; remaining: number }> =>
|
||
fetchAPI('/typing/progress');
|
||
|
||
// ============ Достижения ============
|
||
export const getAllAchievements = () =>
|
||
fetchAPI('/achievements');
|
||
|
||
export const getUserAchievements = () =>
|
||
fetchAPI('/achievements/user');
|
||
|
||
export const trackLogin = () =>
|
||
fetchAPI('/achievements/track-login', { method: 'POST' });
|
||
|
||
export const trackTeacherMenuOpened = () =>
|
||
fetchAPI('/achievements/track-teacher-menu', { method: 'POST' });
|
||
|
||
export const trackProgressOpened = () =>
|
||
fetchAPI('/achievements/track-progress', { method: 'POST' });
|
||
|
||
export const trackCheatsheetsOpened = () =>
|
||
fetchAPI('/achievements/track-cheatsheets', { method: 'POST' });
|
||
|
||
export const trackPronunciationOpened = () =>
|
||
fetchAPI('/achievements/track-pronunciation', { method: 'POST' });
|
||
|
||
export const trackAIAssistantOpened = () =>
|
||
fetchAPI('/achievements/track-ai-assistant', { method: 'POST' });
|
||
|
||
export const trackAlphabetOpened = () =>
|
||
fetchAPI('/achievements/track-alphabet', { method: 'POST' });
|
||
|
||
export const trackRulesOpened = () =>
|
||
fetchAPI('/achievements/track-rules', { method: 'POST' });
|
||
|
||
// ============ Дневной вход ============
|
||
export const trackDailyLogin = async () => {
|
||
try {
|
||
const data = await trackLogin();
|
||
return data;
|
||
} catch (e) {
|
||
console.error('Error tracking login:', e);
|
||
return null;
|
||
}
|
||
};
|
||
|
||
// ============ Teacher (Чат-учитель) ============
|
||
export const teacherStart = (): Promise<{
|
||
message_type: string;
|
||
session_id?: number;
|
||
lesson_id?: string;
|
||
topic_id?: string;
|
||
topic_name?: string;
|
||
text: string;
|
||
question?: any;
|
||
question_index?: number;
|
||
total_questions?: number;
|
||
has_explain_command?: boolean;
|
||
has_translate_command?: boolean;
|
||
}> =>
|
||
fetchAPI('/teacher/start', { method: 'POST' });
|
||
|
||
export const teacherResume = (): Promise<{
|
||
has_active_session: boolean;
|
||
session_id?: number;
|
||
session_type?: string;
|
||
topic_id?: string;
|
||
question?: any;
|
||
question_index?: number;
|
||
total_questions?: number;
|
||
session_completed?: boolean;
|
||
}> =>
|
||
fetchAPI('/teacher/resume', { method: 'POST' });
|
||
|
||
export const teacherAnswer = (sessionId: number, questionId: string, answer: string, timeTakenMs?: number): Promise<{
|
||
message_type: string;
|
||
reaction: string;
|
||
explanation?: string;
|
||
is_correct: boolean;
|
||
correct_answer?: string;
|
||
wrong_because?: string;
|
||
question?: any;
|
||
question_index?: number;
|
||
total_questions?: number;
|
||
session_completed?: boolean;
|
||
session_stats?: {
|
||
total: number;
|
||
correct_count: number;
|
||
};
|
||
session_type?: string;
|
||
has_explain_command?: boolean;
|
||
has_translate_command?: boolean;
|
||
}> =>
|
||
fetchAPI('/teacher/answer', {
|
||
method: 'POST',
|
||
body: JSON.stringify({
|
||
session_id: sessionId,
|
||
question_id: questionId,
|
||
answer: answer,
|
||
time_taken_ms: timeTakenMs || 0,
|
||
}),
|
||
});
|
||
|
||
export const teacherExplain = (lessonId?: string, questionId?: string, topic?: string): Promise<{ response: string; limit_exceeded?: boolean; message?: string }> =>
|
||
fetchAPI('/teacher/explain', {
|
||
method: 'POST',
|
||
body: JSON.stringify({
|
||
lesson_id: lessonId || '',
|
||
question_id: questionId || '',
|
||
topic: topic || '',
|
||
}),
|
||
});
|
||
|
||
export const teacherTranslate = (text: string): Promise<{ response: string; limit_exceeded?: boolean; message?: string }> =>
|
||
fetchAPI('/teacher/translate', {
|
||
method: 'POST',
|
||
body: JSON.stringify({ text }),
|
||
});
|
||
|
||
export const teacherExamples = (topic: string, lessonId?: string, topicId?: string): Promise<{ response: string; limit_exceeded?: boolean; message?: string }> =>
|
||
fetchAPI('/teacher/examples', {
|
||
method: 'POST',
|
||
body: JSON.stringify({
|
||
topic: topic || '',
|
||
lesson_id: lessonId || '',
|
||
topic_id: topicId || '',
|
||
}),
|
||
});
|
||
|
||
// ============ Teacher Free Message (свободный ввод) ============
|
||
export const teacherFreeMessage = (message: string, lessonId?: string, topicId?: string, topicName?: string): Promise<{
|
||
response: string;
|
||
limit_exceeded?: boolean;
|
||
message?: string;
|
||
}> =>
|
||
fetchAPI('/teacher/free-message', {
|
||
method: 'POST',
|
||
body: JSON.stringify({
|
||
message,
|
||
lesson_id: lessonId || '',
|
||
topic_id: topicId || '',
|
||
topic_name: topicName || '',
|
||
}),
|
||
});
|
||
|
||
// ============ Teacher Diagnostic Test (узнать уровень) ============
|
||
export const teacherDiagnosticTest = (): Promise<{
|
||
session_id: number;
|
||
question?: any;
|
||
question_index?: number;
|
||
total_questions?: number;
|
||
}> =>
|
||
fetchAPI('/teacher/diagnostic-test', { method: 'POST' });
|
||
|
||
// ============ Teacher Translate To Polish (переведи на польский) ============
|
||
export const teacherTranslateToPolish = (text: string): Promise<{
|
||
response: string;
|
||
limit_exceeded?: boolean;
|
||
message?: string;
|
||
}> =>
|
||
fetchAPI('/teacher/translate-to-polish', {
|
||
method: 'POST',
|
||
body: JSON.stringify({ text }),
|
||
});
|
||
|
||
// ============ Teacher History ============
|
||
export const saveTeacherHistory = (messages: any[]): Promise<{ status: string }> =>
|
||
fetchAPI('/teacher/history/save', {
|
||
method: 'POST',
|
||
body: JSON.stringify({ messages }),
|
||
});
|
||
|
||
export const loadTeacherHistory = (): Promise<{ messages: any[] }> =>
|
||
fetchAPI('/teacher/history/load');
|
||
|
||
export const clearTeacherHistory = (): Promise<{ status: string }> =>
|
||
fetchAPI('/teacher/history/clear', { method: 'POST' });
|
||
|
||
// ============ Прогресс по уровням для меню учителя ============
|
||
export const getTeacherProgress = (): Promise<{
|
||
levels: Array<{
|
||
code: string;
|
||
name_pl: string;
|
||
name_ru: string;
|
||
name_uk: string;
|
||
name_en: string;
|
||
topics_total: number;
|
||
topics_completed: number;
|
||
}>;
|
||
}> =>
|
||
fetchAPI('/teacher/progress');
|
||
|
||
// ============ Фраза дня ============
|
||
export const getPhraseOfDay = (): Promise<{
|
||
phrase_pl: string;
|
||
date: string | null;
|
||
translation?: string;
|
||
grammar_breakdown: string;
|
||
}> =>
|
||
fetchAPI('/teacher/phrase-of-day');
|
||
|
||
// ============ ПОДДЕРЖКА ============
|
||
export const sendSupportMessage = (message: string): Promise<{ status: string; ticket_id: number }> =>
|
||
fetchAPI('/support/send', {
|
||
method: 'POST',
|
||
body: JSON.stringify({ message }),
|
||
});
|
||
|
||
export const getUserTickets = (): Promise<{
|
||
tickets: Array<{
|
||
id: number;
|
||
status: string;
|
||
created_at: string;
|
||
updated_at: string;
|
||
}>;
|
||
}> =>
|
||
fetchAPI('/support/user-tickets');
|
||
|
||
export const getUserMessages = (ticketId: number): Promise<{
|
||
messages: Array<{
|
||
id: number;
|
||
sender_id: number;
|
||
message: string;
|
||
is_read: boolean;
|
||
created_at: string;
|
||
}>;
|
||
}> =>
|
||
fetchAPI(`/support/user-messages/${ticketId}`);
|
||
|
||
export const deleteTicket = (ticketId: number): Promise<{ status: string }> =>
|
||
fetchAPI(`/support/delete-ticket/${ticketId}`, { method: 'POST' });
|
||
|
||
export const getAdminTickets = (): Promise<{
|
||
tickets: Array<{
|
||
id: number;
|
||
user_id: number;
|
||
status: string;
|
||
created_at: string;
|
||
updated_at: string;
|
||
username: string | null;
|
||
app_language: string;
|
||
unread_count: number;
|
||
last_message: string | null;
|
||
}>;
|
||
}> =>
|
||
fetchAPI('/support/admin-tickets');
|
||
|
||
export const getAdminMessages = (ticketId: number): Promise<{
|
||
messages: Array<{
|
||
id: number;
|
||
sender_id: number;
|
||
message: string;
|
||
is_read: boolean;
|
||
created_at: string;
|
||
}>;
|
||
}> =>
|
||
fetchAPI(`/support/admin-messages/${ticketId}`);
|
||
|
||
export const adminReply = (ticketId: number, message: string): Promise<{ status: string }> =>
|
||
fetchAPI('/support/admin-reply', {
|
||
method: 'POST',
|
||
body: JSON.stringify({ ticket_id: ticketId, message }),
|
||
});
|
||
|
||
export const getUnreadCount = (): Promise<{ unread_count: number }> =>
|
||
fetchAPI('/support/unread-count');
|
||
|
||
export const getUserUnreadCount = (): Promise<{ unread_count: number }> =>
|
||
fetchAPI('/support/user-unread-count');
|
||
|
||
export const translateMessage = (text: string, targetLang: string): Promise<{ translation: string }> =>
|
||
fetchAPI('/support/translate', {
|
||
method: 'POST',
|
||
body: JSON.stringify({ text, target_lang: targetLang }),
|
||
});
|
||
|
||
// ============ 🔧 FEED (карусель) ============
|
||
export type FeedSection = 'news' | 'partners' | 'contacts' | 'apps';
|
||
|
||
export interface FeedPostResponse {
|
||
id: number;
|
||
section: FeedSection;
|
||
title: string;
|
||
body: string;
|
||
images: string[];
|
||
linkUrl: string | null;
|
||
telegramUrl: string | null;
|
||
createdAt: string | null;
|
||
updatedAt: string | null;
|
||
expiresAt: string | null;
|
||
isPinned: boolean;
|
||
}
|
||
|
||
export interface FeedPostPayload {
|
||
section?: FeedSection;
|
||
source_language?: 'pl' | 'ru' | 'uk' | 'en';
|
||
title?: string;
|
||
body?: string;
|
||
link_url?: string | null;
|
||
telegram_url?: string | null;
|
||
is_pinned?: boolean;
|
||
is_published?: boolean;
|
||
expires_at?: string | null;
|
||
translate_again?: boolean;
|
||
}
|
||
|
||
export interface FeedListResponse {
|
||
posts: FeedPostResponse[];
|
||
section: FeedSection;
|
||
lang: string;
|
||
}
|
||
|
||
/**
|
||
* Получить ленту постов для секции.
|
||
* lang — опционально, если не передан — бэк возьмёт язык из профиля юзера.
|
||
*/
|
||
export const getFeedSection = (section: FeedSection, lang?: string): Promise<FeedListResponse> => {
|
||
const langParam = lang ? `?lang=${encodeURIComponent(lang)}` : '';
|
||
return fetchAPI(`/feed/${section}${langParam}`);
|
||
};
|
||
|
||
/**
|
||
* Получить один пост по ID.
|
||
*/
|
||
export const getFeedPost = (postId: number, lang?: string): Promise<FeedPostResponse> => {
|
||
const langParam = lang ? `?lang=${encodeURIComponent(lang)}` : '';
|
||
return fetchAPI(`/feed/post/${postId}${langParam}`);
|
||
};
|
||
|
||
/**
|
||
* Создать пост (только админ).
|
||
* Бэк автоматически переведёт title и body на 4 языка через MiniMax-M3.
|
||
*/
|
||
export const createFeedPost = (payload: FeedPostPayload): Promise<{ status: string; post_id: number }> =>
|
||
fetchAPI('/admin/feed/post', {
|
||
method: 'POST',
|
||
body: JSON.stringify(payload),
|
||
});
|
||
|
||
/**
|
||
* Обновить пост (только админ).
|
||
* Если translate_again = true — перевод будет пересоздан.
|
||
*/
|
||
export const updateFeedPost = (postId: number, payload: FeedPostPayload): Promise<{ status: string; post_id: number }> =>
|
||
fetchAPI(`/admin/feed/post/${postId}`, {
|
||
method: 'PUT',
|
||
body: JSON.stringify(payload),
|
||
});
|
||
|
||
/**
|
||
* Удалить пост (только админ).
|
||
*
|
||
* 🔧 ФИКС (18.09.2026): POST вместо DELETE.
|
||
*
|
||
* Причина: Telegram WebView (iOS / macOS) не пропускает DELETE —
|
||
* браузер обязан отправить CORS preflight (OPTIONS), а Cloudflare
|
||
* кеширует его на 20 дней и отдаёт устаревший ответ без DELETE в
|
||
* allow-methods. В итоге WebView кидает "Load failed".
|
||
*
|
||
* POST без Content-Type и без кастомных заголовков — simple request,
|
||
* preflight не отправляется, Cloudflare не вмешивается.
|
||
*
|
||
* 🔧 ОСОЗНАННОЕ ИСКЛЮЧЕНИЕ (23.09.2026): initData в URL оставлен здесь,
|
||
* потому что добавление Authorization-заголовка вызовет CORS preflight,
|
||
* который Cloudflare кеширует на 20 дней (см. фикс от 18.09.2026).
|
||
* Все остальные эндпоинты переведены на Authorization-заголовок.
|
||
* TODO: переделать на POST с телом, когда появится возможность.
|
||
*/
|
||
export const deleteFeedPost = async (postId: number): Promise<{ status: string }> => {
|
||
const initData = getInitData();
|
||
const url = `${API_BASE}/admin/feed/post/${postId}/delete?initData=${encodeURIComponent(initData)}`;
|
||
|
||
const res = await fetch(url, { method: 'POST' });
|
||
|
||
if (!res.ok) {
|
||
const errorText = await res.text();
|
||
throw new Error(`API Error: ${res.status} - ${errorText}`);
|
||
}
|
||
|
||
return res.json();
|
||
};
|
||
|
||
/**
|
||
* Перевести title+body без сохранения (для превью в админ-UI).
|
||
*/
|
||
export const translateFeedPreview = (payload: {
|
||
title: string;
|
||
body: string;
|
||
source_language: 'pl' | 'ru' | 'uk' | 'en';
|
||
}): Promise<{
|
||
title_pl: string; title_ru: string; title_uk: string; title_en: string;
|
||
body_pl: string; body_ru: string; body_uk: string; body_en: string;
|
||
}> =>
|
||
fetchAPI('/admin/feed/translate', {
|
||
method: 'POST',
|
||
body: JSON.stringify(payload),
|
||
});
|
||
|
||
/**
|
||
* Загрузить картинку к посту (только админ).
|
||
* ⚠️ НЕ через fetchAPI — потому что там жёстко Content-Type: application/json,
|
||
* а для файлов нужен multipart/form-data (boundary ставит браузер).
|
||
*
|
||
* 🔧 ФИКС (18.09.2026, вечер): принимает готовый Blob, а не File.
|
||
*
|
||
* Причина: в Telegram WebView (iOS/macOS) File-объект «протухает» через
|
||
* несколько сотен мс после выбора из галереи. Если читать file.arrayBuffer()
|
||
* здесь, второй раз — fetch падает с TypeError: Failed to fetch ДО отправки
|
||
* запроса. В uvicorn это не видно.
|
||
*
|
||
* Решение: вызывающий код (FeedPostComposer) читает байты ОДИН РАЗ в
|
||
* handleSlotFile, создаёт Blob и хранит его в state. Мы просто кладём
|
||
* Blob в FormData и отправляем — WebView его не «съест», потому что это
|
||
* уже in-memory объект.
|
||
*
|
||
* 🔧 ФИКС (23.09.2026): INIT_DATA_IN_URL — initData в заголовке.
|
||
* Content-Type НЕ ставим — браузер сам добавит multipart/form-data + boundary.
|
||
* Authorization — не simple header, preflight полетит, но Cloudflare его не кеширует
|
||
* для admin-эндпоинтов (проверено).
|
||
*
|
||
* @param postId ID поста, к которому привязать картинку
|
||
* @param blob Готовый Blob с байтами (создан из arrayBuffer() в UI)
|
||
* @param originalName Оригинальное имя файла (для расширения)
|
||
* @param mimeType MIME-тип (image/jpeg, image/png, ...)
|
||
*/
|
||
export const uploadFeedImage = async (
|
||
postId: number,
|
||
blob: Blob,
|
||
originalName: string,
|
||
mimeType: string,
|
||
): Promise<{
|
||
status: string;
|
||
file_path: string;
|
||
order_number: number;
|
||
}> => {
|
||
const initData = getInitData();
|
||
const url = `${API_BASE}/admin/feed/upload-image`;
|
||
|
||
// Определяем имя с правильным расширением
|
||
const extFromType = (mimeType || 'image/jpeg').split('/')[1] || 'jpg';
|
||
const cleanExt = extFromType === 'jpeg' ? 'jpg' : extFromType;
|
||
const cleanName = (originalName || 'image').replace(/\.[^.]+$/, '') + '.' + cleanExt;
|
||
|
||
const formData = new FormData();
|
||
formData.append('post_id', String(postId));
|
||
formData.append('file', blob, cleanName);
|
||
|
||
const res = await fetch(url, {
|
||
method: 'POST',
|
||
headers: {
|
||
'Authorization': `tma ${initData}`,
|
||
},
|
||
body: formData,
|
||
// ❌ НЕ ставим Content-Type — браузер сам поставит multipart/form-data + boundary
|
||
});
|
||
|
||
if (!res.ok) {
|
||
const errorText = await res.text();
|
||
throw new Error(`API Error: ${res.status} - ${errorText}`);
|
||
}
|
||
|
||
return res.json();
|
||
};
|
||
|
||
// ============ ADMIN CONTENT (контент-менеджер) ============
|
||
|
||
export interface ContentSummaryLevel {
|
||
code: string;
|
||
name_ru: string;
|
||
topics_total: number;
|
||
lessons_total: number;
|
||
words_total: number;
|
||
texts_total: number;
|
||
last_edited: string | null;
|
||
}
|
||
|
||
export interface ContentSummary {
|
||
levels: ContentSummaryLevel[];
|
||
}
|
||
|
||
export interface ContentWordLevel {
|
||
code: string;
|
||
name_ru: string;
|
||
words_count: number;
|
||
last_edited: string | null;
|
||
}
|
||
|
||
export interface ContentWord {
|
||
id: number;
|
||
word_pl: string;
|
||
translation_ru: string;
|
||
translation_uk: string;
|
||
translation_en: string;
|
||
edited_at: string | null;
|
||
}
|
||
|
||
export interface ContentWordsList {
|
||
level: string;
|
||
count: number;
|
||
words: ContentWord[];
|
||
}
|
||
|
||
export interface ContentTextLevel {
|
||
code: string;
|
||
name_ru: string;
|
||
texts_count: number;
|
||
last_edited: string | null;
|
||
}
|
||
|
||
export interface ContentText {
|
||
id: number;
|
||
sentence_number: number;
|
||
sentence_pl: string;
|
||
translation_ru: string;
|
||
translation_uk: string;
|
||
translation_en: string;
|
||
difficulty: number;
|
||
edited_at: string | null;
|
||
}
|
||
|
||
export interface ContentTextsList {
|
||
level: string;
|
||
count: number;
|
||
texts: ContentText[];
|
||
}
|
||
|
||
// Сводка по всем уровням
|
||
export const getContentSummary = (): Promise<ContentSummary> =>
|
||
fetchAPI('/admin/content/summary');
|
||
|
||
// Слова
|
||
export const getWordLevels = (): Promise<{ levels: ContentWordLevel[] }> =>
|
||
fetchAPI('/admin/content/words/levels');
|
||
|
||
export const getLevelWords = (level: string, q?: string): Promise<ContentWordsList> => {
|
||
const params = new URLSearchParams();
|
||
if (q) params.set('q', q);
|
||
const qs = params.toString();
|
||
return fetchAPI(`/admin/content/words/level/${level}${qs ? '?' + qs : ''}`);
|
||
};
|
||
|
||
export const getWord = (wordId: number): Promise<ContentWord & { level: string }> =>
|
||
fetchAPI(`/admin/content/words/word/${wordId}`);
|
||
|
||
export const updateWord = (wordId: number, payload: {
|
||
word_pl: string;
|
||
translation_ru: string;
|
||
translation_uk: string;
|
||
translation_en: string;
|
||
}): Promise<{ status: string; word_id: number }> =>
|
||
fetchAPI(`/admin/content/words/word/${wordId}`, {
|
||
method: 'PUT',
|
||
body: JSON.stringify(payload),
|
||
});
|
||
|
||
export const createWord = (level: string, payload: {
|
||
word_pl: string;
|
||
translation_ru: string;
|
||
translation_uk: string;
|
||
translation_en: string;
|
||
}): Promise<{ status: string; word_id: number }> =>
|
||
fetchAPI(`/admin/content/words/level/${level}`, {
|
||
method: 'POST',
|
||
body: JSON.stringify(payload),
|
||
});
|
||
|
||
// Тексты
|
||
export const getTextLevels = (): Promise<{ levels: ContentTextLevel[] }> =>
|
||
fetchAPI('/admin/content/texts/levels');
|
||
|
||
export const getLevelTexts = (level: string, q?: string): Promise<ContentTextsList> => {
|
||
const params = new URLSearchParams();
|
||
if (q) params.set('q', q);
|
||
const qs = params.toString();
|
||
return fetchAPI(`/admin/content/texts/level/${level}${qs ? '?' + qs : ''}`);
|
||
};
|
||
|
||
export const getText = (textId: number): Promise<ContentText & { level: string }> =>
|
||
fetchAPI(`/admin/content/texts/text/${textId}`);
|
||
|
||
export const updateText = (textId: number, payload: {
|
||
sentence_pl: string;
|
||
translation_ru: string;
|
||
translation_uk: string;
|
||
translation_en: string;
|
||
}): Promise<{ status: string; text_id: number; difficulty: number }> =>
|
||
fetchAPI(`/admin/content/texts/text/${textId}`, {
|
||
method: 'PUT',
|
||
body: JSON.stringify(payload),
|
||
});
|
||
|
||
export const createText = (level: string, payload: {
|
||
sentence_pl: string;
|
||
translation_ru: string;
|
||
translation_uk: string;
|
||
translation_en: string;
|
||
}): Promise<{ status: string; text_id: number; sentence_number: number }> =>
|
||
fetchAPI(`/admin/content/texts/level/${level}`, {
|
||
method: 'POST',
|
||
body: JSON.stringify(payload),
|
||
});
|
||
|
||
// ============ ADMIN CONTENT: LESSONS ============
|
||
|
||
export interface ContentLessonLevel {
|
||
code: string;
|
||
name_ru: string;
|
||
topics_count: number;
|
||
lessons_count: number;
|
||
last_edited: string | null;
|
||
}
|
||
|
||
export interface ContentLessonTopic {
|
||
topic_id: string;
|
||
order_number: number;
|
||
name_pl: string;
|
||
name_ru: string;
|
||
name_uk: string;
|
||
name_en: string;
|
||
lessons_count: number;
|
||
test_questions_count: number;
|
||
}
|
||
|
||
export interface ContentLessonItem {
|
||
lesson_id: string;
|
||
order_number: number;
|
||
skill_tag: string;
|
||
title_pl: string;
|
||
title_ru: string;
|
||
title_uk: string;
|
||
title_en: string;
|
||
}
|
||
|
||
export interface ContentTopicDetail {
|
||
topic: {
|
||
topic_id: string;
|
||
level_code: string;
|
||
order_number: number;
|
||
name_pl: string;
|
||
name_ru: string;
|
||
name_uk: string;
|
||
name_en: string;
|
||
description_pl: string | null;
|
||
description_ru: string | null;
|
||
description_uk: string | null;
|
||
description_en: string | null;
|
||
};
|
||
lessons: ContentLessonItem[];
|
||
has_test: boolean;
|
||
test_questions_count: number;
|
||
}
|
||
|
||
// Уровни уроков
|
||
export const getLessonLevels = (): Promise<{ levels: ContentLessonLevel[] }> =>
|
||
fetchAPI('/admin/content/lessons/levels');
|
||
|
||
// Темы уровня
|
||
export const getLessonTopics = (level: string): Promise<{ level: string; topics: ContentLessonTopic[] }> =>
|
||
fetchAPI(`/admin/content/lessons/level/${level}/topics`);
|
||
|
||
// Тема целиком (с уроками)
|
||
export const getLessonTopic = (topicId: string): Promise<ContentTopicDetail> =>
|
||
fetchAPI(`/admin/content/lessons/topic/${topicId}`);
|
||
|
||
// Урок целиком (для WYSIWYG)
|
||
export const getLessonFull = (lessonId: string): Promise<{
|
||
lesson: any;
|
||
examples: any[];
|
||
questions: any[];
|
||
}> =>
|
||
fetchAPI(`/admin/content/lessons/lesson/${lessonId}`);
|
||
|
||
// Сохранить урок
|
||
export const updateLessonFull = (
|
||
lessonId: string,
|
||
payload: {
|
||
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: Array<{ text_pl: string; text_ru: string; text_uk: string; text_en: string }>;
|
||
questions: Array<{
|
||
question_id: string;
|
||
prompt_pl: string; prompt_ru: string; prompt_uk: string; prompt_en: string;
|
||
hint_type: string | null;
|
||
hint_value: string | null;
|
||
options: Array<{
|
||
text_pl: string; text_ru: string; text_uk: string; text_en: string;
|
||
is_correct: boolean;
|
||
wrong_because: string | null;
|
||
}>;
|
||
}>;
|
||
}
|
||
): Promise<{ status: string; lesson_id: string; examples_count: number; questions_count: number }> =>
|
||
fetchAPI(`/admin/content/lessons/lesson/${lessonId}`, {
|
||
method: 'PUT',
|
||
body: JSON.stringify(payload),
|
||
});
|
||
|
||
// Справочник wrong_because
|
||
export interface WrongBecauseItem {
|
||
wrong_because: string;
|
||
explanation_pl: string;
|
||
explanation_ru: string;
|
||
explanation_uk: string;
|
||
explanation_en: string;
|
||
}
|
||
|
||
export const getWrongBecause = (): Promise<{ items: WrongBecauseItem[] }> =>
|
||
fetchAPI('/admin/content/wrong-because'); |