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; // ============ 🔧 ТИПЫ ОТВЕТОВ (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; 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; // 🔧 ФИКС (23.09.2026): client_controlled_achievement_values — // сервер теперь сам считает streak и возвращает его в ответе. server_streak?: number; 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 ============ // 🔧 ФИКС (24.09.2026): DUPLICATED_FETCH_LOGIC — // общий helper для fetch с таймаутом. Используется в fetchAPI, getTTS, // uploadFeedImage, deleteFeedPost. const fetchWithTimeout = async ( url: string, options: RequestInit = {}, timeoutMs: number = FETCH_TIMEOUT_MS, ): Promise => { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), timeoutMs); try { return await fetch(url, { ...options, signal: controller.signal }); } catch (err: any) { // 🔧 ФИКС (25.09.2026): ABORT_ERROR_NOT_USER_FRIENDLY — // AbortError от таймаута → понятное сообщение. if (err?.name === 'AbortError') { throw new Error('Превышено время ожидания запроса. Проверьте соединение и попробуйте снова.'); } throw err; } finally { clearTimeout(timeoutId); } }; const fetchAPI = async (endpoint: string, options: RequestInit = {}) => { const initData = getInitData(); // 🔧 ФИКС (25.09.2026): EMPTY_INIT_DATA_AUTH_HEADER — // если initData пустой (приложение открыто вне Telegram), // уходил заголовок 'Authorization: tma ' и сервер отвечал 401 // с неинформативной ошибкой. Теперь бросаем понятную ошибку. if (!initData) { throw new Error( 'Telegram initData недоступен. Откройте приложение через Telegram.' ); } // 🔧 ФИКС (23.09.2026): INIT_DATA_IN_URL — initData теперь в заголовке Authorization, // а не в query-строке. Токен больше не попадает в логи сервера, Referer, // историю браузера и кеш Cloudflare. // Формат "tma " — стандарт Telegram Mini Apps. const url = `${API_BASE}${endpoint}`; // 🔧 ФИКС (24.09.2026): CONTENT_TYPE_ON_GET_TRIGGERS_PREFLIGHT — // Content-Type ставим ТОЛЬКО когда есть body (POST/PUT/PATCH). // Для GET — не задаём, чтобы не триггерить CORS preflight. const method = (options.method || 'GET').toUpperCase(); const hasBody = options.body !== undefined && options.body !== null; // Content-Type нужен только для методов с телом (POST/PUT/PATCH/DELETE с body). // Для GET/HEAD — никогда, даже если по ошибке передали body. const needsContentType = hasBody && method !== 'GET' && method !== 'HEAD'; const headers: Record = { 'Authorization': `tma ${initData}`, ...(options.headers as Record || {}), }; if (needsContentType && !headers['Content-Type']) { headers['Content-Type'] = 'application/json'; } // 🔧 ФИКС (24.09.2026): DUPLICATED_FETCH_LOGIC — используем helper. const res = await fetchWithTimeout(url, { ...options, headers, }); if (!res.ok) { const errorText = await res.text(); 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; }; // ============ Пользователь ============ export const registerUser = (): Promise<{ status: string; app_language: string; current_level: string; user_id: number; is_admin: boolean }> => fetchAPI('/users/register', { method: 'POST' }); // 🔧 ФИКС (25.09.2026): DEAD_EXPORT_GET_IS_ADMIN — getIsAdmin удалён, // больше нигде не используется (в App.tsx заменили на data.is_admin из registerUser). 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; }> => fetchAPI('/admin/dashboard'); export const getSentryErrors = (): Promise => fetchAPI('/admin/sentry-errors'); // ============ Прогресс ============ export const fetchProgress = (): Promise => fetchAPI('/game/progress'); // ============ Игра ============ export const getLevel = (levelNumber: number): Promise => fetchAPI(`/game/level/${levelNumber}`); export const checkWord = (levelId: number, cells: number[][]): Promise => fetchAPI('/game/check-word', { method: 'POST', body: JSON.stringify({ level_id: levelId, cells }), }); // 🔧 ФИКС (23.09.2026): client_controlled_achievement_values — // perfect_streak больше НЕ отправляем. Сервер считает сам в check_word. export const completeLevel = (levelId: number, hintsUsed: number, completionTime?: number): Promise => fetchAPI('/game/complete-level', { method: 'POST', body: JSON.stringify({ level_id: levelId, hints_used: hintsUsed, completion_time: completionTime || 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 = (): Promise => fetchAPI('/sentences/next'); export const checkSentence = (sentenceId: number, words: string[], completionTime?: number): Promise => 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 = (): Promise => fetchAPI('/wordquiz/next'); export const checkQuizAnswer = (correctPolish: string, answer: string, mistakes: number, completionTime?: number): Promise => 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 = (): Promise => fetchAPI('/bubblewords/next'); export const completeBubbleLevel = (hintsUsed: number, wordsCount: number, completionTime?: number): Promise => 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 = async (text: string, voice: string = 'female'): Promise => { const initData = getInitData(); // 🔧 ФИКС (25.09.2026): EMPTY_INIT_DATA_AUTH_HEADER — см. fetchAPI. if (!initData) { throw new Error( 'Telegram initData недоступен. Откройте приложение через Telegram.' ); } // 🔧 ФИКС (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)}`; // 🔧 ФИКС (24.09.2026): DUPLICATED_FETCH_LOGIC — используем helper. const res = await fetchWithTimeout(url, { method: 'GET', headers: { 'Authorization': `tma ${initData}`, }, }); if (!res.ok) { const errorText = await res.text(); throw new Error(`API Error: ${res.status} - ${errorText}`); } // 🔧 ФИКС (25.09.2026): TTS_NO_CONTENT_TYPE_CHECK — // если сервер вернул 200 с JSON-ошибкой (например, лимит TTS), // клиент молча возвращал JSON как Blob и пытался проиграть как аудио. // // ⚠️ ВАЖНО: на некоторых деплоях /tts отдаёт `application/octet-stream` // вместо явного `audio/*`. Разрешаем оба варианта, но блокируем JSON/HTML, // чтобы поймать реальные ошибки и captive-portal'ы. const contentType = res.headers.get('content-type') || ''; const isAudio = contentType.includes('audio/'); const isOctetStream = contentType.includes('application/octet-stream'); if (!isAudio && !isOctetStream) { const text = await res.text(); throw new Error( `TTS Error: expected audio, got ${contentType}. Body: ${text.slice(0, 200)}` ); } return res.blob(); }; // ============ 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 }), }); // 🔧 ФИКС (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 => fetchAPI('/assistant/stats/admin'); // ============ Уроки (Learning) ============ export const getLearningLevels = (): Promise => fetchAPI('/learning/levels'); export const getLearningTopics = (level: string) => fetchAPI(`/learning/topics?level=${encodeURIComponent(level)}`); export const getLearningTopic = (topicId: string) => fetchAPI(`/learning/topics/${encodeURIComponent(topicId)}`); export const getLearningLesson = (lessonId: string) => fetchAPI(`/learning/lessons/${encodeURIComponent(lessonId)}`); export const getTopicTest = (topicId: string) => fetchAPI(`/learning/test/${encodeURIComponent(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 = (): Promise => fetchAPI('/achievements'); export const getUserAchievements = () => fetchAPI('/achievements/user'); export const trackLogin = (): Promise => 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; // 🔧 ФИКС (23.09.2026): existing_image_removal_no_delete — // список URL существующих картинок, которые юзер удалил в UI. removed_images?: string[]; } export interface FeedListResponse { posts: FeedPostResponse[]; section: FeedSection; lang: string; } /** * Получить ленту постов для секции. * lang — опционально, если не передан — бэк возьмёт язык из профиля юзера. */ export const getFeedSection = (section: FeedSection, lang?: string): Promise => { const langParam = lang ? `?lang=${encodeURIComponent(lang)}` : ''; return fetchAPI(`/feed/${section}${langParam}`); }; /** * Получить один пост по ID. */ export const getFeedPost = (postId: number, lang?: string): Promise => { 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(); // 🔧 ФИКС (25.09.2026): DELETE_FEED_NO_INIT_DATA_CHECK — // без initData запрос уходит с initData= (пустым) и сервер отвечает 401 // с неинформативной ошибкой. Бросаем понятную ошибку. if (!initData) { throw new Error('Telegram initData недоступен. Откройте приложение через Telegram.'); } const url = `${API_BASE}/admin/feed/post/${postId}/delete?initData=${encodeURIComponent(initData)}`; // 🔧 ФИКС (24.09.2026): DUPLICATED_FETCH_LOGIC — используем helper. const res = await fetchWithTimeout(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(); // 🔧 ФИКС (25.09.2026): EMPTY_INIT_DATA_AUTH_HEADER — см. fetchAPI. if (!initData) { throw new Error( 'Telegram initData недоступен. Откройте приложение через Telegram.' ); } 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); // 🔧 ФИКС (24.09.2026): DUPLICATED_FETCH_LOGIC — используем helper. const res = await fetchWithTimeout(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 => fetchAPI('/admin/content/summary'); // Слова export const getWordLevels = (): Promise<{ levels: ContentWordLevel[] }> => fetchAPI('/admin/content/words/levels'); export const getLevelWords = (level: string, q?: string): Promise => { const params = new URLSearchParams(); if (q) params.set('q', q); const qs = params.toString(); return fetchAPI(`/admin/content/words/level/${encodeURIComponent(level)}${qs ? '?' + qs : ''}`); }; export const getWord = (wordId: number): Promise => 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/${encodeURIComponent(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 => { const params = new URLSearchParams(); if (q) params.set('q', q); const qs = params.toString(); return fetchAPI(`/admin/content/texts/level/${encodeURIComponent(level)}${qs ? '?' + qs : ''}`); }; export const getText = (textId: number): Promise => 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/${encodeURIComponent(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/${encodeURIComponent(level)}/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 => fetchAPI(`/admin/content/lessons/lesson/${encodeURIComponent(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/${encodeURIComponent(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'); // ============ LECTURES (Лекции) ============ export interface LectureListItem { id: number; level_code: string; lecture_language: string; title: string; file_type: string; file_size_kb: number; file_url: string; order_number: number; created_at: string | null; } export interface LecturesListResponse { level: string; lectures: LectureListItem[]; } export interface LectureDetail { id: number; level_code: string; title_pl: string; title_ru: string; title_uk: string; title_en: string; description_pl: string; description_ru: string; description_uk: string; description_en: string; file_type: string; file_size_kb: number; file_url: string; order_number: number; } /** * Получить список лекций для уровня. * Если level не передан — бэк возьмёт из профиля юзера. */ export const getLectures = (level?: string): Promise => { const levelParam = level ? `?level=${encodeURIComponent(level)}` : ''; return fetchAPI(`/learning/lectures${levelParam}`); }; /** * Получить метаданные одной лекции. */ export const getLecture = (lectureId: number): Promise => fetchAPI(`/learning/lecture/${lectureId}`); /** * Скачать файл лекции. * Возвращает blob, который можно сохранить. */ export const downloadLecture = async (lectureId: number): Promise => { const initData = getInitData(); if (!initData) { throw new Error('Telegram initData недоступен. Откройте приложение через Telegram.'); } const url = `${API_BASE}/learning/lecture/${lectureId}/download`; const res = await fetchWithTimeout(url, { method: 'GET', headers: { 'Authorization': `tma ${initData}`, }, }); if (!res.ok) { const errorText = await res.text(); throw new Error(`API Error: ${res.status} - ${errorText}`); } return res.blob(); };