Merge pull request #65 from BEDOLAGA-DEV/dev

Dev
This commit is contained in:
Egor
2026-01-20 14:46:26 +03:00
committed by GitHub
10 changed files with 418 additions and 5 deletions

View File

@@ -1,8 +1,10 @@
import { lazy, Suspense } from 'react'
import { Routes, Route, Navigate, useLocation } from 'react-router-dom'
import { useAuthStore } from './store/auth'
import { useBlockingStore } from './store/blocking'
import Layout from './components/layout/Layout'
import PageLoader from './components/common/PageLoader'
import { MaintenanceScreen, ChannelSubscriptionScreen } from './components/blocking'
import { saveReturnUrl } from './utils/token'
// Auth pages - load immediately (small)
@@ -89,8 +91,24 @@ function LazyPage({ children }: { children: React.ReactNode }) {
)
}
function BlockingOverlay() {
const { blockingType } = useBlockingStore()
if (blockingType === 'maintenance') {
return <MaintenanceScreen />
}
if (blockingType === 'channel_subscription') {
return <ChannelSubscriptionScreen />
}
return null
}
function App() {
return (
<>
<BlockingOverlay />
<Routes>
{/* Public routes */}
<Route path="/login" element={<Login />} />
@@ -316,6 +334,7 @@ function App() {
{/* Catch all */}
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</>
)
}

View File

@@ -1,5 +1,6 @@
import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios'
import { tokenStorage, isTokenExpired, tokenRefreshManager, safeRedirectToLogin } from '../utils/token'
import { useBlockingStore } from '../store/blocking'
const API_BASE_URL = import.meta.env.VITE_API_URL || '/api'
@@ -87,12 +88,57 @@ apiClient.interceptors.request.use(async (config: InternalAxiosRequestConfig) =>
return config
})
// Response interceptor - handle 401 as fallback
// Custom error types for special handling
export interface MaintenanceError {
code: 'maintenance'
message: string
reason?: string
}
export interface ChannelSubscriptionError {
code: 'channel_subscription_required'
message: string
channel_link?: string
}
export function isMaintenanceError(error: unknown): error is { response: { status: 503, data: { detail: MaintenanceError } } } {
if (!error || typeof error !== 'object') return false
const err = error as AxiosError<{ detail: MaintenanceError }>
return err.response?.status === 503 && err.response?.data?.detail?.code === 'maintenance'
}
export function isChannelSubscriptionError(error: unknown): error is { response: { status: 403, data: { detail: ChannelSubscriptionError } } } {
if (!error || typeof error !== 'object') return false
const err = error as AxiosError<{ detail: ChannelSubscriptionError }>
return err.response?.status === 403 && err.response?.data?.detail?.code === 'channel_subscription_required'
}
// Response interceptor - handle 401, 503 (maintenance), 403 (channel subscription)
apiClient.interceptors.response.use(
(response) => response,
async (error: AxiosError) => {
const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean }
// Handle maintenance mode (503)
if (isMaintenanceError(error)) {
const detail = (error.response?.data as { detail: MaintenanceError }).detail
useBlockingStore.getState().setMaintenance({
message: detail.message,
reason: detail.reason,
})
return Promise.reject(error)
}
// Handle channel subscription required (403)
if (isChannelSubscriptionError(error)) {
const detail = (error.response?.data as { detail: ChannelSubscriptionError }).detail
useBlockingStore.getState().setChannelSubscription({
message: detail.message,
channel_link: detail.channel_link,
})
return Promise.reject(error)
}
// Если получили 401 и ещё не пробовали refresh (на случай если проверка exp не сработала)
if (error.response?.status === 401 && !originalRequest._retry) {
originalRequest._retry = true

View File

@@ -0,0 +1,155 @@
import { useState, useEffect, useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { useBlockingStore } from '../../store/blocking'
import { apiClient } from '../../api/client'
const CHECK_COOLDOWN_SECONDS = 5
export default function ChannelSubscriptionScreen() {
const { t } = useTranslation()
const { channelInfo, clearBlocking } = useBlockingStore()
const [isChecking, setIsChecking] = useState(false)
const [cooldown, setCooldown] = useState(0)
const [error, setError] = useState<string | null>(null)
// Cooldown timer
useEffect(() => {
if (cooldown <= 0) return
const timer = setInterval(() => {
setCooldown((prev) => {
if (prev <= 1) {
clearInterval(timer)
return 0
}
return prev - 1
})
}, 1000)
return () => clearInterval(timer)
}, [cooldown])
const openChannel = useCallback(() => {
if (channelInfo?.channel_link) {
window.open(channelInfo.channel_link, '_blank')
}
}, [channelInfo?.channel_link])
const checkSubscription = useCallback(async () => {
if (isChecking || cooldown > 0) return
setIsChecking(true)
setError(null)
try {
// Make any authenticated request - if channel check passes, it will succeed
await apiClient.get('/cabinet/auth/me')
// If we get here, subscription is valid - reload page
clearBlocking()
window.location.reload()
} catch (err: unknown) {
// Check if it's still a channel subscription error
const error = err as { response?: { status?: number; data?: { detail?: { code?: string } } } }
if (error.response?.status === 403 && error.response?.data?.detail?.code === 'channel_subscription_required') {
setError(t('blocking.channel.notSubscribed', 'Вы ещё не подписались на канал'))
} else {
// Other error - might be network issue
setError(t('blocking.channel.checkError', 'Ошибка проверки. Попробуйте позже.'))
}
} finally {
setIsChecking(false)
setCooldown(CHECK_COOLDOWN_SECONDS)
}
}, [isChecking, cooldown, clearBlocking, t])
return (
<div className="fixed inset-0 z-[100] bg-dark-950 flex flex-col items-center justify-center p-6">
<div className="w-full max-w-md text-center">
{/* Icon */}
<div className="mb-8">
<div className="w-24 h-24 mx-auto rounded-full bg-gradient-to-br from-blue-500/20 to-cyan-500/20 flex items-center justify-center">
<svg
className="w-12 h-12 text-blue-400"
fill="currentColor"
viewBox="0 0 24 24"
>
<path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z"/>
</svg>
</div>
</div>
{/* Title */}
<h1 className="text-2xl font-bold text-white mb-4">
{t('blocking.channel.title', 'Подписка на канал')}
</h1>
{/* Message */}
<p className="text-gray-400 mb-8 text-lg">
{channelInfo?.message || t('blocking.channel.defaultMessage', 'Для продолжения работы подпишитесь на наш канал')}
</p>
{/* Error message */}
{error && (
<div className="bg-red-500/10 border border-red-500/30 rounded-xl p-4 mb-6">
<p className="text-red-400 text-sm">{error}</p>
</div>
)}
{/* Buttons */}
<div className="space-y-4">
{/* Open channel button */}
<button
onClick={openChannel}
disabled={!channelInfo?.channel_link}
className="w-full py-4 px-6 bg-gradient-to-r from-blue-500 to-cyan-500 hover:from-blue-600 hover:to-cyan-600 disabled:from-gray-600 disabled:to-gray-600 text-white font-semibold rounded-xl transition-all duration-200 flex items-center justify-center gap-3"
>
<svg
className="w-5 h-5"
fill="currentColor"
viewBox="0 0 24 24"
>
<path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z"/>
</svg>
{t('blocking.channel.openChannel', 'Открыть канал')}
</button>
{/* Check subscription button */}
<button
onClick={checkSubscription}
disabled={isChecking || cooldown > 0}
className="w-full py-4 px-6 bg-dark-800 hover:bg-dark-700 disabled:bg-dark-800 disabled:opacity-60 text-white font-semibold rounded-xl transition-all duration-200 flex items-center justify-center gap-3"
>
{isChecking ? (
<>
<svg className="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{t('blocking.channel.checking', 'Проверяем...')}
</>
) : cooldown > 0 ? (
<>
<svg className="w-5 h-5 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
{t('blocking.channel.waitSeconds', 'Подождите {{seconds}} сек.', { seconds: cooldown })}
</>
) : (
<>
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
{t('blocking.channel.checkSubscription', 'Проверить подписку')}
</>
)}
</button>
</div>
{/* Hint */}
<p className="text-gray-500 text-sm mt-6">
{t('blocking.channel.hint', 'После подписки нажмите кнопку проверки')}
</p>
</div>
</div>
)
}

View File

@@ -0,0 +1,65 @@
import { useTranslation } from 'react-i18next'
import { useBlockingStore } from '../../store/blocking'
export default function MaintenanceScreen() {
const { t } = useTranslation()
const { maintenanceInfo } = useBlockingStore()
return (
<div className="fixed inset-0 z-[100] bg-dark-950 flex flex-col items-center justify-center p-6">
<div className="w-full max-w-md text-center">
{/* Icon */}
<div className="mb-8">
<div className="w-24 h-24 mx-auto rounded-full bg-dark-800 flex items-center justify-center">
<svg
className="w-12 h-12 text-amber-500"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={1.5}
d="M11.42 15.17L17.25 21A2.652 2.652 0 0021 17.25l-5.877-5.877M11.42 15.17l2.496-3.03c.317-.384.74-.626 1.208-.766M11.42 15.17l-4.655 5.653a2.548 2.548 0 11-3.586-3.586l6.837-5.63m5.108-.233c.55-.164 1.163-.188 1.743-.14a4.5 4.5 0 004.486-6.336l-3.276 3.277a3.004 3.004 0 01-2.25-2.25l3.276-3.276a4.5 4.5 0 00-6.336 4.486c.091 1.076-.071 2.264-.904 2.95l-.102.085m-1.745 1.437L5.909 7.5H4.5L2.25 3.75l1.5-1.5L7.5 4.5v1.409l4.26 4.26m-1.745 1.437l1.745-1.437m6.615 8.206L15.75 15.75M4.867 19.125h.008v.008h-.008v-.008z"
/>
</svg>
</div>
</div>
{/* Title */}
<h1 className="text-2xl font-bold text-white mb-4">
{t('blocking.maintenance.title', 'Технические работы')}
</h1>
{/* Message */}
<p className="text-gray-400 mb-6 text-lg">
{maintenanceInfo?.message || t('blocking.maintenance.defaultMessage', 'Сервис временно недоступен. Проводятся технические работы.')}
</p>
{/* Reason */}
{maintenanceInfo?.reason && (
<div className="bg-dark-800/50 rounded-xl p-4 mb-6">
<p className="text-gray-500 text-sm mb-1">
{t('blocking.maintenance.reason', 'Причина')}:
</p>
<p className="text-gray-300">
{maintenanceInfo.reason}
</p>
</div>
)}
{/* Decorative dots */}
<div className="flex items-center justify-center gap-2 mt-8">
<div className="w-2 h-2 rounded-full bg-amber-500 animate-pulse" style={{ animationDelay: '0ms' }} />
<div className="w-2 h-2 rounded-full bg-amber-500 animate-pulse" style={{ animationDelay: '300ms' }} />
<div className="w-2 h-2 rounded-full bg-amber-500 animate-pulse" style={{ animationDelay: '600ms' }} />
</div>
<p className="text-gray-500 text-sm mt-4">
{t('blocking.maintenance.waitMessage', 'Пожалуйста, подождите...')}
</p>
</div>
</div>
)
}

View File

@@ -0,0 +1,2 @@
export { default as MaintenanceScreen } from './MaintenanceScreen'
export { default as ChannelSubscriptionScreen } from './ChannelSubscriptionScreen'

View File

@@ -33,7 +33,8 @@
"contests": "Contests",
"polls": "Polls",
"info": "Info",
"wheel": "Fortune Wheel"
"wheel": "Fortune Wheel",
"menu": "Menu"
},
"notifications": {
"ticketNotifications": "Ticket Notifications",
@@ -1314,5 +1315,24 @@
"hours": "h",
"minutes": "m"
}
},
"blocking": {
"maintenance": {
"title": "Maintenance",
"defaultMessage": "Service is temporarily unavailable. Maintenance in progress.",
"reason": "Reason",
"waitMessage": "Please wait..."
},
"channel": {
"title": "Channel Subscription",
"defaultMessage": "Please subscribe to our channel to continue",
"openChannel": "Open Channel",
"checkSubscription": "Check Subscription",
"checking": "Checking...",
"waitSeconds": "Wait {{seconds}} sec.",
"hint": "Click check button after subscribing",
"notSubscribed": "You haven't subscribed to the channel yet",
"checkError": "Check failed. Please try again later."
}
}
}

View File

@@ -794,5 +794,24 @@
"hours": "ساعت",
"minutes": "دقیقه"
}
},
"blocking": {
"maintenance": {
"title": "تعمیرات",
"defaultMessage": "سرویس موقتاً در دسترس نیست. تعمیرات در حال انجام است.",
"reason": "دلیل",
"waitMessage": "لطفاً صبر کنید..."
},
"channel": {
"title": "اشتراک کانال",
"defaultMessage": "لطفاً برای ادامه در کانال ما عضو شوید",
"openChannel": "باز کردن کانال",
"checkSubscription": "بررسی اشتراک",
"checking": "در حال بررسی...",
"waitSeconds": "{{seconds}} ثانیه صبر کنید",
"hint": "پس از عضویت دکمه بررسی را بزنید",
"notSubscribed": "شما هنوز در کانال عضو نشده‌اید",
"checkError": "بررسی ناموفق بود. لطفاً بعداً دوباره امتحان کنید."
}
}
}

View File

@@ -33,7 +33,8 @@
"contests": "Конкурсы",
"polls": "Опросы",
"info": "Информация",
"wheel": "Колесо удачи"
"wheel": "Колесо удачи",
"menu": "Меню"
},
"notifications": {
"ticketNotifications": "Уведомления о тикетах",
@@ -1472,5 +1473,24 @@
"hours": "ч",
"minutes": "м"
}
},
"blocking": {
"maintenance": {
"title": "Технические работы",
"defaultMessage": "Сервис временно недоступен. Проводятся технические работы.",
"reason": "Причина",
"waitMessage": "Пожалуйста, подождите..."
},
"channel": {
"title": "Подписка на канал",
"defaultMessage": "Для продолжения работы подпишитесь на наш канал",
"openChannel": "Открыть канал",
"checkSubscription": "Проверить подписку",
"checking": "Проверяем...",
"waitSeconds": "Подождите {{seconds}} сек.",
"hint": "После подписки нажмите кнопку проверки",
"notSubscribed": "Вы ещё не подписались на канал",
"checkError": "Ошибка проверки. Попробуйте позже."
}
}
}

View File

@@ -31,7 +31,8 @@
"contests": "活动",
"polls": "问卷",
"info": "信息",
"wheel": "幸运转盘"
"wheel": "幸运转盘",
"menu": "菜单"
},
"notifications": {
"ticketNotifications": "工单通知",
@@ -794,5 +795,24 @@
"hours": "时",
"minutes": "分"
}
},
"blocking": {
"maintenance": {
"title": "系统维护",
"defaultMessage": "服务暂时不可用。正在进行系统维护。",
"reason": "原因",
"waitMessage": "请稍候..."
},
"channel": {
"title": "频道订阅",
"defaultMessage": "请订阅我们的频道以继续",
"openChannel": "打开频道",
"checkSubscription": "检查订阅",
"checking": "检查中...",
"waitSeconds": "请等待 {{seconds}} 秒",
"hint": "订阅后点击检查按钮",
"notSubscribed": "您还没有订阅该频道",
"checkError": "检查失败。请稍后重试。"
}
}
}

47
src/store/blocking.ts Normal file
View File

@@ -0,0 +1,47 @@
import { create } from 'zustand'
export type BlockingType = 'maintenance' | 'channel_subscription' | null
interface MaintenanceInfo {
message: string
reason?: string
}
interface ChannelSubscriptionInfo {
message: string
channel_link?: string
}
interface BlockingState {
blockingType: BlockingType
maintenanceInfo: MaintenanceInfo | null
channelInfo: ChannelSubscriptionInfo | null
setMaintenance: (info: MaintenanceInfo) => void
setChannelSubscription: (info: ChannelSubscriptionInfo) => void
clearBlocking: () => void
}
export const useBlockingStore = create<BlockingState>((set) => ({
blockingType: null,
maintenanceInfo: null,
channelInfo: null,
setMaintenance: (info) => set({
blockingType: 'maintenance',
maintenanceInfo: info,
channelInfo: null,
}),
setChannelSubscription: (info) => set({
blockingType: 'channel_subscription',
channelInfo: info,
maintenanceInfo: null,
}),
clearBlocking: () => set({
blockingType: null,
maintenanceInfo: null,
channelInfo: null,
}),
}))