BIG_UPDATE deleted vps, added s3 infrastructure.
This commit is contained in:
@@ -4,7 +4,7 @@
|
||||
<meta charset="UTF-8" />
|
||||
|
||||
<!-- Favicons -->
|
||||
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
@@ -46,8 +46,30 @@
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link rel="dns-prefetch" href="https://cdn.jsdelivr.net" />
|
||||
|
||||
<!-- Fonts -->
|
||||
<link href="https://fonts.googleapis.com/css2?family=Share+Tech+Mono&display=swap" rel="stylesheet" />
|
||||
<!-- Критические стили для первой отрисовки -->
|
||||
<style>
|
||||
/* Минимальные критические стили для предотвращения FOUC */
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
#root {
|
||||
min-height: 100vh;
|
||||
}
|
||||
</style>
|
||||
|
||||
<!-- Fonts - асинхронная загрузка для производительности -->
|
||||
<link
|
||||
rel="preload"
|
||||
as="style"
|
||||
href="https://fonts.googleapis.com/css2?family=Share+Tech+Mono&display=swap"
|
||||
onload="this.onload=null;this.rel='stylesheet'"
|
||||
/>
|
||||
<noscript>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Share+Tech+Mono&display=swap" rel="stylesheet" />
|
||||
</noscript>
|
||||
|
||||
<!-- Structured Data (JSON-LD) -->
|
||||
<script type="application/ld+json">
|
||||
@@ -59,7 +81,8 @@
|
||||
"logo": "https://ospab.host/logo.jpg",
|
||||
"description": "Облачные решения в Великом Новгороде.",
|
||||
"sameAs": [
|
||||
"https://github.com/Ospab"
|
||||
"https://github.com/Ospab",
|
||||
"https://github.com/ospab/ospabhost8.1"
|
||||
],
|
||||
"address": {
|
||||
"@type": "PostalAddress",
|
||||
@@ -96,5 +119,10 @@
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
|
||||
<!-- Инлайн скрипт для асинхронной загрузки шрифтов -->
|
||||
<script>
|
||||
!function(e){"use strict";var t=function(t,n,o){var i,r=e.document,a=r.createElement("link");if(n)i=n;else{var d=(r.body||r.getElementsByTagName("head")[0]).childNodes;i=d[d.length-1]}var l=r.styleSheets;if(o)for(var s in o)o.hasOwnProperty(s)&&a.setAttribute(s,o[s]);a.rel="stylesheet",a.href=t,a.media="only x",function e(t){if(r.body)return t();setTimeout(function(){e(t)})}(function(){i.parentNode.insertBefore(a,n?i:i.nextSibling)});var f=function(e){for(var t=a.href,n=l.length;n--;)if(l[n].href===t)return e();setTimeout(function(){f(e)})};return a.addEventListener&&a.addEventListener("load",function(){this.media="all"}),a.onloadcssdefined=f,f(function(){a.media!=="all"&&(a.media="all")}),a};"undefined"!=typeof exports?exports.loadCSS=t:e.loadCSS=t}("undefined"!=typeof global?global:this);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
933
ospabhost/frontend/package-lock.json
generated
933
ospabhost/frontend/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -12,17 +12,21 @@
|
||||
"dependencies": {
|
||||
"@marsidev/react-turnstile": "^1.3.1",
|
||||
"axios": "^1.12.2",
|
||||
"react": "^19.1.1",
|
||||
"react-dom": "^19.1.1",
|
||||
"qrcode.react": "^4.2.0",
|
||||
"quill": "^2.0.3",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-helmet-async": "^2.0.5",
|
||||
"react-icons": "^5.5.0",
|
||||
"react-qr-code": "^2.0.18",
|
||||
"react-quill": "^2.0.0",
|
||||
"recharts": "^3.3.0",
|
||||
"xterm": "^5.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.33.0",
|
||||
"@types/react": "^19.1.10",
|
||||
"@types/react-dom": "^19.1.7",
|
||||
"@types/react": "^18.3.12",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@vitejs/plugin-react": "^5.0.0",
|
||||
"autoprefixer": "^10.4.14",
|
||||
"eslint": "^9.33.0",
|
||||
@@ -32,6 +36,7 @@
|
||||
"postcss": "^8.4.21",
|
||||
"react-router-dom": "^7.9.1",
|
||||
"tailwindcss": "^3.3.3",
|
||||
"terser": "^5.44.1",
|
||||
"typescript": "~5.8.3",
|
||||
"typescript-eslint": "^8.39.1",
|
||||
"vite": "^7.1.2"
|
||||
|
||||
43
ospabhost/frontend/public/favicon.svg
Normal file
43
ospabhost/frontend/public/favicon.svg
Normal file
@@ -0,0 +1,43 @@
|
||||
<?xml version="1.0" standalone="no"?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
|
||||
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
|
||||
<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
|
||||
width="192.000000pt" height="192.000000pt" viewBox="0 0 192.000000 192.000000"
|
||||
preserveAspectRatio="xMidYMid meet">
|
||||
<metadata>
|
||||
Created by potrace 1.16, written by Peter Selinger 2001-2019
|
||||
</metadata>
|
||||
<g transform="translate(0.000000,192.000000) scale(0.100000,-0.100000)"
|
||||
fill="#000000" stroke="none">
|
||||
<path d="M925 1717 c-10 -7 -25 -18 -33 -24 -7 -7 -17 -13 -22 -13 -5 0 -15
|
||||
-6 -22 -12 -8 -7 -23 -18 -33 -25 -51 -31 -157 -99 -225 -144 -41 -27 -84 -53
|
||||
-96 -58 -50 -22 -114 -123 -114 -182 0 -17 -27 -29 -68 -29 -68 0 -216 -110
|
||||
-258 -192 -24 -46 -54 -157 -54 -198 0 -41 30 -152 54 -199 25 -48 117 -134
|
||||
172 -162 43 -21 66 -24 182 -27 133 -4 158 3 110 29 -13 7 -56 34 -97 61 -41
|
||||
26 -89 51 -108 54 -42 8 -117 74 -145 128 -30 57 -31 174 -1 231 55 104 145
|
||||
155 275 155 l68 0 0 73 c0 91 16 116 107 174 94 59 110 65 136 51 23 -12 292
|
||||
-186 339 -219 15 -10 31 -19 36 -19 5 0 16 -8 25 -18 14 -15 17 -42 17 -153
|
||||
l0 -135 -57 -34 c-32 -19 -60 -37 -63 -40 -3 -4 -12 -10 -20 -13 -8 -4 -30
|
||||
-16 -47 -27 l-33 -20 -82 55 c-144 93 -128 66 -128 225 l0 139 33 17 c17 9 34
|
||||
20 37 23 3 3 22 15 43 26 47 24 52 32 37 51 -12 13 -24 21 -87 55 -22 12 -46
|
||||
1 -142 -64 -14 -9 -34 -20 -43 -23 -16 -6 -18 -26 -18 -224 l0 -217 68 -43
|
||||
c37 -24 93 -61 125 -82 32 -21 60 -38 62 -38 3 0 50 -30 162 -104 18 -11 33
|
||||
-24 33 -27 0 -3 -22 -19 -48 -36 l-48 -30 -74 48 c-97 62 -200 127 -225 142
|
||||
-11 7 -36 24 -56 40 -20 15 -41 27 -46 27 -6 0 -17 8 -26 18 -14 16 -17 43
|
||||
-17 165 l0 147 -65 0 -65 0 0 -195 c0 -110 4 -195 9 -195 5 0 42 -22 83 -49
|
||||
131 -87 199 -131 204 -131 3 0 17 -9 32 -19 15 -10 76 -51 135 -90 l109 -71
|
||||
59 37 c33 21 67 43 77 48 9 6 31 19 47 30 17 10 95 61 175 113 80 52 157 102
|
||||
172 113 15 10 32 19 38 19 6 0 10 67 10 195 l0 195 -70 0 -69 0 -3 -156 -3
|
||||
-157 -75 -48 c-133 -85 -118 -83 -198 -33 l-32 21 97 62 c53 35 102 65 110 68
|
||||
10 4 13 51 13 223 l0 218 -57 38 c-32 20 -77 50 -101 66 -24 15 -47 28 -53 28
|
||||
-5 0 -9 4 -9 9 0 5 -13 14 -30 21 -16 7 -30 16 -30 20 0 4 -8 10 -17 14 -10 3
|
||||
-48 25 -85 49 l-66 43 46 29 c55 35 71 35 120 -2 20 -15 46 -33 57 -40 184
|
||||
-110 289 -186 305 -218 7 -16 14 -59 15 -95 l0 -65 85 -5 c142 -10 214 -55
|
||||
265 -169 27 -59 29 -108 9 -173 -25 -82 -86 -145 -171 -176 -34 -13 -69 -29
|
||||
-77 -37 -8 -8 -17 -15 -21 -15 -6 0 -66 -40 -75 -51 -3 -3 -13 -8 -22 -12 -10
|
||||
-3 -18 -11 -18 -17 0 -6 44 -10 120 -10 113 0 124 2 184 30 78 37 155 116 192
|
||||
197 24 50 28 72 28 158 1 116 -15 170 -75 252 -56 76 -167 143 -237 143 -38 0
|
||||
-45 7 -67 74 -23 70 -86 138 -155 169 -8 4 -69 42 -135 86 -156 104 -264 171
|
||||
-273 170 -4 0 -16 -6 -27 -12z"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.7 KiB |
79
ospabhost/frontend/public/service-worker.js
Normal file
79
ospabhost/frontend/public/service-worker.js
Normal file
@@ -0,0 +1,79 @@
|
||||
self.addEventListener('push', (event) => {
|
||||
console.log('[Service Worker] Push-уведомление получено');
|
||||
|
||||
if (!event.data) {
|
||||
console.warn('[Service Worker] Push без данных');
|
||||
return;
|
||||
}
|
||||
|
||||
let data;
|
||||
|
||||
try {
|
||||
data = event.data.json();
|
||||
} catch (error) {
|
||||
console.error('[Service Worker] Ошибка парсинга Push данных:', error);
|
||||
return;
|
||||
}
|
||||
|
||||
const title = data.title || 'Новое уведомление';
|
||||
const options = {
|
||||
body: data.body,
|
||||
icon: data.icon || '/favicon.svg',
|
||||
badge: '/favicon.svg',
|
||||
tag: `notification-${data.data?.notificationId || Date.now()}`,
|
||||
data: data.data,
|
||||
requireInteraction: false,
|
||||
vibrate: [200, 100, 200]
|
||||
};
|
||||
|
||||
event.waitUntil(
|
||||
self.registration.showNotification(title, options)
|
||||
);
|
||||
});
|
||||
|
||||
// Обработка клика по уведомлению
|
||||
self.addEventListener('notificationclick', (event) => {
|
||||
console.log('[Service Worker] Клик по уведомлению');
|
||||
|
||||
event.notification.close();
|
||||
|
||||
const actionUrl = event.notification.data?.actionUrl;
|
||||
const targetUrl = actionUrl
|
||||
? `https://ospab.host${actionUrl}`
|
||||
: 'https://ospab.host/dashboard';
|
||||
|
||||
event.waitUntil(
|
||||
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
|
||||
// Если есть открытая вкладка с сайтом, фокусируем её и переходим
|
||||
for (const client of clientList) {
|
||||
if (client.url.startsWith('https://ospab.host') && 'focus' in client) {
|
||||
client.focus();
|
||||
client.navigate(targetUrl);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Иначе открываем новую вкладку
|
||||
if (self.clients.openWindow) {
|
||||
return self.clients.openWindow(targetUrl);
|
||||
}
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
// Обработка закрытия уведомления
|
||||
self.addEventListener('notificationclose', (event) => {
|
||||
console.log('[Service Worker] Уведомление закрыто:', event.notification.tag);
|
||||
});
|
||||
|
||||
// Активация Service Worker
|
||||
self.addEventListener('activate', (event) => {
|
||||
console.log('[Service Worker] Активирован');
|
||||
event.waitUntil(self.clients.claim());
|
||||
});
|
||||
|
||||
// Установка Service Worker
|
||||
self.addEventListener('install', (event) => {
|
||||
console.log('[Service Worker] Установлен');
|
||||
event.waitUntil(self.skipWaiting());
|
||||
});
|
||||
@@ -6,14 +6,23 @@ import Homepage from './pages/index';
|
||||
import Dashboard from './pages/dashboard/mainpage';
|
||||
import Loginpage from './pages/login';
|
||||
import Registerpage from './pages/register';
|
||||
import TariffsPage from './pages/tariffs';
|
||||
import QRLoginPage from './pages/qr-login';
|
||||
import Aboutpage from './pages/about';
|
||||
import S3PlansPage from './pages/s3plans';
|
||||
import Privacy from './pages/privacy';
|
||||
import Terms from './pages/terms';
|
||||
import Blog from './pages/blog';
|
||||
import BlogPost from './pages/blogpost';
|
||||
import NotFound from './pages/404';
|
||||
import Unauthorized from './pages/401';
|
||||
import Forbidden from './pages/403';
|
||||
import ServerError from './pages/500';
|
||||
import BadGateway from './pages/502';
|
||||
import ServiceUnavailable from './pages/503';
|
||||
import GatewayTimeout from './pages/504';
|
||||
import Privateroute from './components/privateroute';
|
||||
import { AuthProvider } from './context/authcontext';
|
||||
import { WebSocketProvider } from './context/WebSocketContext';
|
||||
import ErrorBoundary from './components/ErrorBoundary';
|
||||
import { ToastProvider } from './components/Toast';
|
||||
|
||||
@@ -30,66 +39,66 @@ const SEO_CONFIG: Record<string, {
|
||||
};
|
||||
}> = {
|
||||
'/': {
|
||||
title: 'Облачный хостинг и виртуальные машины',
|
||||
description: 'Ospab.host - надёжный облачный хостинг и виртуальные машины (VPS/VDS) в Великом Новгороде. Запускайте и масштабируйте проекты с высокой производительностью, 24/7 поддержкой и доступными ценами.',
|
||||
keywords: 'хостинг, облачный хостинг, VPS, VDS, виртуальные машины, дата-центр, Великий Новгород',
|
||||
title: 'Облачное S3 хранилище',
|
||||
description: 'ospab.host - надёжное облачное S3-совместимое хранилище в Великом Новгороде. Хранение файлов, резервные копии, медиа-контент. Тикеты поддержки 24/7, QR-аутентификация.',
|
||||
keywords: 'хостинг, облачное хранилище, S3, хранение файлов, Великий Новгород, object storage',
|
||||
og: {
|
||||
title: 'Ospab.host - Облачный хостинг',
|
||||
description: 'Запускайте и масштабируйте проекты с надёжной инфраструктурой',
|
||||
title: 'ospab.host - Облачное S3 хранилище',
|
||||
description: 'S3-совместимое хранилище с поддержкой 24/7',
|
||||
image: 'https://ospab.host/og-image.jpg',
|
||||
url: 'https://ospab.host/',
|
||||
},
|
||||
},
|
||||
'/about': {
|
||||
title: 'О компании',
|
||||
description: 'Узнайте о Ospab.host - первом облачном хостинге в Великом Новгороде. История создания, миссия и видение компании. Основатель Георгий Сыралёв.',
|
||||
keywords: 'об ospab, история хостинга, облачные решения, Великий Новгород',
|
||||
title: 'О компании - Ospab Host',
|
||||
description: 'Узнайте о ospab.host - современной платформе облачного хранилища в Великом Новгороде. S3-совместимое хранилище с тикетами поддержки. Основатель Георгий Сыралёв.',
|
||||
keywords: 'об ospab, история хостинга, облачные решения, S3 хранилище, Великий Новгород',
|
||||
og: {
|
||||
title: 'О компании Ospab.host',
|
||||
description: 'История создания первого хостинга в Великом Новгороде',
|
||||
title: 'О компании ospab.host',
|
||||
description: 'Современная платформа облачного хранилища',
|
||||
image: 'https://ospab.host/og-image.jpg',
|
||||
url: 'https://ospab.host/about',
|
||||
},
|
||||
},
|
||||
'/tariffs': {
|
||||
title: 'Тарифы и цены',
|
||||
description: 'Выберите подходящий тариф для вашего проекта. Облачный хостинг, VPS, VDS с гибкими тарифами и доступными ценами. Начните с облачного хостинга от Ospab.host.',
|
||||
keywords: 'цены на хостинг, тарифы, VPS цена, VDS цена, облачные решения, стоимость хостинга',
|
||||
og: {
|
||||
title: 'Тарифы Ospab.host',
|
||||
description: 'Выберите тариф для размещения сайта или сервера',
|
||||
image: 'https://ospab.host/og-image.jpg',
|
||||
url: 'https://ospab.host/tariffs',
|
||||
},
|
||||
},
|
||||
'/login': {
|
||||
title: 'Вход в аккаунт',
|
||||
description: 'Войдите в ваш личный кабинет Ospab.host. Управляйте серверами, тарифами и билетами поддержки. Быстрый вход в аккаунт хостинга.',
|
||||
keywords: 'вход в аккаунт, личный кабинет, ospab, вход в хостинг',
|
||||
title: 'Вход в аккаунт - Ospab Host',
|
||||
description: 'Войдите в ваш личный кабинет ospab.host. Управляйте хранилищем, тикеты поддержки, QR-аутентификация для быстрого входа.',
|
||||
keywords: 'вход в аккаунт, личный кабинет, ospab логин, вход в хостинг, QR вход, панель управления',
|
||||
og: {
|
||||
title: 'Вход в Ospab.host',
|
||||
description: 'Логин в личный кабинет',
|
||||
title: 'Вход в ospab.host',
|
||||
description: 'Доступ к панели управления',
|
||||
image: 'https://ospab.host/og-image.jpg',
|
||||
url: 'https://ospab.host/login',
|
||||
},
|
||||
},
|
||||
'/register': {
|
||||
title: 'Регистрация',
|
||||
description: 'Зарегистрируйтесь в Ospab.host и начните пользоваться облачным хостингом. Создайте аккаунт бесплатно за 2 минуты и получите бонус.',
|
||||
keywords: 'регистрация, создать аккаунт, ospab регистрация, регистрация хостинга',
|
||||
title: 'Регистрация - Создать аккаунт',
|
||||
description: 'Зарегистрируйтесь в ospab.host и начните пользоваться облачным хранилищем. Создайте аккаунт бесплатно за 2 минуты, получите доступ к S3 API и тикетам поддержки.',
|
||||
keywords: 'регистрация, создать аккаунт, ospab регистрация, регистрация хостинга, новый аккаунт',
|
||||
og: {
|
||||
title: 'Регистрация в Ospab.host',
|
||||
description: 'Создайте аккаунт и начните пользоваться хостингом',
|
||||
title: 'Регистрация в ospab.host',
|
||||
description: 'Создайте аккаунт и начните использовать S3 хранилище',
|
||||
image: 'https://ospab.host/og-image.jpg',
|
||||
url: 'https://ospab.host/register',
|
||||
},
|
||||
},
|
||||
'/blog': {
|
||||
title: 'Блог о хостинге и S3',
|
||||
description: 'Статьи о хостинге, S3 хранилище, облачных технологиях, DevOps практиках, безопасности. Полезные гайды от команды ospab.host.',
|
||||
keywords: 'блог хостинг, S3 гайды, облачное хранилище, DevOps, object storage',
|
||||
og: {
|
||||
title: 'Блог ospab.host',
|
||||
description: 'Статьи о хостинге и DevOps',
|
||||
image: 'https://ospab.host/og-image.jpg',
|
||||
url: 'https://ospab.host/blog',
|
||||
},
|
||||
},
|
||||
'/terms': {
|
||||
title: 'Условия использования',
|
||||
description: 'Условия использования сервиса Ospab.host. Ознакомьтесь с полными правилами и требованиями для пользователей хостинга.',
|
||||
keywords: 'условия использования, пользовательское соглашение, правила использования',
|
||||
description: 'Условия использования сервиса ospab.host. Ознакомьтесь с полными правилами для пользователей облачного хранилища.',
|
||||
keywords: 'условия использования, пользовательское соглашение, правила использования, юридические условия',
|
||||
og: {
|
||||
title: 'Условия использования Ospab.host',
|
||||
title: 'Условия использования ospab.host',
|
||||
description: 'Полные условия использования сервиса',
|
||||
image: 'https://ospab.host/og-image.jpg',
|
||||
url: 'https://ospab.host/terms',
|
||||
@@ -97,11 +106,11 @@ const SEO_CONFIG: Record<string, {
|
||||
},
|
||||
'/privacy': {
|
||||
title: 'Политика конфиденциальности',
|
||||
description: 'Политика конфиденциальности Ospab.host. Узнайте как мы защищаем ваши персональные данные и информацию о приватности.',
|
||||
keywords: 'политика конфиденциальности, приватность, защита данных, GDPR',
|
||||
description: 'Политика конфиденциальности ospab.host. Узнайте как мы защищаем ваши персональные данные, информацию об аккаунте и платежах. Соответствие GDPR.',
|
||||
keywords: 'политика конфиденциальности, приватность, защита данных, GDPR, безопасность данных',
|
||||
og: {
|
||||
title: 'Политика конфиденциальности Ospab.host',
|
||||
description: 'Узнайте о защите ваших данных',
|
||||
title: 'Политика конфиденциальности ospab.host',
|
||||
description: 'Защита ваших данных и приватности',
|
||||
image: 'https://ospab.host/og-image.jpg',
|
||||
url: 'https://ospab.host/privacy',
|
||||
},
|
||||
@@ -117,13 +126,13 @@ function SEOUpdater() {
|
||||
|
||||
// Получаем SEO данные для текущего маршрута, иначе используем дефолтные
|
||||
const seoData = SEO_CONFIG[pathname] || {
|
||||
title: 'Ospab.host - Облачный хостинг',
|
||||
description: 'Ospab.host - надёжный облачный хостинг и виртуальные машины в Великом Новгороде.',
|
||||
title: 'ospab.host - облачный хостинг',
|
||||
description: 'ospab.host - надёжный облачный хостинг и виртуальные машины в Великом Новгороде.',
|
||||
keywords: 'хостинг, облачный хостинг, VPS, VDS',
|
||||
};
|
||||
|
||||
// Устанавливаем title
|
||||
document.title = `${seoData.title} - Ospab.host`;
|
||||
document.title = `${seoData.title} - ospab.host`;
|
||||
|
||||
// Функция для установки или обновления meta тега
|
||||
const setMeta = (name: string, content: string, isProperty = false) => {
|
||||
@@ -186,33 +195,43 @@ function App() {
|
||||
<Router>
|
||||
<SEOUpdater />
|
||||
<AuthProvider>
|
||||
<ToastProvider>
|
||||
<ErrorBoundary>
|
||||
<Routes>
|
||||
{/* Обычные страницы с footer */}
|
||||
<Route path="/" element={<Pagetempl><Homepage /></Pagetempl>} />
|
||||
<Route path="/tariffs" element={<Pagetempl><TariffsPage /></Pagetempl>} />
|
||||
<Route path="/about" element={<Pagetempl><Aboutpage /></Pagetempl>} />
|
||||
<Route path="/privacy" element={<Privacy />} />
|
||||
<Route path="/terms" element={<Terms />} />
|
||||
<Route path="/login" element={<Pagetempl><Loginpage /></Pagetempl>} />
|
||||
<Route path="/register" element={<Pagetempl><Registerpage /></Pagetempl>} />
|
||||
|
||||
{/* Дашборд без footer */}
|
||||
<Route path="/dashboard/*" element={
|
||||
<DashboardTempl>
|
||||
<Privateroute>
|
||||
<Dashboard />
|
||||
</Privateroute>
|
||||
</DashboardTempl>
|
||||
} />
|
||||
<WebSocketProvider>
|
||||
<ToastProvider>
|
||||
<ErrorBoundary>
|
||||
<Routes>
|
||||
{/* Обычные страницы с footer */}
|
||||
<Route path="/" element={<Pagetempl><Homepage /></Pagetempl>} />
|
||||
<Route path="/about" element={<Pagetempl><Aboutpage /></Pagetempl>} />
|
||||
<Route path="/tariffs" element={<Pagetempl><S3PlansPage /></Pagetempl>} />
|
||||
<Route path="/blog" element={<Pagetempl><Blog /></Pagetempl>} />
|
||||
<Route path="/blog/:url" element={<Pagetempl><BlogPost /></Pagetempl>} />
|
||||
<Route path="/privacy" element={<Privacy />} />
|
||||
<Route path="/terms" element={<Terms />} />
|
||||
<Route path="/login" element={<Pagetempl><Loginpage /></Pagetempl>} />
|
||||
<Route path="/register" element={<Pagetempl><Registerpage /></Pagetempl>} />
|
||||
<Route path="/qr-login" element={<QRLoginPage />} />
|
||||
|
||||
{/* Дашборд без footer */}
|
||||
<Route path="/dashboard/*" element={
|
||||
<DashboardTempl>
|
||||
<Privateroute>
|
||||
<Dashboard />
|
||||
</Privateroute>
|
||||
</DashboardTempl>
|
||||
} />
|
||||
|
||||
{/* Страницы ошибок */}
|
||||
<Route path="/500" element={<ServerError />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</ErrorBoundary>
|
||||
</ToastProvider>
|
||||
{/* Страницы ошибок */}
|
||||
<Route path="/401" element={<Unauthorized />} />
|
||||
<Route path="/403" element={<Forbidden />} />
|
||||
<Route path="/500" element={<ServerError />} />
|
||||
<Route path="/502" element={<BadGateway />} />
|
||||
<Route path="/503" element={<ServiceUnavailable />} />
|
||||
<Route path="/504" element={<GatewayTimeout />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</ErrorBoundary>
|
||||
</ToastProvider>
|
||||
</WebSocketProvider>
|
||||
</AuthProvider>
|
||||
</Router>
|
||||
);
|
||||
|
||||
109
ospabhost/frontend/src/components/ErrorPage.tsx
Normal file
109
ospabhost/frontend/src/components/ErrorPage.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
interface ErrorPageProps {
|
||||
code: string;
|
||||
title: string;
|
||||
description: string;
|
||||
icon: ReactNode;
|
||||
color: 'red' | 'orange' | 'purple' | 'blue' | 'gray';
|
||||
showLoginButton?: boolean;
|
||||
showBackButton?: boolean;
|
||||
showHomeButton?: boolean;
|
||||
}
|
||||
|
||||
const colorClasses = {
|
||||
red: 'text-red-600 border-red-200 bg-red-50',
|
||||
orange: 'text-orange-600 border-orange-200 bg-orange-50',
|
||||
purple: 'text-purple-600 border-purple-200 bg-purple-50',
|
||||
blue: 'text-blue-600 border-blue-200 bg-blue-50',
|
||||
gray: 'text-gray-600 border-gray-200 bg-gray-50',
|
||||
};
|
||||
|
||||
const buttonColorClasses = {
|
||||
red: 'bg-red-600 hover:bg-red-700 focus:ring-red-500',
|
||||
orange: 'bg-orange-600 hover:bg-orange-700 focus:ring-orange-500',
|
||||
purple: 'bg-purple-600 hover:bg-purple-700 focus:ring-purple-500',
|
||||
blue: 'bg-blue-600 hover:bg-blue-700 focus:ring-blue-500',
|
||||
gray: 'bg-gray-600 hover:bg-gray-700 focus:ring-gray-500',
|
||||
};
|
||||
|
||||
export default function ErrorPage({
|
||||
code,
|
||||
title,
|
||||
description,
|
||||
icon,
|
||||
color,
|
||||
showLoginButton = false,
|
||||
showBackButton = true,
|
||||
showHomeButton = true,
|
||||
}: ErrorPageProps) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-white px-4">
|
||||
<div className="max-w-md w-full text-center">
|
||||
{/* Код ошибки */}
|
||||
<div className="mb-8">
|
||||
<h1 className="text-8xl font-bold text-gray-200 mb-4">{code}</h1>
|
||||
<div className={`inline-flex items-center justify-center w-16 h-16 rounded-full border-2 ${colorClasses[color]}`}>
|
||||
{icon}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Заголовок */}
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-3">
|
||||
{title}
|
||||
</h2>
|
||||
|
||||
{/* Описание */}
|
||||
<p className="text-gray-600 mb-8">
|
||||
{description}
|
||||
</p>
|
||||
|
||||
{/* Кнопки */}
|
||||
<div className="flex flex-col gap-3">
|
||||
{showHomeButton && (
|
||||
<Link
|
||||
to="/"
|
||||
className={`w-full inline-flex items-center justify-center px-6 py-3 border border-transparent text-base font-medium rounded-lg text-white ${buttonColorClasses[color]} transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2`}
|
||||
>
|
||||
На главную
|
||||
</Link>
|
||||
)}
|
||||
|
||||
{showLoginButton && (
|
||||
<Link
|
||||
to="/login"
|
||||
className={`w-full inline-flex items-center justify-center px-6 py-3 border border-transparent text-base font-medium rounded-lg text-white ${buttonColorClasses[color]} transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2`}
|
||||
>
|
||||
Войти
|
||||
</Link>
|
||||
)}
|
||||
|
||||
{showBackButton && (
|
||||
<button
|
||||
onClick={() => window.history.back()}
|
||||
className="w-full inline-flex items-center justify-center px-6 py-3 border-2 border-gray-300 text-base font-medium rounded-lg text-gray-700 bg-white hover:bg-gray-50 transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500"
|
||||
>
|
||||
Назад
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Контактная информация (опционально) */}
|
||||
{(code === '500' || code === '503') && (
|
||||
<div className="mt-8 pt-6 border-t border-gray-200">
|
||||
<p className="text-sm text-gray-500">
|
||||
Если проблема сохраняется, свяжитесь с нами:{' '}
|
||||
<a
|
||||
href="mailto:support@ospab.host"
|
||||
className={`${color === 'red' ? 'text-red-600' : color === 'orange' ? 'text-orange-600' : 'text-gray-600'} hover:underline font-medium`}
|
||||
>
|
||||
support@ospab.host
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -48,21 +48,21 @@ export const Modal: React.FC<ModalProps> = ({
|
||||
switch (type) {
|
||||
case 'warning':
|
||||
return {
|
||||
icon: '⚠️',
|
||||
icon: '!',
|
||||
iconBg: 'bg-yellow-100',
|
||||
iconColor: 'text-yellow-600',
|
||||
buttonBg: 'bg-yellow-600 hover:bg-yellow-700'
|
||||
};
|
||||
case 'danger':
|
||||
return {
|
||||
icon: '🗑️',
|
||||
icon: '×',
|
||||
iconBg: 'bg-red-100',
|
||||
iconColor: 'text-red-600',
|
||||
buttonBg: 'bg-red-600 hover:bg-red-700'
|
||||
};
|
||||
default:
|
||||
return {
|
||||
icon: 'ℹ️',
|
||||
icon: 'i',
|
||||
iconBg: 'bg-blue-100',
|
||||
iconColor: 'text-blue-600',
|
||||
buttonBg: 'bg-blue-600 hover:bg-blue-700'
|
||||
|
||||
254
ospabhost/frontend/src/components/NotificationBell.tsx
Normal file
254
ospabhost/frontend/src/components/NotificationBell.tsx
Normal file
@@ -0,0 +1,254 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { getUnreadCount, getNotifications, markAsRead, type Notification } from '../services/notificationService';
|
||||
import { useWebSocket } from '../hooks/useWebSocket';
|
||||
import { wsLogger } from '../utils/logger';
|
||||
|
||||
const NotificationBell = () => {
|
||||
const [unreadCount, setUnreadCount] = useState(0);
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [notifications, setNotifications] = useState<Notification[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { subscribe, unsubscribe, isConnected } = useWebSocket();
|
||||
|
||||
// WebSocket обработчик событий
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const handleWebSocketEvent = useCallback((event: any) => {
|
||||
if (event.type === 'notification:new') {
|
||||
// Добавляем новое уведомление в начало списка
|
||||
setNotifications((prev) => [event.notification, ...prev.slice(0, 4)]);
|
||||
setUnreadCount((prev) => prev + 1);
|
||||
wsLogger.log('Получено новое уведомление:', event.notification);
|
||||
} else if (event.type === 'notification:read') {
|
||||
// Помечаем уведомление как прочитанное
|
||||
setNotifications((prev) =>
|
||||
prev.map((n) => (n.id === event.notificationId ? { ...n, isRead: true } : n))
|
||||
);
|
||||
setUnreadCount((prev) => Math.max(0, prev - 1));
|
||||
wsLogger.log('Уведомление помечено прочитанным:', event.notificationId);
|
||||
} else if (event.type === 'notification:delete') {
|
||||
// Удаляем уведомление из списка
|
||||
// Если оно было непрочитанным - уменьшаем счётчик
|
||||
setNotifications((prev) => {
|
||||
const notification = prev.find((n) => n.id === event.notificationId);
|
||||
if (notification && !notification.isRead) {
|
||||
setUnreadCount((count) => Math.max(0, count - 1));
|
||||
}
|
||||
return prev.filter((n) => n.id !== event.notificationId);
|
||||
});
|
||||
wsLogger.log('Уведомление удалено:', event.notificationId);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Подписка на WebSocket при монтировании
|
||||
useEffect(() => {
|
||||
if (isConnected) {
|
||||
subscribe('notifications', handleWebSocketEvent);
|
||||
wsLogger.log('Подписались на уведомления');
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (isConnected) {
|
||||
unsubscribe('notifications', handleWebSocketEvent);
|
||||
wsLogger.log('Отписались от уведомлений');
|
||||
}
|
||||
};
|
||||
}, [isConnected, subscribe, unsubscribe, handleWebSocketEvent]);
|
||||
|
||||
// Загрузка количества непрочитанных при монтировании
|
||||
useEffect(() => {
|
||||
loadUnreadCount();
|
||||
}, []);
|
||||
|
||||
// Загрузка последних уведомлений при открытии дропдауна
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
loadNotifications();
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
const loadUnreadCount = async () => {
|
||||
try {
|
||||
const count = await getUnreadCount();
|
||||
setUnreadCount(count);
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки количества уведомлений:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const loadNotifications = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await getNotifications({ page: 1, limit: 5 });
|
||||
// Проверяем, что response имеет правильную структуру
|
||||
if (response && Array.isArray(response.notifications)) {
|
||||
setNotifications(response.notifications);
|
||||
} else {
|
||||
console.error('Неверный формат ответа от сервера:', response);
|
||||
setNotifications([]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки уведомлений:', error);
|
||||
setNotifications([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleNotificationClick = async (notification: Notification) => {
|
||||
if (!notification.isRead) {
|
||||
try {
|
||||
await markAsRead(notification.id);
|
||||
setUnreadCount((prev) => Math.max(0, prev - 1));
|
||||
setNotifications((prev) =>
|
||||
prev.map((n) => (n.id === notification.id ? { ...n, isRead: true } : n))
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Ошибка пометки уведомления прочитанным:', error);
|
||||
}
|
||||
}
|
||||
setIsOpen(false);
|
||||
};
|
||||
|
||||
const formatDate = (dateString: string) => {
|
||||
const date = new Date(dateString);
|
||||
const now = new Date();
|
||||
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
|
||||
|
||||
if (diffInSeconds < 60) return 'только что';
|
||||
if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)} мин назад`;
|
||||
if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)} ч назад`;
|
||||
if (diffInSeconds < 604800) return `${Math.floor(diffInSeconds / 86400)} д назад`;
|
||||
|
||||
return date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
{/* Иконка колокольчика */}
|
||||
<button
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
className="relative p-2 text-gray-600 hover:text-ospab-primary transition-colors"
|
||||
aria-label="Уведомления"
|
||||
>
|
||||
<svg
|
||||
className="w-6 h-6"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"
|
||||
/>
|
||||
</svg>
|
||||
|
||||
{/* Бейдж с количеством */}
|
||||
{unreadCount > 0 && (
|
||||
<span className="absolute top-0 right-0 inline-flex items-center justify-center px-2 py-1 text-xs font-bold leading-none text-white transform translate-x-1/2 -translate-y-1/2 bg-red-500 rounded-full">
|
||||
{unreadCount > 99 ? '99+' : unreadCount}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Дропдаун */}
|
||||
{isOpen && (
|
||||
<>
|
||||
{/* Оверлей для закрытия при клике вне */}
|
||||
<div
|
||||
className="fixed inset-0 z-10"
|
||||
onClick={() => setIsOpen(false)}
|
||||
/>
|
||||
|
||||
<div className="absolute right-0 mt-2 w-96 bg-white rounded-lg shadow-xl border border-gray-200 z-20 max-h-[600px] overflow-hidden flex flex-col">
|
||||
{/* Заголовок */}
|
||||
<div className="px-4 py-3 border-b border-gray-200 flex justify-between items-center">
|
||||
<h3 className="text-lg font-semibold text-gray-800">Уведомления</h3>
|
||||
<Link
|
||||
to="/dashboard/notifications"
|
||||
onClick={() => setIsOpen(false)}
|
||||
className="text-sm text-ospab-primary hover:underline"
|
||||
>
|
||||
Все
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Список уведомлений */}
|
||||
<div className="overflow-y-auto flex-1">
|
||||
{loading ? (
|
||||
<div className="flex justify-center items-center py-8">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-ospab-primary"></div>
|
||||
</div>
|
||||
) : notifications.length === 0 ? (
|
||||
<div className="px-4 py-8 text-center text-gray-500">
|
||||
<svg className="mx-auto h-12 w-12 text-gray-400 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
|
||||
</svg>
|
||||
<p>Нет уведомлений</p>
|
||||
</div>
|
||||
) : (
|
||||
notifications.map((notification) => (
|
||||
<Link
|
||||
key={notification.id}
|
||||
to={notification.actionUrl || '/dashboard/notifications'}
|
||||
onClick={() => handleNotificationClick(notification)}
|
||||
className={`block px-4 py-3 hover:bg-gray-50 transition-colors border-l-4 ${
|
||||
notification.isRead ? 'border-transparent' : 'border-ospab-primary bg-blue-50'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
{/* Цветовой индикатор вместо иконки */}
|
||||
<div className={`flex-shrink-0 w-3 h-3 rounded-full mt-2 ${
|
||||
notification.color === 'green' ? 'bg-green-500' :
|
||||
notification.color === 'blue' ? 'bg-blue-500' :
|
||||
notification.color === 'orange' ? 'bg-orange-500' :
|
||||
notification.color === 'red' ? 'bg-red-500' :
|
||||
notification.color === 'purple' ? 'bg-purple-500' :
|
||||
'bg-gray-500'
|
||||
}`}></div>
|
||||
|
||||
{/* Содержимое */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className={`text-sm font-medium ${notification.isRead ? 'text-gray-800' : 'text-gray-900 font-semibold'}`}>
|
||||
{notification.title}
|
||||
</p>
|
||||
<p className="text-sm text-gray-600 mt-1 line-clamp-2">
|
||||
{notification.message}
|
||||
</p>
|
||||
<p className="text-xs text-gray-400 mt-1">
|
||||
{formatDate(notification.createdAt)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Индикатор непрочитанного */}
|
||||
{!notification.isRead && (
|
||||
<div className="flex-shrink-0 w-2 h-2 bg-ospab-primary rounded-full mt-2"></div>
|
||||
)}
|
||||
</div>
|
||||
</Link>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Футер с кнопкой */}
|
||||
{notifications.length > 0 && (
|
||||
<div className="px-4 py-3 border-t border-gray-200">
|
||||
<Link
|
||||
to="/dashboard/notifications"
|
||||
onClick={() => setIsOpen(false)}
|
||||
className="block w-full text-center py-2 text-sm text-ospab-primary hover:bg-gray-50 rounded-md transition-colors"
|
||||
>
|
||||
Показать все уведомления
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default NotificationBell;
|
||||
173
ospabhost/frontend/src/components/QRLogin.tsx
Normal file
173
ospabhost/frontend/src/components/QRLogin.tsx
Normal file
@@ -0,0 +1,173 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { QRCodeSVG } from 'qrcode.react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import useAuth from '../context/useAuth';
|
||||
import apiClient from '../utils/apiClient';
|
||||
|
||||
interface QRLoginProps {
|
||||
onSuccess?: () => void;
|
||||
}
|
||||
|
||||
const QRLogin: React.FC<QRLoginProps> = ({ onSuccess }) => {
|
||||
const navigate = useNavigate();
|
||||
const { login } = useAuth();
|
||||
const [qrCode, setQrCode] = useState<string>('');
|
||||
const [status, setStatus] = useState<'generating' | 'waiting' | 'scanning' | 'expired' | 'error'>('generating');
|
||||
const [pollingInterval, setPollingInterval] = useState<NodeJS.Timeout | null>(null);
|
||||
const [refreshInterval, setRefreshInterval] = useState<NodeJS.Timeout | null>(null);
|
||||
const qrLinkBase = typeof window !== 'undefined' ? window.location.origin : '';
|
||||
|
||||
useEffect(() => {
|
||||
generateQR();
|
||||
return () => {
|
||||
if (pollingInterval) clearInterval(pollingInterval);
|
||||
if (refreshInterval) clearInterval(refreshInterval);
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const generateQR = async () => {
|
||||
try {
|
||||
setStatus('generating');
|
||||
const response = await apiClient.post('/api/qr-auth/generate');
|
||||
setQrCode(response.data.code);
|
||||
setStatus('waiting');
|
||||
startPolling(response.data.code);
|
||||
|
||||
// Автоматическое обновление QR-кода каждые 60 секунд
|
||||
if (refreshInterval) clearInterval(refreshInterval);
|
||||
const interval = setInterval(() => {
|
||||
generateQR();
|
||||
}, 60000);
|
||||
setRefreshInterval(interval);
|
||||
} catch (error) {
|
||||
console.error('Ошибка генерации QR:', error);
|
||||
setStatus('error');
|
||||
}
|
||||
};
|
||||
|
||||
const startPolling = (code: string) => {
|
||||
const interval = setInterval(async () => {
|
||||
try {
|
||||
const response = await apiClient.get(`/api/qr-auth/status/${code}`);
|
||||
|
||||
// Если статус изменился на "scanning" (пользователь открыл страницу подтверждения)
|
||||
if (response.data.status === 'scanning') {
|
||||
setStatus('scanning');
|
||||
}
|
||||
|
||||
if (response.data.status === 'confirmed' && response.data.token) {
|
||||
clearInterval(interval);
|
||||
setPollingInterval(null);
|
||||
|
||||
// Вызываем login из контекста для обновления состояния
|
||||
login(response.data.token);
|
||||
|
||||
if (onSuccess) {
|
||||
onSuccess();
|
||||
} else {
|
||||
navigate('/dashboard');
|
||||
}
|
||||
} else if (response.data.status === 'rejected') {
|
||||
clearInterval(interval);
|
||||
setPollingInterval(null);
|
||||
setStatus('error');
|
||||
}
|
||||
} catch (error) {
|
||||
const axiosError = error as { response?: { status?: number } };
|
||||
if (axiosError.response?.status === 404 || axiosError.response?.status === 410) {
|
||||
clearInterval(interval);
|
||||
setPollingInterval(null);
|
||||
setStatus('expired');
|
||||
}
|
||||
}
|
||||
}, 2000); // Проверка каждые 2 секунды
|
||||
|
||||
setPollingInterval(interval);
|
||||
};
|
||||
|
||||
const getStatusMessage = () => {
|
||||
switch (status) {
|
||||
case 'generating':
|
||||
return 'Генерация...';
|
||||
case 'waiting':
|
||||
return 'Отсканируйте QR-код телефоном, на котором вы уже авторизованы';
|
||||
case 'scanning':
|
||||
return 'Ожидание подтверждения на телефоне...';
|
||||
case 'expired':
|
||||
return 'QR-код истёк';
|
||||
case 'error':
|
||||
return 'Ошибка';
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-white rounded-2xl shadow-xl p-8 w-full max-w-md">
|
||||
<div className="text-center mb-6">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-2">Вход по QR-коду</h2>
|
||||
<p className="text-gray-600 text-sm">
|
||||
{getStatusMessage()}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-center justify-center">
|
||||
{status === 'generating' && (
|
||||
<div className="w-64 h-64 flex items-center justify-center">
|
||||
<div className="animate-spin rounded-full h-16 w-16 border-b-4 border-blue-500"></div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(status === 'waiting' || status === 'scanning') && qrCode && (
|
||||
<div className="relative">
|
||||
<div className="bg-white p-4 rounded-xl shadow-lg">
|
||||
<QRCodeSVG
|
||||
value={`${qrLinkBase}/qr-login?code=${qrCode}`}
|
||||
size={256}
|
||||
level="H"
|
||||
includeMargin={true}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{status === 'expired' && (
|
||||
<div className="w-64 h-64 flex flex-col items-center justify-center gap-4">
|
||||
<div className="text-6xl text-orange-500">⌛</div>
|
||||
<button
|
||||
onClick={generateQR}
|
||||
className="bg-blue-500 hover:bg-blue-600 text-white px-6 py-3 rounded-lg font-medium transition-colors duration-200"
|
||||
>
|
||||
Обновить
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{status === 'error' && (
|
||||
<div className="w-64 h-64 flex flex-col items-center justify-center gap-4">
|
||||
<div className="text-6xl text-red-500">✕</div>
|
||||
<button
|
||||
onClick={generateQR}
|
||||
className="bg-blue-500 hover:bg-blue-600 text-white px-6 py-3 rounded-lg font-medium transition-colors duration-200"
|
||||
>
|
||||
Попробовать снова
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Alternative Login */}
|
||||
<div className="mt-6 text-center">
|
||||
<button
|
||||
onClick={() => window.location.reload()}
|
||||
className="text-blue-500 hover:text-blue-600 font-medium text-sm"
|
||||
>
|
||||
Войти по паролю
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default QRLogin;
|
||||
43
ospabhost/frontend/src/components/ScrollToTop.tsx
Normal file
43
ospabhost/frontend/src/components/ScrollToTop.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
const ScrollToTop = () => {
|
||||
const [isVisible, setIsVisible] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const toggleVisibility = () => {
|
||||
if (window.pageYOffset > 400) {
|
||||
setIsVisible(true);
|
||||
} else {
|
||||
setIsVisible(false);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('scroll', toggleVisibility);
|
||||
return () => window.removeEventListener('scroll', toggleVisibility);
|
||||
}, []);
|
||||
|
||||
const scrollToTop = () => {
|
||||
window.scrollTo({
|
||||
top: 0,
|
||||
behavior: 'smooth'
|
||||
});
|
||||
};
|
||||
|
||||
if (!isVisible) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={scrollToTop}
|
||||
className="fixed bottom-8 right-8 p-3 bg-blue-500 hover:bg-blue-600 text-white rounded-full shadow-xl transition-all duration-300 hover:scale-110 z-40 animate-fade-in"
|
||||
aria-label="Наверх"
|
||||
>
|
||||
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 10l7-7m0 0l7 7m-7-7v18" />
|
||||
</svg>
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
export default ScrollToTop;
|
||||
413
ospabhost/frontend/src/components/ServerMetrics.tsx
Normal file
413
ospabhost/frontend/src/components/ServerMetrics.tsx
Normal file
@@ -0,0 +1,413 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
LineChart,
|
||||
Line,
|
||||
AreaChart,
|
||||
Area,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
Legend,
|
||||
ResponsiveContainer
|
||||
} from 'recharts';
|
||||
import axios from 'axios';
|
||||
import { API_URL } from '../config/api';
|
||||
|
||||
interface ServerMetricsProps {
|
||||
serverId: number;
|
||||
}
|
||||
|
||||
interface MetricData {
|
||||
timestamp: string;
|
||||
cpuUsage: number;
|
||||
memoryUsage: number;
|
||||
diskUsage: number;
|
||||
networkIn: number;
|
||||
networkOut: number;
|
||||
status: string;
|
||||
}
|
||||
|
||||
interface CurrentMetrics {
|
||||
vmid: number;
|
||||
status: string;
|
||||
uptime: number;
|
||||
cpu: number;
|
||||
memory: {
|
||||
used: number;
|
||||
max: number;
|
||||
usage: number;
|
||||
};
|
||||
disk: {
|
||||
used: number;
|
||||
max: number;
|
||||
usage: number;
|
||||
};
|
||||
network: {
|
||||
in: number;
|
||||
out: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface Summary {
|
||||
cpu: { avg: number; max: number; min: number };
|
||||
memory: { avg: number; max: number; min: number };
|
||||
disk: { avg: number; max: number; min: number };
|
||||
network: { totalIn: number; totalOut: number };
|
||||
uptime: number;
|
||||
}
|
||||
|
||||
export default function ServerMetrics({ serverId }: ServerMetricsProps) {
|
||||
const [period, setPeriod] = useState<'1h' | '6h' | '24h' | '7d' | '30d'>('24h');
|
||||
const [history, setHistory] = useState<MetricData[]>([]);
|
||||
const [current, setCurrent] = useState<CurrentMetrics | null>(null);
|
||||
const [summary, setSummary] = useState<Summary | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const formatBytes = (bytes: number) => {
|
||||
if (bytes === 0) return '0 B';
|
||||
const k = 1024;
|
||||
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||
};
|
||||
|
||||
const formatUptime = (seconds: number) => {
|
||||
const days = Math.floor(seconds / 86400);
|
||||
const hours = Math.floor((seconds % 86400) / 3600);
|
||||
const minutes = Math.floor((seconds % 3600) / 60);
|
||||
|
||||
if (days > 0) return `${days}д ${hours}ч`;
|
||||
if (hours > 0) return `${hours}ч ${minutes}м`;
|
||||
return `${minutes}м`;
|
||||
};
|
||||
|
||||
const formatTimestamp = (timestamp: string) => {
|
||||
const date = new Date(timestamp);
|
||||
if (period === '1h' || period === '6h') {
|
||||
return date.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });
|
||||
} else if (period === '24h') {
|
||||
return date.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });
|
||||
} else {
|
||||
return date.toLocaleDateString('ru-RU', { month: 'short', day: 'numeric' });
|
||||
}
|
||||
};
|
||||
|
||||
const fetchMetrics = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
|
||||
const token = localStorage.getItem('access_token');
|
||||
if (!token) {
|
||||
throw new Error('Токен не найден. Пожалуйста, войдите снова.');
|
||||
}
|
||||
|
||||
// Получаем текущие метрики
|
||||
const currentRes = await axios.get(`${API_URL}/api/server/${serverId}/metrics`, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
console.log('📊 Текущие метрики:', currentRes.data.data);
|
||||
setCurrent(currentRes.data.data);
|
||||
|
||||
// Получаем историю
|
||||
const historyRes = await axios.get(`${API_URL}/api/server/${serverId}/metrics/history`, {
|
||||
params: { period },
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
console.log('📈 История метрик:', historyRes.data.data?.length, 'точек данных');
|
||||
setHistory(historyRes.data.data || []);
|
||||
|
||||
// Получаем сводку
|
||||
const summaryRes = await axios.get(`${API_URL}/api/server/${serverId}/metrics/summary`, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
console.log('📋 Сводка метрик:', summaryRes.data.data);
|
||||
setSummary(summaryRes.data.data);
|
||||
|
||||
} catch (err: unknown) {
|
||||
const error = err as { response?: { status?: number; data?: { error?: string } }; message?: string };
|
||||
console.error('❌ Ошибка загрузки метрик:', error);
|
||||
if (error.response?.status === 401) {
|
||||
setError('Ошибка авторизации. Пожалуйста, войдите снова.');
|
||||
// Можно добавить редирект на логин
|
||||
// window.location.href = '/login';
|
||||
} else {
|
||||
setError(error.response?.data?.error || error.message || 'Ошибка загрузки метрик');
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchMetrics();
|
||||
// Обновляем каждую минуту
|
||||
const interval = setInterval(fetchMetrics, 60000);
|
||||
return () => clearInterval(interval);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [serverId, period]);
|
||||
|
||||
if (loading && !current) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<div className="text-gray-500">Загрузка метрик...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="bg-red-50 border border-red-200 rounded-lg p-4">
|
||||
<p className="text-red-600">{error}</p>
|
||||
<button
|
||||
onClick={fetchMetrics}
|
||||
className="mt-2 text-sm text-red-600 hover:text-red-800 underline"
|
||||
>
|
||||
Попробовать снова
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Текущие метрики */}
|
||||
{current && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
{/* CPU */}
|
||||
<div className="bg-white rounded-lg shadow p-6 border border-gray-200">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h3 className="text-sm font-medium text-gray-600">CPU</h3>
|
||||
<span className={`text-xs px-2 py-1 rounded ${
|
||||
Number(current.cpu) * 100 > 80 ? 'bg-red-100 text-red-700' :
|
||||
Number(current.cpu) * 100 > 50 ? 'bg-yellow-100 text-yellow-700' :
|
||||
'bg-green-100 text-green-700'
|
||||
}`}>
|
||||
{current.status}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-3xl font-bold text-gray-900">
|
||||
{(Number(current.cpu) * 100).toFixed(1)}%
|
||||
</div>
|
||||
{summary && (
|
||||
<div className="mt-2 text-xs text-gray-500">
|
||||
Ср: {summary.cpu.avg.toFixed(1)}% | Макс: {summary.cpu.max.toFixed(1)}%
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Memory */}
|
||||
<div className="bg-white rounded-lg shadow p-6 border border-gray-200">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h3 className="text-sm font-medium text-gray-600">Память</h3>
|
||||
</div>
|
||||
<div className="text-3xl font-bold text-gray-900">
|
||||
{current.memory.usage.toFixed(1)}%
|
||||
</div>
|
||||
<div className="mt-1 text-sm text-gray-500">
|
||||
{formatBytes(current.memory.used)} / {formatBytes(current.memory.max)}
|
||||
</div>
|
||||
{summary && (
|
||||
<div className="mt-2 text-xs text-gray-500">
|
||||
Ср: {summary.memory.avg.toFixed(1)}%
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Disk */}
|
||||
<div className="bg-white rounded-lg shadow p-6 border border-gray-200">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h3 className="text-sm font-medium text-gray-600">Диск</h3>
|
||||
</div>
|
||||
<div className="text-3xl font-bold text-gray-900">
|
||||
{current.disk.usage.toFixed(1)}%
|
||||
</div>
|
||||
<div className="mt-1 text-sm text-gray-500">
|
||||
{formatBytes(current.disk.used)} / {formatBytes(current.disk.max)}
|
||||
</div>
|
||||
{summary && (
|
||||
<div className="mt-2 text-xs text-gray-500">
|
||||
Ср: {summary.disk.avg.toFixed(1)}%
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Network */}
|
||||
<div className="bg-white rounded-lg shadow p-6 border border-gray-200">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h3 className="text-sm font-medium text-gray-600">Сеть</h3>
|
||||
</div>
|
||||
<div className="text-sm font-medium text-gray-900">
|
||||
↓ {formatBytes(current.network.in)}
|
||||
</div>
|
||||
<div className="text-sm font-medium text-gray-900 mt-1">
|
||||
↑ {formatBytes(current.network.out)}
|
||||
</div>
|
||||
<div className="mt-2 text-xs text-gray-500">
|
||||
Uptime: {formatUptime(current.uptime)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Фильтр периода */}
|
||||
<div className="flex items-center space-x-2">
|
||||
<span className="text-sm font-medium text-gray-700">Период:</span>
|
||||
{(['1h', '6h', '24h', '7d', '30d'] as const).map((p) => (
|
||||
<button
|
||||
key={p}
|
||||
onClick={() => setPeriod(p)}
|
||||
className={`px-3 py-1 text-sm rounded-md transition ${
|
||||
period === p
|
||||
? 'bg-ospab-primary text-white'
|
||||
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
|
||||
}`}
|
||||
>
|
||||
{p === '1h' ? '1 час' : p === '6h' ? '6 часов' : p === '24h' ? '24 часа' : p === '7d' ? '7 дней' : '30 дней'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Графики */}
|
||||
{history.length > 0 ? (
|
||||
<div className="space-y-6">
|
||||
{/* CPU График */}
|
||||
<div className="bg-white rounded-lg shadow p-6 border border-gray-200">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-4">Использование CPU</h3>
|
||||
<ResponsiveContainer width="100%" height={250}>
|
||||
<AreaChart data={history}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis
|
||||
dataKey="timestamp"
|
||||
tickFormatter={formatTimestamp}
|
||||
style={{ fontSize: '12px' }}
|
||||
/>
|
||||
<YAxis
|
||||
domain={[0, 100]}
|
||||
tickFormatter={(value) => `${value}%`}
|
||||
style={{ fontSize: '12px' }}
|
||||
/>
|
||||
<Tooltip
|
||||
formatter={(value: number) => `${value.toFixed(2)}%`}
|
||||
labelFormatter={(label) => new Date(label).toLocaleString('ru-RU')}
|
||||
/>
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="cpuUsage"
|
||||
stroke="#F97316"
|
||||
fill="#FDBA74"
|
||||
name="CPU"
|
||||
/>
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
|
||||
{/* Memory и Disk */}
|
||||
<div className="bg-white rounded-lg shadow p-6 border border-gray-200">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-4">Использование памяти и диска</h3>
|
||||
<ResponsiveContainer width="100%" height={250}>
|
||||
<LineChart data={history}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis
|
||||
dataKey="timestamp"
|
||||
tickFormatter={formatTimestamp}
|
||||
style={{ fontSize: '12px' }}
|
||||
/>
|
||||
<YAxis
|
||||
domain={[0, 100]}
|
||||
tickFormatter={(value) => `${value}%`}
|
||||
style={{ fontSize: '12px' }}
|
||||
/>
|
||||
<Tooltip
|
||||
formatter={(value: number) => `${value.toFixed(2)}%`}
|
||||
labelFormatter={(label) => new Date(label).toLocaleString('ru-RU')}
|
||||
/>
|
||||
<Legend />
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="memoryUsage"
|
||||
stroke="#3B82F6"
|
||||
name="Память"
|
||||
dot={false}
|
||||
/>
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="diskUsage"
|
||||
stroke="#10B981"
|
||||
name="Диск"
|
||||
dot={false}
|
||||
/>
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
|
||||
{/* Network Traffic */}
|
||||
<div className="bg-white rounded-lg shadow p-6 border border-gray-200">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-4">Сетевой трафик</h3>
|
||||
<ResponsiveContainer width="100%" height={250}>
|
||||
<AreaChart data={history}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis
|
||||
dataKey="timestamp"
|
||||
tickFormatter={formatTimestamp}
|
||||
style={{ fontSize: '12px' }}
|
||||
/>
|
||||
<YAxis
|
||||
tickFormatter={(value) => formatBytes(value)}
|
||||
style={{ fontSize: '12px' }}
|
||||
/>
|
||||
<Tooltip
|
||||
formatter={(value: number) => formatBytes(value)}
|
||||
labelFormatter={(label) => new Date(label).toLocaleString('ru-RU')}
|
||||
/>
|
||||
<Legend />
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="networkIn"
|
||||
stroke="#8B5CF6"
|
||||
fill="#C4B5FD"
|
||||
name="Входящий"
|
||||
/>
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="networkOut"
|
||||
stroke="#EC4899"
|
||||
fill="#F9A8D4"
|
||||
name="Исходящий"
|
||||
/>
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg p-12 text-center border-2 border-dashed border-gray-300">
|
||||
<div className="text-6xl mb-4">📊</div>
|
||||
<h3 className="text-xl font-semibold text-gray-800 mb-2">
|
||||
{loading ? 'Загрузка данных...' : 'Нет данных за выбранный период'}
|
||||
</h3>
|
||||
<p className="text-gray-600 mb-4">
|
||||
{current ? 'Метрики собираются автоматически каждую минуту' : 'Данные появятся через 1-2 минуты после запуска сервера'}
|
||||
</p>
|
||||
{current && (
|
||||
<div className="mt-6 p-4 bg-blue-50 rounded-lg border border-blue-200 max-w-md mx-auto">
|
||||
<p className="text-sm text-blue-800 font-medium mb-2">💡 Хотите увидеть графики?</p>
|
||||
<p className="text-xs text-blue-700">
|
||||
1. Откройте консоль сервера<br/>
|
||||
2. Запустите: <code className="bg-blue-100 px-2 py-1 rounded">stress-ng --cpu 2 --cpu-load 50 --timeout 180s</code><br/>
|
||||
3. Обновите страницу через 1-2 минуты
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
onClick={fetchMetrics}
|
||||
className="mt-6 px-6 py-2 bg-ospab-primary text-white rounded-lg hover:bg-ospab-accent transition"
|
||||
>
|
||||
🔄 Обновить данные
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,12 +2,12 @@ export const StructuredData = () => {
|
||||
const schema = {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Organization",
|
||||
"name": "Ospab.host",
|
||||
"name": "ospab.host",
|
||||
"url": "https://ospab.host",
|
||||
"logo": "https://ospab.host/logo.jpg",
|
||||
"description": "Облачный хостинг и виртуальные машины с высокопроизводительной инфраструктурой",
|
||||
"sameAs": [
|
||||
"https://github.com/Ospab"
|
||||
"https://github.com/ospab"
|
||||
],
|
||||
"address": {
|
||||
"@type": "PostalAddress",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { createContext, useContext, useState, useCallback } from 'react';
|
||||
import React, { useState, useCallback } from 'react';
|
||||
import { ToastContext } from '../hooks/toastContext';
|
||||
|
||||
export type ToastType = 'success' | 'error' | 'warning' | 'info';
|
||||
|
||||
@@ -8,22 +9,6 @@ export interface Toast {
|
||||
type: ToastType;
|
||||
}
|
||||
|
||||
interface ToastContextType {
|
||||
toasts: Toast[];
|
||||
addToast: (message: string, type?: ToastType) => void;
|
||||
removeToast: (id: string) => void;
|
||||
}
|
||||
|
||||
const ToastContext = createContext<ToastContextType | undefined>(undefined);
|
||||
|
||||
export const useToast = () => {
|
||||
const context = useContext(ToastContext);
|
||||
if (!context) {
|
||||
throw new Error('useToast must be used within ToastProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const [toasts, setToasts] = useState<Toast[]>([]);
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import { FaGithub } from 'react-icons/fa';
|
||||
import logo from '../assets/logo.svg';
|
||||
|
||||
const Footer = () => {
|
||||
@@ -11,7 +12,7 @@ const Footer = () => {
|
||||
{/* About Section */}
|
||||
<div>
|
||||
<div className="mb-4 flex justify-center md:justify-start">
|
||||
<img src={logo} alt="Логотип" className="h-16 w-auto" />
|
||||
<img src={logo} alt="Логотип" className="h-16 w-auto" width="64" height="64" />
|
||||
</div>
|
||||
<h3 className="text-xl font-bold mb-4">О нас</h3>
|
||||
<p className="text-sm text-gray-400">
|
||||
@@ -26,6 +27,7 @@ const Footer = () => {
|
||||
<li><Link to="/" className="text-gray-400 hover:text-white transition-colors">Главная</Link></li>
|
||||
<li><Link to="/tariffs" className="text-gray-400 hover:text-white transition-colors">Тарифы</Link></li>
|
||||
<li><Link to="/about" className="text-gray-400 hover:text-white transition-colors">О нас</Link></li>
|
||||
<li><Link to="/blog" className="text-gray-400 hover:text-white transition-colors">Блог</Link></li>
|
||||
<li><Link to="/login" className="text-gray-400 hover:text-white transition-colors">Войти</Link></li>
|
||||
</ul>
|
||||
</div>
|
||||
@@ -36,6 +38,17 @@ const Footer = () => {
|
||||
<ul className="space-y-2 text-sm">
|
||||
<li><Link to="/privacy" className="text-gray-400 hover:text-white transition-colors">Политика конфиденциальности</Link></li>
|
||||
<li><Link to="/terms" className="text-gray-400 hover:text-white transition-colors">Условия использования</Link></li>
|
||||
<li>
|
||||
<a
|
||||
href="https://github.com/ospab/ospabhost8.1"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-gray-400 hover:text-white transition-colors flex items-center justify-center md:justify-start gap-2"
|
||||
>
|
||||
<FaGithub className="text-xl" />
|
||||
GitHub
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Link } from 'react-router-dom';
|
||||
import { useState } from 'react';
|
||||
import useAuth from '../context/useAuth';
|
||||
import logo from '../assets/logo.svg';
|
||||
import NotificationBell from './NotificationBell';
|
||||
|
||||
const Header = () => {
|
||||
const { isLoggedIn, logout } = useAuth();
|
||||
@@ -18,7 +19,7 @@ const Header = () => {
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="flex items-center gap-1">
|
||||
<Link to="/" className="flex items-center">
|
||||
<img src={logo} alt="Логотип" className="h-10 lg:h-14 w-auto mr-2" />
|
||||
<img src={logo} alt="Логотип" className="h-10 lg:h-14 w-auto mr-2" width="56" height="56" />
|
||||
<span className="font-mono text-xl lg:text-2xl text-gray-800 font-bold">ospab.host</span>
|
||||
</Link>
|
||||
</div>
|
||||
@@ -26,10 +27,12 @@ const Header = () => {
|
||||
{/* Desktop Menu */}
|
||||
<div className="hidden md:flex items-center space-x-4">
|
||||
<Link to="/tariffs" className="text-gray-600 hover:text-ospab-primary transition-colors">Тарифы</Link>
|
||||
<Link to="/blog" className="text-gray-600 hover:text-ospab-primary transition-colors">Блог</Link>
|
||||
<Link to="/about" className="text-gray-600 hover:text-ospab-primary transition-colors">О нас</Link>
|
||||
{isLoggedIn ? (
|
||||
<>
|
||||
<Link to="/dashboard" className="text-gray-600 hover:text-ospab-primary transition-colors">Личный кабинет</Link>
|
||||
<NotificationBell />
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="px-4 py-2 rounded-full text-white font-bold transition-colors transform hover:scale-105 bg-gray-500 hover:bg-red-500"
|
||||
@@ -54,8 +57,10 @@ const Header = () => {
|
||||
<button
|
||||
onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
|
||||
className="md:hidden p-2 text-gray-800"
|
||||
aria-label={isMobileMenuOpen ? "Закрыть меню" : "Открыть меню"}
|
||||
aria-expanded={isMobileMenuOpen}
|
||||
>
|
||||
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
|
||||
{isMobileMenuOpen ? (
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
) : (
|
||||
@@ -75,6 +80,13 @@ const Header = () => {
|
||||
>
|
||||
Тарифы
|
||||
</Link>
|
||||
<Link
|
||||
to="/blog"
|
||||
className="block py-2 text-gray-600 hover:text-ospab-primary transition-colors"
|
||||
onClick={() => setIsMobileMenuOpen(false)}
|
||||
>
|
||||
Блог
|
||||
</Link>
|
||||
<Link
|
||||
to="/about"
|
||||
className="block py-2 text-gray-600 hover:text-ospab-primary transition-colors"
|
||||
|
||||
@@ -18,10 +18,10 @@ export const showAlert = (message: string, type: 'success' | 'error' | 'info' |
|
||||
};
|
||||
|
||||
const iconMap = {
|
||||
success: '✅',
|
||||
error: '❌',
|
||||
info: 'ℹ️',
|
||||
warning: '⚠️'
|
||||
success: '✓',
|
||||
error: '×',
|
||||
info: 'i',
|
||||
warning: '!'
|
||||
};
|
||||
|
||||
root.render(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import Header from './header';
|
||||
import Footer from './footer';
|
||||
import ScrollToTop from './ScrollToTop';
|
||||
import React from 'react';
|
||||
|
||||
interface PageTmplProps {
|
||||
@@ -10,10 +11,11 @@ const PageTmpl: React.FC<PageTmplProps> = ({ children }) => {
|
||||
return (
|
||||
<div className="flex flex-col min-h-screen">
|
||||
<Header />
|
||||
<main className="flex-grow">
|
||||
<main className="flex-grow">
|
||||
{children}
|
||||
</main>
|
||||
<Footer />
|
||||
<ScrollToTop />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -7,8 +7,11 @@ interface PrivateRouteProps {
|
||||
}
|
||||
|
||||
const PrivateRoute: React.FC<PrivateRouteProps> = ({ children }) => {
|
||||
const { isLoggedIn } = useAuth();
|
||||
const { isLoggedIn, isInitialized } = useAuth();
|
||||
const location = useLocation();
|
||||
if (!isInitialized) {
|
||||
return null;
|
||||
}
|
||||
return isLoggedIn ? children : <Navigate to="/login" replace state={{ from: location }} />;
|
||||
};
|
||||
|
||||
|
||||
@@ -2,8 +2,36 @@
|
||||
* Централизованная конфигурация API
|
||||
*/
|
||||
|
||||
// API URL - напрямую на порт 5000
|
||||
export const API_URL = import.meta.env.VITE_API_URL || 'https://ospab.host:5000';
|
||||
const resolveDefaultApiUrl = () => {
|
||||
if (typeof window === 'undefined') {
|
||||
return import.meta.env.DEV ? 'http://localhost:5000' : '';
|
||||
}
|
||||
|
||||
// WebSocket URL - напрямую на порт 5000
|
||||
export const SOCKET_URL = import.meta.env.VITE_SOCKET_URL || 'wss://ospab.host:5000';
|
||||
if (import.meta.env.DEV) {
|
||||
return 'http://localhost:5000';
|
||||
}
|
||||
|
||||
return window.location.origin;
|
||||
};
|
||||
|
||||
const resolveDefaultSocketUrl = (apiUrl: string) => {
|
||||
if (!apiUrl) {
|
||||
return import.meta.env.DEV ? 'ws://localhost:5000/ws' : '';
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL(apiUrl);
|
||||
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
url.pathname = '/ws';
|
||||
url.search = '';
|
||||
url.hash = '';
|
||||
return url.toString();
|
||||
} catch (error) {
|
||||
console.warn('[config/api] Некорректный API_URL, используем ws://localhost:5000/ws');
|
||||
return 'ws://localhost:5000/ws';
|
||||
}
|
||||
};
|
||||
|
||||
export const API_URL = import.meta.env.VITE_API_URL || resolveDefaultApiUrl();
|
||||
|
||||
export const SOCKET_URL = import.meta.env.VITE_SOCKET_URL || resolveDefaultSocketUrl(API_URL);
|
||||
|
||||
145
ospabhost/frontend/src/constants/storagePlans.ts
Normal file
145
ospabhost/frontend/src/constants/storagePlans.ts
Normal file
@@ -0,0 +1,145 @@
|
||||
export type StoragePlanId = 'basic' | 'standard' | 'plus' | 'pro' | 'enterprise';
|
||||
|
||||
export interface StoragePlan {
|
||||
id: StoragePlanId;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
price: number;
|
||||
quotaGb: number;
|
||||
bandwidthGb: number;
|
||||
requestLimit: string;
|
||||
bestFor: string;
|
||||
support: string;
|
||||
included: string[];
|
||||
extras: string[];
|
||||
accentClass: string;
|
||||
badge?: string;
|
||||
}
|
||||
|
||||
export const STORAGE_PLANS: StoragePlan[] = [
|
||||
{
|
||||
id: 'basic',
|
||||
title: 'Basic',
|
||||
subtitle: 'Старт для pet-проектов',
|
||||
price: 99,
|
||||
quotaGb: 50,
|
||||
bandwidthGb: 100,
|
||||
requestLimit: '100 000 операций',
|
||||
bestFor: 'Личные проекты, тестовые среды и prototyping',
|
||||
support: 'Тикеты 24/7 • ответ до 24 часов',
|
||||
included: [
|
||||
'50 GB SSD-хранилища включено',
|
||||
'100 GB исходящего трафика',
|
||||
'1 регион (ru-central-1)',
|
||||
'IAM политики и токены доступа'
|
||||
],
|
||||
extras: [
|
||||
'Уведомления о превышении лимитов',
|
||||
'Версионирование по запросу',
|
||||
'Быстрый веб-интерфейс управления'
|
||||
],
|
||||
accentClass: 'text-blue-600 bg-blue-50'
|
||||
},
|
||||
{
|
||||
id: 'standard',
|
||||
title: 'Standard',
|
||||
subtitle: 'Оптимальный выбор',
|
||||
price: 199,
|
||||
quotaGb: 200,
|
||||
bandwidthGb: 500,
|
||||
requestLimit: '500 000 операций',
|
||||
bestFor: 'Коммерческие MVP, сайты и внутренние сервисы',
|
||||
support: 'Приоритетные тикеты • ответ до 12 часов',
|
||||
included: [
|
||||
'200 GB SSD-хранилища',
|
||||
'500 GB исходящего трафика',
|
||||
'2 региона (ru-central-1, eu-east-1)',
|
||||
'Публичные и приватные бакеты'
|
||||
],
|
||||
extras: [
|
||||
'Автоверсионирование объектов',
|
||||
'Webhook-уведомления об изменениях',
|
||||
'Ежедневные снапшоты бакета'
|
||||
],
|
||||
accentClass: 'text-emerald-600 bg-emerald-50',
|
||||
badge: 'Хит продаж'
|
||||
},
|
||||
{
|
||||
id: 'plus',
|
||||
title: 'Plus',
|
||||
subtitle: 'Для продакшн-нагрузки',
|
||||
price: 399,
|
||||
quotaGb: 500,
|
||||
bandwidthGb: 1000,
|
||||
requestLimit: '1 000 000 операций',
|
||||
bestFor: 'Медиа, SaaS и клиентские проекты',
|
||||
support: 'Priority поддержка • ответ до 6 часов',
|
||||
included: [
|
||||
'500 GB SSD + Infrequent хранилище',
|
||||
'1 TB исходящего трафика',
|
||||
'3 региона и кросс-регион репликация',
|
||||
'Расширенные ACL и presigned URL'
|
||||
],
|
||||
extras: [
|
||||
'Живой мониторинг и алерты',
|
||||
'Lifecycle политики хранения',
|
||||
'Доступ к staging окружению'
|
||||
],
|
||||
accentClass: 'text-purple-600 bg-purple-50'
|
||||
},
|
||||
{
|
||||
id: 'pro',
|
||||
title: 'Pro',
|
||||
subtitle: 'Высокие нагрузки и SLA',
|
||||
price: 699,
|
||||
quotaGb: 1000,
|
||||
bandwidthGb: 2500,
|
||||
requestLimit: '5 000 000 операций',
|
||||
bestFor: 'SaaS-платформы, big data и крупные команды',
|
||||
support: 'Выделенный инженер • ответ до 3 часов',
|
||||
included: [
|
||||
'1 TB гибридного хранилища (SSD + Archive)',
|
||||
'2.5 TB исходящего трафика',
|
||||
'Geo-DNS и custom endpoint',
|
||||
'Object Lock (WORM) и аудит логов'
|
||||
],
|
||||
extras: [
|
||||
'Расширенные IAM роли',
|
||||
'Планировщик бэкапов и экспорта',
|
||||
'Подключение к приватной сети'
|
||||
],
|
||||
accentClass: 'text-orange-600 bg-orange-50'
|
||||
},
|
||||
{
|
||||
id: 'enterprise',
|
||||
title: 'Enterprise',
|
||||
subtitle: 'Корпоративный уровень',
|
||||
price: 1999,
|
||||
quotaGb: 5000,
|
||||
bandwidthGb: 10000,
|
||||
requestLimit: 'Безлимитные операции',
|
||||
bestFor: 'Корпорации, финтех и высоконадежные сервисы',
|
||||
support: '24/7 персональный менеджер и SLA 99.99%',
|
||||
included: [
|
||||
'5 TB распределённого хранилища',
|
||||
'10 TB исходящего трафика',
|
||||
'Dedicated аппаратные ресурсы',
|
||||
'White-label и кастомные домены'
|
||||
],
|
||||
extras: [
|
||||
'On-prem/Hybrid сценарии',
|
||||
'Geo-распределённое хранение (3+ регионов)',
|
||||
'Совместное планирование roadmap'
|
||||
],
|
||||
accentClass: 'text-red-600 bg-red-50'
|
||||
}
|
||||
];
|
||||
|
||||
export const STORAGE_PLAN_MAP: Record<StoragePlanId, StoragePlan> = STORAGE_PLANS.reduce((acc, plan) => {
|
||||
acc[plan.id] = plan;
|
||||
return acc;
|
||||
}, {} as Record<StoragePlanId, StoragePlan>);
|
||||
|
||||
export const STORAGE_PLAN_IDS: StoragePlanId[] = STORAGE_PLANS.map((plan) => plan.id);
|
||||
|
||||
export const DEFAULT_STORAGE_PLAN_ID: StoragePlanId = 'standard';
|
||||
231
ospabhost/frontend/src/context/WebSocketContext.tsx
Normal file
231
ospabhost/frontend/src/context/WebSocketContext.tsx
Normal file
@@ -0,0 +1,231 @@
|
||||
import React, { createContext, useContext, useEffect, useRef, useState, useCallback } from 'react';
|
||||
import AuthContext from './authcontext';
|
||||
import { wsLogger } from '../utils/logger';
|
||||
|
||||
// Типы событий (синхронизированы с backend)
|
||||
type RoomType = 'notifications' | 'servers' | 'tickets' | 'balance';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
type AnyObject = Record<string, any>;
|
||||
|
||||
type ServerToClientEvent =
|
||||
| { type: 'auth:success'; userId: number }
|
||||
| { type: 'auth:error'; message: string }
|
||||
| { type: 'notification:new'; notification: AnyObject }
|
||||
| { type: 'notification:read'; notificationId: number }
|
||||
| { type: 'notification:delete'; notificationId: number }
|
||||
| { type: 'server:created'; server: AnyObject }
|
||||
| { type: 'server:status'; serverId: number; status: string; ipAddress?: string }
|
||||
| { type: 'server:deleted'; serverId: number }
|
||||
| { type: 'ticket:new'; ticket: AnyObject }
|
||||
| { type: 'ticket:response'; ticketId: number; response: AnyObject }
|
||||
| { type: 'ticket:status'; ticketId: number; status: string }
|
||||
| { type: 'balance:updated'; newBalance: number }
|
||||
| { type: 'check:status'; checkId: number; status: string }
|
||||
| { type: 'pong' }
|
||||
| { type: 'error'; message: string };
|
||||
|
||||
type MessageHandler = (event: ServerToClientEvent) => void;
|
||||
|
||||
interface WebSocketContextType {
|
||||
isConnected: boolean;
|
||||
subscribe: (room: RoomType, handler: MessageHandler) => void;
|
||||
unsubscribe: (room: RoomType, handler: MessageHandler) => void;
|
||||
send: (message: AnyObject) => void;
|
||||
}
|
||||
|
||||
const WebSocketContext = createContext<WebSocketContextType | null>(null);
|
||||
|
||||
// Экспорт контекста для хука
|
||||
export { WebSocketContext };
|
||||
|
||||
interface WebSocketProviderProps {
|
||||
children: React.ReactNode;
|
||||
url?: string;
|
||||
}
|
||||
|
||||
export const WebSocketProvider: React.FC<WebSocketProviderProps> = ({
|
||||
children,
|
||||
url = 'wss://ospab.host:5000/ws'
|
||||
}) => {
|
||||
const authContext = useContext(AuthContext);
|
||||
const token = authContext?.isLoggedIn ? localStorage.getItem('access_token') : null;
|
||||
const [isConnected, setIsConnected] = useState(false);
|
||||
const wsRef = useRef<WebSocket | null>(null);
|
||||
const reconnectTimeoutRef = useRef<NodeJS.Timeout>();
|
||||
const handlersRef = useRef<Map<RoomType, Set<MessageHandler>>>(new Map());
|
||||
const subscribedRoomsRef = useRef<Set<RoomType>>(new Set());
|
||||
const reconnectAttemptsRef = useRef(0);
|
||||
const maxReconnectAttempts = 5;
|
||||
const baseReconnectDelay = 1000;
|
||||
|
||||
// Подписка на комнату
|
||||
const subscribe = useCallback((room: RoomType, handler: MessageHandler) => {
|
||||
if (!handlersRef.current.has(room)) {
|
||||
handlersRef.current.set(room, new Set());
|
||||
}
|
||||
handlersRef.current.get(room)?.add(handler);
|
||||
|
||||
// Если WebSocket подключен и комната ещё не подписана — отправляем subscribe
|
||||
if (wsRef.current?.readyState === WebSocket.OPEN && !subscribedRoomsRef.current.has(room)) {
|
||||
wsRef.current.send(JSON.stringify({ type: `subscribe:${room}` }));
|
||||
subscribedRoomsRef.current.add(room);
|
||||
wsLogger.log(`Подписались на комнату: ${room}`);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Отписка от комнаты
|
||||
const unsubscribe = useCallback((room: RoomType, handler: MessageHandler) => {
|
||||
const handlers = handlersRef.current.get(room);
|
||||
if (handlers) {
|
||||
handlers.delete(handler);
|
||||
|
||||
// Если больше нет обработчиков — отписываемся от комнаты
|
||||
if (handlers.size === 0) {
|
||||
handlersRef.current.delete(room);
|
||||
if (wsRef.current?.readyState === WebSocket.OPEN && subscribedRoomsRef.current.has(room)) {
|
||||
wsRef.current.send(JSON.stringify({ type: `unsubscribe:${room}` }));
|
||||
subscribedRoomsRef.current.delete(room);
|
||||
wsLogger.log(`Отписались от комнаты: ${room}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Отправка сообщения
|
||||
const send = useCallback((message: AnyObject) => {
|
||||
if (wsRef.current?.readyState === WebSocket.OPEN) {
|
||||
wsRef.current.send(JSON.stringify(message));
|
||||
} else {
|
||||
wsLogger.warn('Попытка отправки сообщения при закрытом соединении');
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Обработка входящих сообщений
|
||||
const handleMessage = useCallback((event: MessageEvent) => {
|
||||
try {
|
||||
const data: ServerToClientEvent = JSON.parse(event.data);
|
||||
|
||||
// Определяем комнату по типу события
|
||||
let room: RoomType | null = null;
|
||||
if (data.type.startsWith('notification:')) room = 'notifications';
|
||||
else if (data.type.startsWith('server:')) room = 'servers';
|
||||
else if (data.type.startsWith('ticket:')) room = 'tickets';
|
||||
else if (data.type.startsWith('balance:')) room = 'balance';
|
||||
|
||||
// Вызываем все обработчики для этой комнаты
|
||||
if (room) {
|
||||
const handlers = handlersRef.current.get(room);
|
||||
if (handlers) {
|
||||
handlers.forEach(handler => handler(data));
|
||||
}
|
||||
}
|
||||
|
||||
// Логирование (для отладки)
|
||||
if (data.type !== 'pong') {
|
||||
wsLogger.log(`Получено событие:`, data);
|
||||
}
|
||||
} catch (error) {
|
||||
wsLogger.error('Ошибка парсинга сообщения:', error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Подключение к WebSocket
|
||||
const connect = useCallback(() => {
|
||||
if (!token) {
|
||||
wsLogger.log('Токен отсутствует, подключение отложено');
|
||||
return;
|
||||
}
|
||||
|
||||
if (wsRef.current?.readyState === WebSocket.OPEN || wsRef.current?.readyState === WebSocket.CONNECTING) {
|
||||
wsLogger.log('Соединение уже активно');
|
||||
return;
|
||||
}
|
||||
|
||||
wsLogger.log('Подключение к WebSocket...');
|
||||
const ws = new WebSocket(url);
|
||||
wsRef.current = ws;
|
||||
|
||||
ws.onopen = () => {
|
||||
wsLogger.log('Соединение установлено');
|
||||
setIsConnected(true);
|
||||
reconnectAttemptsRef.current = 0;
|
||||
|
||||
// Отправляем токен для аутентификации
|
||||
ws.send(JSON.stringify({ type: 'auth', token }));
|
||||
|
||||
// Переподписываемся на все комнаты
|
||||
subscribedRoomsRef.current.forEach(room => {
|
||||
ws.send(JSON.stringify({ type: `subscribe:${room}` }));
|
||||
wsLogger.log(`Переподписались на комнату: ${room}`);
|
||||
});
|
||||
};
|
||||
|
||||
ws.onmessage = handleMessage;
|
||||
|
||||
ws.onerror = (error) => {
|
||||
wsLogger.error('Ошибка соединения:', error);
|
||||
};
|
||||
|
||||
ws.onclose = (event) => {
|
||||
wsLogger.log(`Соединение закрыто (код: ${event.code})`);
|
||||
setIsConnected(false);
|
||||
subscribedRoomsRef.current.clear();
|
||||
|
||||
// Переподключение с экспоненциальной задержкой
|
||||
if (reconnectAttemptsRef.current < maxReconnectAttempts) {
|
||||
const delay = baseReconnectDelay * Math.pow(2, reconnectAttemptsRef.current);
|
||||
wsLogger.log(`Переподключение через ${delay}ms (попытка ${reconnectAttemptsRef.current + 1}/${maxReconnectAttempts})`);
|
||||
reconnectTimeoutRef.current = setTimeout(() => {
|
||||
reconnectAttemptsRef.current++;
|
||||
connect();
|
||||
}, delay);
|
||||
} else {
|
||||
wsLogger.error('Превышено максимальное количество попыток переподключения');
|
||||
}
|
||||
};
|
||||
}, [token, url, handleMessage]);
|
||||
|
||||
// Подключение при монтировании компонента и наличии токена
|
||||
useEffect(() => {
|
||||
if (token) {
|
||||
connect();
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (reconnectTimeoutRef.current) {
|
||||
clearTimeout(reconnectTimeoutRef.current);
|
||||
}
|
||||
if (wsRef.current) {
|
||||
wsRef.current.close();
|
||||
wsRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [token, connect]);
|
||||
|
||||
// Ping каждые 30 секунд
|
||||
useEffect(() => {
|
||||
if (!isConnected) return;
|
||||
|
||||
const pingInterval = setInterval(() => {
|
||||
if (wsRef.current?.readyState === WebSocket.OPEN) {
|
||||
wsRef.current.send(JSON.stringify({ type: 'ping' }));
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
return () => clearInterval(pingInterval);
|
||||
}, [isConnected]);
|
||||
|
||||
const value: WebSocketContextType = {
|
||||
isConnected,
|
||||
subscribe,
|
||||
unsubscribe,
|
||||
send,
|
||||
};
|
||||
|
||||
return (
|
||||
<WebSocketContext.Provider value={value}>
|
||||
{children}
|
||||
</WebSocketContext.Provider>
|
||||
);
|
||||
};
|
||||
@@ -2,23 +2,28 @@
|
||||
import { createContext, useState, useEffect } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
import apiClient from '../utils/apiClient';
|
||||
import type { UserData } from '../pages/dashboard/types';
|
||||
|
||||
interface AuthContextType {
|
||||
isLoggedIn: boolean;
|
||||
isInitialized: boolean;
|
||||
userData: UserData | null;
|
||||
setUserData: (data: UserData | null) => void;
|
||||
login: (token: string) => void;
|
||||
logout: () => void;
|
||||
refreshUser: () => Promise<void>;
|
||||
}
|
||||
|
||||
// Создаем контекст с начальными значениями
|
||||
const AuthContext = createContext<AuthContextType>({
|
||||
isLoggedIn: false,
|
||||
isInitialized: false,
|
||||
userData: null,
|
||||
setUserData: () => {},
|
||||
login: () => {},
|
||||
logout: () => {},
|
||||
refreshUser: async () => {},
|
||||
});
|
||||
|
||||
interface AuthProviderProps {
|
||||
@@ -29,16 +34,57 @@ interface AuthProviderProps {
|
||||
export const AuthProvider = ({ children }: AuthProviderProps) => {
|
||||
const [isLoggedIn, setIsLoggedIn] = useState(false);
|
||||
const [userData, setUserData] = useState<UserData | null>(null);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
const bootstrapSession = async () => {
|
||||
const token = localStorage.getItem('access_token');
|
||||
if (!token) {
|
||||
setIsLoggedIn(false);
|
||||
setUserData(null);
|
||||
setIsInitialized(true);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await apiClient.get('/api/auth/me');
|
||||
const fetchedUser: UserData['user'] = response.data.user;
|
||||
setUserData({
|
||||
user: fetchedUser,
|
||||
balance: fetchedUser.balance ?? 0,
|
||||
tickets: fetchedUser.tickets ?? [],
|
||||
});
|
||||
setIsLoggedIn(true);
|
||||
} catch (error) {
|
||||
console.warn('[Auth] bootstrap failed, clearing token', error);
|
||||
localStorage.removeItem('access_token');
|
||||
setIsLoggedIn(false);
|
||||
setUserData(null);
|
||||
} finally {
|
||||
setIsInitialized(true);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem('access_token');
|
||||
setIsLoggedIn(!!token);
|
||||
// Можно добавить загрузку userData при наличии токена
|
||||
bootstrapSession();
|
||||
|
||||
// Слушаем событие unauthorized из apiClient
|
||||
const handleUnauthorized = () => {
|
||||
setIsLoggedIn(false);
|
||||
setUserData(null);
|
||||
window.location.href = '/401';
|
||||
};
|
||||
|
||||
window.addEventListener('unauthorized', handleUnauthorized);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('unauthorized', handleUnauthorized);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const login = (token: string) => {
|
||||
localStorage.setItem('access_token', token);
|
||||
setIsLoggedIn(true);
|
||||
// После установки токена немедленно валидируем пользователя
|
||||
bootstrapSession();
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
@@ -47,8 +93,30 @@ export const AuthProvider = ({ children }: AuthProviderProps) => {
|
||||
setUserData(null);
|
||||
};
|
||||
|
||||
const refreshUser = async () => {
|
||||
const token = localStorage.getItem('access_token');
|
||||
if (!token) {
|
||||
logout();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await apiClient.get('/api/auth/me');
|
||||
const fetchedUser: UserData['user'] = response.data.user;
|
||||
setUserData({
|
||||
user: fetchedUser,
|
||||
balance: fetchedUser.balance ?? 0,
|
||||
tickets: fetchedUser.tickets ?? [],
|
||||
});
|
||||
setIsLoggedIn(true);
|
||||
} catch (error) {
|
||||
console.error('[Auth] refreshUser failed', error);
|
||||
logout();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ isLoggedIn, userData, setUserData, login, logout }}>
|
||||
<AuthContext.Provider value={{ isLoggedIn, isInitialized, userData, setUserData, login, logout, refreshUser }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
|
||||
10
ospabhost/frontend/src/hooks/toastContext.tsx
Normal file
10
ospabhost/frontend/src/hooks/toastContext.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { createContext } from 'react';
|
||||
import type { ToastType } from '../components/Toast';
|
||||
|
||||
export interface ToastContextType {
|
||||
toasts: Array<{ id: string; message: string; type: ToastType }>;
|
||||
addToast: (message: string, type?: ToastType) => void;
|
||||
removeToast: (id: string) => void;
|
||||
}
|
||||
|
||||
export const ToastContext = createContext<ToastContextType | undefined>(undefined);
|
||||
10
ospabhost/frontend/src/hooks/useToast.ts
Normal file
10
ospabhost/frontend/src/hooks/useToast.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { useContext } from 'react';
|
||||
import { ToastContext } from './toastContext';
|
||||
|
||||
export const useToast = () => {
|
||||
const context = useContext(ToastContext);
|
||||
if (!context) {
|
||||
throw new Error('useToast must be used within a ToastProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
10
ospabhost/frontend/src/hooks/useWebSocket.ts
Normal file
10
ospabhost/frontend/src/hooks/useWebSocket.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { useContext } from 'react';
|
||||
import { WebSocketContext } from '../context/WebSocketContext';
|
||||
|
||||
export const useWebSocket = () => {
|
||||
const context = useContext(WebSocketContext);
|
||||
if (!context) {
|
||||
throw new Error('useWebSocket must be used within WebSocketProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
20
ospabhost/frontend/src/pages/401.tsx
Normal file
20
ospabhost/frontend/src/pages/401.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
import ErrorPage from '../components/ErrorPage';
|
||||
|
||||
export default function Unauthorized() {
|
||||
return (
|
||||
<ErrorPage
|
||||
code="401"
|
||||
title="Требуется авторизация"
|
||||
description="Для доступа к этому ресурсу необходимо войти в систему."
|
||||
icon={
|
||||
<svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
|
||||
</svg>
|
||||
}
|
||||
color="orange"
|
||||
showLoginButton={true}
|
||||
showBackButton={false}
|
||||
showHomeButton={true}
|
||||
/>
|
||||
);
|
||||
}
|
||||
20
ospabhost/frontend/src/pages/403.tsx
Normal file
20
ospabhost/frontend/src/pages/403.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
import ErrorPage from '../components/ErrorPage';
|
||||
|
||||
export default function Forbidden() {
|
||||
return (
|
||||
<ErrorPage
|
||||
code="403"
|
||||
title="Доступ запрещён"
|
||||
description="У вас недостаточно прав для доступа к этой странице. Обратитесь к администратору, если считаете это ошибкой."
|
||||
icon={
|
||||
<svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
|
||||
</svg>
|
||||
}
|
||||
color="purple"
|
||||
showLoginButton={false}
|
||||
showBackButton={true}
|
||||
showHomeButton={true}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,120 +1,20 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import ErrorPage from '../components/ErrorPage';
|
||||
|
||||
export default function NotFound() {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100">
|
||||
<div className="max-w-2xl w-full mx-auto px-6 py-12 text-center">
|
||||
{/* 404 число */}
|
||||
<div className="mb-8">
|
||||
<h1 className="text-9xl font-bold text-indigo-600 animate-bounce">
|
||||
404
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
{/* Иконка */}
|
||||
<div className="mb-8">
|
||||
<svg
|
||||
className="w-32 h-32 mx-auto text-indigo-400"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
{/* Текст */}
|
||||
<h2 className="text-3xl font-bold text-gray-800 mb-4">
|
||||
Страница не найдена
|
||||
</h2>
|
||||
<p className="text-lg text-gray-600 mb-8">
|
||||
К сожалению, запрашиваемая страница не существует или была перемещена.
|
||||
</p>
|
||||
|
||||
{/* Кнопки */}
|
||||
<div className="flex flex-col sm:flex-row gap-4 justify-center">
|
||||
<Link
|
||||
to="/"
|
||||
className="inline-flex items-center justify-center px-6 py-3 border border-transparent text-base font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 transition-colors shadow-lg hover:shadow-xl"
|
||||
>
|
||||
<svg
|
||||
className="w-5 h-5 mr-2"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"
|
||||
/>
|
||||
</svg>
|
||||
На главную
|
||||
</Link>
|
||||
|
||||
<button
|
||||
onClick={() => window.history.back()}
|
||||
className="inline-flex items-center justify-center px-6 py-3 border-2 border-indigo-600 text-base font-medium rounded-md text-indigo-600 bg-white hover:bg-indigo-50 transition-colors"
|
||||
>
|
||||
<svg
|
||||
className="w-5 h-5 mr-2"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M10 19l-7-7m0 0l7-7m-7 7h18"
|
||||
/>
|
||||
</svg>
|
||||
Назад
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Дополнительные ссылки */}
|
||||
<div className="mt-12 pt-8 border-t border-gray-300">
|
||||
<p className="text-sm text-gray-500 mb-4">
|
||||
Возможно, вы искали одну из этих страниц:
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-3 justify-center">
|
||||
<Link
|
||||
to="/tariffs"
|
||||
className="text-sm text-indigo-600 hover:text-indigo-800 hover:underline"
|
||||
>
|
||||
Тарифы
|
||||
</Link>
|
||||
<span className="text-gray-400">•</span>
|
||||
<Link
|
||||
to="/dashboard"
|
||||
className="text-sm text-indigo-600 hover:text-indigo-800 hover:underline"
|
||||
>
|
||||
Личный кабинет
|
||||
</Link>
|
||||
<span className="text-gray-400">•</span>
|
||||
<Link
|
||||
to="/about"
|
||||
className="text-sm text-indigo-600 hover:text-indigo-800 hover:underline"
|
||||
>
|
||||
О нас
|
||||
</Link>
|
||||
<span className="text-gray-400">•</span>
|
||||
<a
|
||||
href="mailto:support@ospab.host"
|
||||
className="text-sm text-indigo-600 hover:text-indigo-800 hover:underline"
|
||||
>
|
||||
Поддержка
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<ErrorPage
|
||||
code="404"
|
||||
title="Страница не найдена"
|
||||
description="К сожалению, запрашиваемая страница не существует или была перемещена."
|
||||
icon={
|
||||
<svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
}
|
||||
color="blue"
|
||||
showLoginButton={false}
|
||||
showBackButton={true}
|
||||
showHomeButton={true}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,233 +1,20 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useState, useEffect } from 'react';
|
||||
import ErrorPage from '../components/ErrorPage';
|
||||
|
||||
export default function ServerError() {
|
||||
const [countdown, setCountdown] = useState(10);
|
||||
const [autoRedirect, setAutoRedirect] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (!autoRedirect || countdown <= 0) return;
|
||||
|
||||
const timer = setInterval(() => {
|
||||
setCountdown((prev) => {
|
||||
if (prev <= 1) {
|
||||
window.location.href = '/';
|
||||
return 0;
|
||||
}
|
||||
return prev - 1;
|
||||
});
|
||||
}, 1000);
|
||||
|
||||
return () => clearInterval(timer);
|
||||
}, [autoRedirect, countdown]);
|
||||
|
||||
const handleRefresh = () => {
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
const handleCancelRedirect = () => {
|
||||
setAutoRedirect(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-red-50 to-orange-100">
|
||||
<div className="max-w-2xl w-full mx-auto px-6 py-12 text-center">
|
||||
{/* 500 число */}
|
||||
<div className="mb-8">
|
||||
<h1 className="text-9xl font-bold text-red-600 animate-pulse">
|
||||
500
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
{/* Иконка */}
|
||||
<div className="mb-8">
|
||||
<svg
|
||||
className="w-32 h-32 mx-auto text-red-400"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
{/* Текст */}
|
||||
<h2 className="text-3xl font-bold text-gray-800 mb-4">
|
||||
Ошибка сервера
|
||||
</h2>
|
||||
<p className="text-lg text-gray-600 mb-4">
|
||||
К сожалению, на сервере произошла ошибка. Мы уже работаем над её устранением.
|
||||
</p>
|
||||
<p className="text-sm text-gray-500 mb-8">
|
||||
Пожалуйста, попробуйте обновить страницу или вернитесь позже.
|
||||
</p>
|
||||
|
||||
{/* Таймер автоперенаправления */}
|
||||
{autoRedirect && countdown > 0 && (
|
||||
<div className="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
|
||||
<p className="text-sm text-blue-800">
|
||||
Автоматическое перенаправление на главную страницу через{' '}
|
||||
<span className="font-bold text-xl text-blue-600">{countdown}</span> сек.
|
||||
</p>
|
||||
<button
|
||||
onClick={handleCancelRedirect}
|
||||
className="mt-2 text-xs text-blue-600 hover:text-blue-800 underline"
|
||||
>
|
||||
Отменить
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Кнопки */}
|
||||
<div className="flex flex-col sm:flex-row gap-4 justify-center mb-8">
|
||||
<button
|
||||
onClick={handleRefresh}
|
||||
className="inline-flex items-center justify-center px-6 py-3 border border-transparent text-base font-medium rounded-md text-white bg-red-600 hover:bg-red-700 transition-colors shadow-lg hover:shadow-xl"
|
||||
>
|
||||
<svg
|
||||
className="w-5 h-5 mr-2"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
|
||||
/>
|
||||
</svg>
|
||||
Обновить страницу
|
||||
</button>
|
||||
|
||||
<Link
|
||||
to="/"
|
||||
className="inline-flex items-center justify-center px-6 py-3 border-2 border-red-600 text-base font-medium rounded-md text-red-600 bg-white hover:bg-red-50 transition-colors"
|
||||
>
|
||||
<svg
|
||||
className="w-5 h-5 mr-2"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"
|
||||
/>
|
||||
</svg>
|
||||
На главную
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Информация для пользователя */}
|
||||
<div className="mt-12 pt-8 border-t border-gray-300">
|
||||
<h3 className="text-lg font-semibold text-gray-800 mb-4">
|
||||
Что можно сделать?
|
||||
</h3>
|
||||
<div className="text-left max-w-md mx-auto space-y-3">
|
||||
<div className="flex items-start">
|
||||
<svg
|
||||
className="w-6 h-6 text-green-500 mr-3 flex-shrink-0 mt-0.5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
|
||||
/>
|
||||
</svg>
|
||||
<p className="text-sm text-gray-600">
|
||||
Обновите страницу (Ctrl+R или F5)
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-start">
|
||||
<svg
|
||||
className="w-6 h-6 text-green-500 mr-3 flex-shrink-0 mt-0.5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
|
||||
/>
|
||||
</svg>
|
||||
<p className="text-sm text-gray-600">
|
||||
Очистите кэш браузера (Ctrl+Shift+Del)
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-start">
|
||||
<svg
|
||||
className="w-6 h-6 text-green-500 mr-3 flex-shrink-0 mt-0.5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
|
||||
/>
|
||||
</svg>
|
||||
<p className="text-sm text-gray-600">
|
||||
Попробуйте зайти позже (5-10 минут)
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-start">
|
||||
<svg
|
||||
className="w-6 h-6 text-green-500 mr-3 flex-shrink-0 mt-0.5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
|
||||
/>
|
||||
</svg>
|
||||
<p className="text-sm text-gray-600">
|
||||
Свяжитесь с поддержкой:{' '}
|
||||
<a
|
||||
href="mailto:support@ospab.host"
|
||||
className="text-red-600 hover:text-red-800 underline"
|
||||
>
|
||||
support@ospab.host
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Код ошибки (для техподдержки) */}
|
||||
<div className="mt-8">
|
||||
<details className="text-left max-w-md mx-auto">
|
||||
<summary className="cursor-pointer text-sm text-gray-500 hover:text-gray-700">
|
||||
Техническая информация
|
||||
</summary>
|
||||
<div className="mt-3 p-4 bg-gray-100 rounded text-xs font-mono text-gray-700">
|
||||
<p>Error: 500 Internal Server Error</p>
|
||||
<p>Timestamp: {new Date().toISOString()}</p>
|
||||
<p>Path: {window.location.pathname}</p>
|
||||
<p>User Agent: {navigator.userAgent.substring(0, 50)}...</p>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<ErrorPage
|
||||
code="500"
|
||||
title="Ошибка сервера"
|
||||
description="На сервере произошла ошибка. Мы уже работаем над её устранением. Попробуйте обновить страницу или вернитесь позже."
|
||||
icon={
|
||||
<svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
|
||||
</svg>
|
||||
}
|
||||
color="red"
|
||||
showLoginButton={false}
|
||||
showBackButton={true}
|
||||
showHomeButton={true}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
20
ospabhost/frontend/src/pages/502.tsx
Normal file
20
ospabhost/frontend/src/pages/502.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
import ErrorPage from '../components/ErrorPage';
|
||||
|
||||
export default function BadGateway() {
|
||||
return (
|
||||
<ErrorPage
|
||||
code="502"
|
||||
title="Неверный шлюз"
|
||||
description="Сервер получил недействительный ответ от вышестоящего сервера. Это временная проблема, попробуйте обновить страницу."
|
||||
icon={
|
||||
<svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.141 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0" />
|
||||
</svg>
|
||||
}
|
||||
color="orange"
|
||||
showLoginButton={false}
|
||||
showBackButton={true}
|
||||
showHomeButton={true}
|
||||
/>
|
||||
);
|
||||
}
|
||||
21
ospabhost/frontend/src/pages/503.tsx
Normal file
21
ospabhost/frontend/src/pages/503.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
import ErrorPage from '../components/ErrorPage';
|
||||
|
||||
export default function ServiceUnavailable() {
|
||||
return (
|
||||
<ErrorPage
|
||||
code="503"
|
||||
title="Сервис недоступен"
|
||||
description="Сервер временно не может обработать запрос. Возможно, проводятся технические работы. Пожалуйста, попробуйте позже."
|
||||
icon={
|
||||
<svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
</svg>
|
||||
}
|
||||
color="orange"
|
||||
showLoginButton={false}
|
||||
showBackButton={true}
|
||||
showHomeButton={true}
|
||||
/>
|
||||
);
|
||||
}
|
||||
20
ospabhost/frontend/src/pages/504.tsx
Normal file
20
ospabhost/frontend/src/pages/504.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
import ErrorPage from '../components/ErrorPage';
|
||||
|
||||
export default function GatewayTimeout() {
|
||||
return (
|
||||
<ErrorPage
|
||||
code="504"
|
||||
title="Превышено время ожидания"
|
||||
description="Сервер не дождался ответа от вышестоящего сервера. Это может быть вызвано временными проблемами с сетью."
|
||||
icon={
|
||||
<svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
}
|
||||
color="orange"
|
||||
showLoginButton={false}
|
||||
showBackButton={true}
|
||||
showHomeButton={true}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,34 +1,288 @@
|
||||
import { FaRocket, FaUsers, FaShieldAlt, FaChartLine, FaHeart, FaServer, FaGithub } from 'react-icons/fa';
|
||||
|
||||
const AboutPage = () => {
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-blue-100 via-white to-ospab-primary flex items-center justify-center py-20 px-4">
|
||||
<div className="bg-white p-10 md:p-16 rounded-3xl shadow-2xl max-w-4xl mx-auto text-center border-4 border-ospab-primary/20">
|
||||
<h1 className="text-5xl md:text-6xl font-extrabold text-ospab-primary mb-8 drop-shadow-lg">История ospab.host</h1>
|
||||
<div className="flex flex-col md:flex-row items-center gap-8 mb-8">
|
||||
<img src="/me.jpg" alt="Георгий" className="w-32 h-32 rounded-full shadow-lg border-4 border-ospab-primary mx-auto" />
|
||||
<div className="text-left md:text-center">
|
||||
<h2 className="text-3xl font-bold text-gray-900 mb-2">Георгий, основатель</h2>
|
||||
<p className="text-lg text-gray-700 mb-2">Возраст: 13 лет</p>
|
||||
<p className="text-lg text-gray-700">Великий Новгород, Россия</p>
|
||||
<div className="min-h-screen bg-white">
|
||||
{/* Hero Section */}
|
||||
<section className="relative bg-gradient-to-br from-ospab-primary to-blue-700 text-white py-20 px-4 overflow-hidden">
|
||||
<div className="absolute inset-0 opacity-10">
|
||||
<div className="absolute top-0 left-0 w-96 h-96 bg-white rounded-full blur-3xl"></div>
|
||||
<div className="absolute bottom-0 right-0 w-96 h-96 bg-white rounded-full blur-3xl"></div>
|
||||
</div>
|
||||
|
||||
<div className="container mx-auto max-w-6xl relative z-10">
|
||||
<div className="text-center mb-12">
|
||||
<h1 className="text-5xl md:text-6xl font-extrabold mb-6 leading-tight">
|
||||
История ospab.host
|
||||
</h1>
|
||||
<p className="text-xl md:text-2xl text-blue-100 max-w-3xl mx-auto">
|
||||
Первый дата-центр в Великом Новгороде.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-lg text-gray-800 leading-relaxed mb-6">
|
||||
<p className="mb-4">В сентябре 2025 года я, Георгий, начал работу над первым дата-центром (ЦОД) и крупным хостингом в Великом Новгороде. Всё началось с мечты — создать место, где любой сможет разместить свой проект, сайт или сервер с максимальной надёжностью и скоростью.</p>
|
||||
<p className="mb-4">Сейчас я работаю над хостингом для будущего ЦОД, а мой друг-инвестор помогает с развитием инфраструктуры. Мы строим не просто сервис, а сообщество, где каждый клиент — как друг, а поддержка всегда рядом.</p>
|
||||
<p className="mb-4">ospab.host — это не просто хостинг. Это первый шаг к цифровому будущему Великого Новгорода, созданный с нуля школьником, который верит в технологии и силу дружбы.</p>
|
||||
<p className="mb-4">Наша миссия — сделать качественный хостинг доступным для всех, а ЦОД — гордостью города. Мы используем современные технологии, заботимся о безопасности и всегда готовы помочь.</p>
|
||||
</section>
|
||||
|
||||
{/* Founder Section */}
|
||||
<section className="py-20 px-4 bg-gray-50">
|
||||
<div className="container mx-auto max-w-6xl">
|
||||
<div className="bg-white rounded-3xl shadow-xl p-8 md:p-12 border border-gray-100">
|
||||
<div className="flex flex-col md:flex-row items-center gap-8 md:gap-12">
|
||||
<div className="flex-shrink-0">
|
||||
<img
|
||||
src="/me.jpg"
|
||||
alt="Георгий, основатель ospab.host"
|
||||
className="w-48 h-48 md:w-56 md:h-56 rounded-2xl shadow-2xl border-4 border-ospab-primary object-cover"
|
||||
width="224"
|
||||
height="224"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 text-center md:text-left">
|
||||
<div className="mb-6">
|
||||
<h2 className="text-4xl font-bold text-gray-900 mb-3">Георгий</h2>
|
||||
<p className="text-xl text-ospab-primary font-semibold mb-2">Основатель и CEO</p>
|
||||
<div className="flex flex-wrap justify-center md:justify-start gap-4 text-gray-600">
|
||||
<span className="flex items-center gap-2">
|
||||
<FaUsers className="text-ospab-primary" />
|
||||
13 лет
|
||||
</span>
|
||||
<span className="flex items-center gap-2">
|
||||
<FaServer className="text-ospab-primary" />
|
||||
Великий Новгород
|
||||
</span>
|
||||
<a
|
||||
href="https://github.com/ospab/ospabhost8.1"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-2 hover:text-ospab-primary transition-colors"
|
||||
title="Исходный код проекта"
|
||||
>
|
||||
<FaGithub className="text-ospab-primary" />
|
||||
GitHub
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-lg text-gray-700 leading-relaxed">
|
||||
В 13 лет я решил создать то, чего не было в моём городе — современный дата-центр.
|
||||
Начав с изучения технологий и работы над первым хостингом, я постепенно превращаю мечту
|
||||
в реальность. С помощью друга-инвестора мы строим инфраструктуру будущего для Великого Новгорода.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-ospab-primary/10 rounded-xl p-6 mt-8">
|
||||
<h3 className="text-2xl font-bold text-ospab-primary mb-2">Почему выбирают ospab.host?</h3>
|
||||
<ul className="list-disc list-inside text-lg text-gray-700 text-left mx-auto max-w-xl">
|
||||
<li>Первый ЦОД и крупный хостинг в Великом Новгороде</li>
|
||||
<li>Личная поддержка от основателя</li>
|
||||
<li>Современная инфраструктура и технологии</li>
|
||||
<li>Доступные тарифы для всех</li>
|
||||
<li>История, которой можно гордиться</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
{/* Story Section */}
|
||||
<section className="py-20 px-4">
|
||||
<div className="container mx-auto max-w-4xl">
|
||||
<h2 className="text-4xl md:text-5xl font-bold text-center text-gray-900 mb-12">
|
||||
Наша история
|
||||
</h2>
|
||||
|
||||
<div className="space-y-8">
|
||||
<div className="bg-gradient-to-r from-blue-50 to-white p-8 rounded-2xl border-l-4 border-ospab-primary shadow-lg">
|
||||
<h3 className="text-2xl font-bold text-gray-900 mb-4 flex items-center gap-3">
|
||||
<FaRocket className="text-ospab-primary" />
|
||||
Сентябрь 2025 — Начало пути
|
||||
</h3>
|
||||
<p className="text-lg text-gray-700 leading-relaxed">
|
||||
Всё началось с простой идеи: создать место, где любой сможет разместить свой проект,
|
||||
сайт или сервер с максимальной надёжностью и скоростью. Великий Новгород заслуживает
|
||||
свой дата-центр, и я решил взяться за эту задачу.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-gradient-to-r from-purple-50 to-white p-8 rounded-2xl border-l-4 border-ospab-accent shadow-lg">
|
||||
<h3 className="text-2xl font-bold text-gray-900 mb-4 flex items-center gap-3">
|
||||
<FaHeart className="text-ospab-accent" />
|
||||
Поддержка и развитие
|
||||
</h3>
|
||||
<p className="text-lg text-gray-700 leading-relaxed">
|
||||
Мой друг-инвестор поверил в проект и помогает с развитием инфраструктуры.
|
||||
Мы строим не просто бизнес, а сообщество, где каждый клиент — как друг,
|
||||
а поддержка всегда рядом.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-gradient-to-r from-green-50 to-white p-8 rounded-2xl border-l-4 border-green-500 shadow-lg">
|
||||
<h3 className="text-2xl font-bold text-gray-900 mb-4 flex items-center gap-3">
|
||||
<FaChartLine className="text-green-500" />
|
||||
Настоящее и будущее
|
||||
</h3>
|
||||
<p className="text-lg text-gray-700 leading-relaxed">
|
||||
Сейчас мы активно работаем над хостингом и подготовкой инфраструктуры для будущего ЦОД.
|
||||
ospab.host — это первый шаг к цифровому будущему Великого Новгорода, и мы только начинаем.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Mission Section */}
|
||||
<section className="py-20 px-4 bg-gray-50">
|
||||
<div className="container mx-auto max-w-6xl">
|
||||
<div className="text-center mb-16">
|
||||
<h2 className="text-4xl md:text-5xl font-bold text-gray-900 mb-6">
|
||||
Наша миссия
|
||||
</h2>
|
||||
<p className="text-xl text-gray-600 max-w-3xl mx-auto">
|
||||
Сделать качественный хостинг доступным для всех, а ЦОД — гордостью города
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-8">
|
||||
<div className="bg-white p-8 rounded-2xl shadow-xl hover:shadow-2xl transition-all duration-300 transform hover:-translate-y-2">
|
||||
<div className="w-16 h-16 bg-blue-100 rounded-2xl flex items-center justify-center mb-6">
|
||||
<FaServer className="text-3xl text-ospab-primary" />
|
||||
</div>
|
||||
<h3 className="text-2xl font-bold text-gray-900 mb-4">Современные технологии</h3>
|
||||
<p className="text-gray-600 leading-relaxed">
|
||||
Используем новейшее оборудование и программное обеспечение для максимальной производительности
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-8 rounded-2xl shadow-xl hover:shadow-2xl transition-all duration-300 transform hover:-translate-y-2">
|
||||
<div className="w-16 h-16 bg-pink-100 rounded-2xl flex items-center justify-center mb-6">
|
||||
<FaShieldAlt className="text-3xl text-ospab-accent" />
|
||||
</div>
|
||||
<h3 className="text-2xl font-bold text-gray-900 mb-4">Безопасность данных</h3>
|
||||
<p className="text-gray-600 leading-relaxed">
|
||||
Защита информации клиентов — наш приоритет. Регулярные бэкапы и мониторинг 24/7
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-8 rounded-2xl shadow-xl hover:shadow-2xl transition-all duration-300 transform hover:-translate-y-2">
|
||||
<div className="w-16 h-16 bg-green-100 rounded-2xl flex items-center justify-center mb-6">
|
||||
<FaUsers className="text-3xl text-green-500" />
|
||||
</div>
|
||||
<h3 className="text-2xl font-bold text-gray-900 mb-4">Личная поддержка</h3>
|
||||
<p className="text-gray-600 leading-relaxed">
|
||||
Каждый клиент получает персональное внимание и помощь от основателя
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Why Choose Us Section */}
|
||||
<section className="py-20 px-4">
|
||||
<div className="container mx-auto max-w-6xl">
|
||||
<div className="bg-gradient-to-br from-ospab-primary to-blue-700 rounded-3xl shadow-2xl p-12 md:p-16 text-white">
|
||||
<h2 className="text-4xl md:text-5xl font-bold text-center mb-12">
|
||||
Почему выбирают ospab.host?
|
||||
</h2>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 max-w-4xl mx-auto">
|
||||
<div className="flex items-start gap-4 bg-white/10 backdrop-blur-sm p-6 rounded-xl">
|
||||
<div className="flex-shrink-0 w-8 h-8 bg-white/20 rounded-full flex items-center justify-center">
|
||||
<span className="text-white font-bold">✓</span>
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-bold text-lg mb-2">Первый ЦОД в городе</h4>
|
||||
<p className="text-blue-100">Мы создаём историю Великого Новгорода</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-4 bg-white/10 backdrop-blur-sm p-6 rounded-xl">
|
||||
<div className="flex-shrink-0 w-8 h-8 bg-white/20 rounded-full flex items-center justify-center">
|
||||
<span className="text-white font-bold">✓</span>
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-bold text-lg mb-2">Доступные тарифы</h4>
|
||||
<p className="text-blue-100">Качественный хостинг для всех без переплат</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-4 bg-white/10 backdrop-blur-sm p-6 rounded-xl">
|
||||
<div className="flex-shrink-0 w-8 h-8 bg-white/20 rounded-full flex items-center justify-center">
|
||||
<span className="text-white font-bold">✓</span>
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-bold text-lg mb-2">Быстрая поддержка</h4>
|
||||
<p className="text-blue-100">Ответим на вопросы в любое время</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-4 bg-white/10 backdrop-blur-sm p-6 rounded-xl">
|
||||
<div className="flex-shrink-0 w-8 h-8 bg-white/20 rounded-full flex items-center justify-center">
|
||||
<span className="text-white font-bold">✓</span>
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-bold text-lg mb-2">Прозрачность</h4>
|
||||
<p className="text-blue-100">Честно о возможностях и ограничениях</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-4 bg-white/10 backdrop-blur-sm p-6 rounded-xl">
|
||||
<div className="flex-shrink-0 w-8 h-8 bg-white/20 rounded-full flex items-center justify-center">
|
||||
<span className="text-white font-bold">✓</span>
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-bold text-lg mb-2">Современная инфраструктура</h4>
|
||||
<p className="text-blue-100">Актуальное ПО и оборудование</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-4 bg-white/10 backdrop-blur-sm p-6 rounded-xl">
|
||||
<div className="flex-shrink-0 w-8 h-8 bg-white/20 rounded-full flex items-center justify-center">
|
||||
<span className="text-white font-bold">✓</span>
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-bold text-lg mb-2">Мечта становится реальностью</h4>
|
||||
<p className="text-blue-100">История, которой можно гордиться</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-4 bg-white/10 backdrop-blur-sm p-6 rounded-xl">
|
||||
<div className="flex-shrink-0 w-8 h-8 bg-white/20 rounded-full flex items-center justify-center">
|
||||
<FaGithub className="text-white text-lg" />
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-bold text-lg mb-2">Open Source</h4>
|
||||
<p className="text-blue-100">
|
||||
<a
|
||||
href="https://github.com/ospab/ospabhost8.1"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="hover:underline"
|
||||
>
|
||||
Исходный код на GitHub
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* CTA Section */}
|
||||
<section className="py-20 px-4 bg-gray-50">
|
||||
<div className="container mx-auto max-w-4xl text-center">
|
||||
<h2 className="text-4xl md:text-5xl font-bold text-gray-900 mb-6">
|
||||
Станьте частью истории
|
||||
</h2>
|
||||
<p className="text-xl text-gray-600 mb-10">
|
||||
Присоединяйтесь к ospab.host и помогите создать цифровое будущее Великого Новгорода
|
||||
</p>
|
||||
<div className="flex flex-col sm:flex-row gap-4 justify-center">
|
||||
<a
|
||||
href="/register"
|
||||
className="px-8 py-4 bg-ospab-primary hover:bg-blue-700 text-white font-bold text-lg rounded-full transition-all transform hover:scale-105 shadow-lg"
|
||||
>
|
||||
Начать бесплатно
|
||||
</a>
|
||||
<a
|
||||
href="/tariffs"
|
||||
className="px-8 py-4 bg-white hover:bg-gray-50 text-ospab-primary font-bold text-lg rounded-full border-2 border-ospab-primary transition-all transform hover:scale-105 shadow-lg"
|
||||
>
|
||||
Посмотреть тарифы
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
144
ospabhost/frontend/src/pages/blog.tsx
Normal file
144
ospabhost/frontend/src/pages/blog.tsx
Normal file
@@ -0,0 +1,144 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import axios from 'axios';
|
||||
import { API_URL } from '../config/api';
|
||||
|
||||
interface Post {
|
||||
id: number;
|
||||
title: string;
|
||||
excerpt: string;
|
||||
coverImage: string | null;
|
||||
url: string;
|
||||
views: number;
|
||||
createdAt: string;
|
||||
publishedAt: string;
|
||||
author: {
|
||||
id: number;
|
||||
username: string;
|
||||
};
|
||||
_count: {
|
||||
comments: number;
|
||||
};
|
||||
}
|
||||
|
||||
const Blog: React.FC = () => {
|
||||
const [posts, setPosts] = useState<Post[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
loadPosts();
|
||||
}, []);
|
||||
|
||||
const loadPosts = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await axios.get(`${API_URL}/api/blog/posts`);
|
||||
setPosts(response.data.data);
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
console.error('Ошибка загрузки постов:', err);
|
||||
setError('Не удалось загрузить статьи');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const formatDate = (dateString: string) => {
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleDateString('ru-RU', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric'
|
||||
});
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
|
||||
<div className="text-xl text-gray-600">Загрузка...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 py-12">
|
||||
<div className="container mx-auto px-4 max-w-6xl">
|
||||
{/* Header */}
|
||||
<div className="text-center mb-12">
|
||||
<h1 className="text-5xl font-bold text-gray-900 mb-4">Блог</h1>
|
||||
<p className="text-xl text-gray-600">
|
||||
Новости, статьи и полезные материалы о хостинге
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-8 text-center">
|
||||
<p className="text-red-800">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Posts Grid */}
|
||||
{posts.length === 0 ? (
|
||||
<div className="text-center py-12">
|
||||
<p className="text-2xl text-gray-400">📭 Статей пока нет</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
|
||||
{posts.map((post) => (
|
||||
<Link
|
||||
key={post.id}
|
||||
to={`/blog/${post.url}`}
|
||||
className="bg-white rounded-lg shadow-md hover:shadow-xl transition-shadow overflow-hidden group"
|
||||
>
|
||||
{/* Cover Image */}
|
||||
{post.coverImage ? (
|
||||
<div className="h-48 bg-gray-200 overflow-hidden">
|
||||
<img
|
||||
src={post.coverImage}
|
||||
alt={post.title}
|
||||
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-48 bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center">
|
||||
<span className="text-4xl text-white font-bold">Статья</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Content */}
|
||||
<div className="p-6">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-3 group-hover:text-blue-600 transition-colors line-clamp-2">
|
||||
{post.title}
|
||||
</h2>
|
||||
|
||||
{post.excerpt && (
|
||||
<p className="text-gray-600 mb-4 line-clamp-3">
|
||||
{post.excerpt}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Meta */}
|
||||
<div className="flex items-center justify-between text-sm text-gray-500">
|
||||
<div className="flex items-center gap-4">
|
||||
<span>Автор: {post.author.username}</span>
|
||||
<span>Просмотров: {post.views}</span>
|
||||
<span>Комментариев: {post._count.comments}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-3 text-sm text-gray-400">
|
||||
{formatDate(post.publishedAt || post.createdAt)}
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Blog;
|
||||
278
ospabhost/frontend/src/pages/blogpost.tsx
Normal file
278
ospabhost/frontend/src/pages/blogpost.tsx
Normal file
@@ -0,0 +1,278 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { useParams, useNavigate } from 'react-router-dom';
|
||||
import axios from 'axios';
|
||||
import { API_URL } from '../config/api';
|
||||
import { useToast } from '../hooks/useToast';
|
||||
import useAuth from '../context/useAuth';
|
||||
|
||||
interface Comment {
|
||||
id: number;
|
||||
content: string;
|
||||
authorName: string | null;
|
||||
createdAt: string;
|
||||
user: {
|
||||
id: number;
|
||||
username: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
interface Post {
|
||||
id: number;
|
||||
title: string;
|
||||
content: string;
|
||||
coverImage: string | null;
|
||||
url: string;
|
||||
views: number;
|
||||
createdAt: string;
|
||||
publishedAt: string;
|
||||
author: {
|
||||
id: number;
|
||||
username: string;
|
||||
};
|
||||
comments: Comment[];
|
||||
}
|
||||
|
||||
const BlogPost: React.FC = () => {
|
||||
const { url } = useParams<{ url: string }>();
|
||||
const navigate = useNavigate();
|
||||
const { addToast } = useToast();
|
||||
const { isLoggedIn } = useAuth();
|
||||
|
||||
const [post, setPost] = useState<Post | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const [commentContent, setCommentContent] = useState('');
|
||||
const [commentAuthorName, setCommentAuthorName] = useState('');
|
||||
const [submittingComment, setSubmittingComment] = useState(false);
|
||||
|
||||
const loadPost = React.useCallback(async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await axios.get(`${API_URL}/api/blog/posts/${url}`);
|
||||
setPost(response.data.data);
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
console.error('Ошибка загрузки поста:', err);
|
||||
if (err && typeof err === 'object' && 'response' in err) {
|
||||
const axiosError = err as { response?: { status?: number } };
|
||||
if (axiosError.response?.status === 404) {
|
||||
setError('Статья не найдена');
|
||||
} else {
|
||||
setError('Не удалось загрузить статью');
|
||||
}
|
||||
} else {
|
||||
setError('Не удалось загрузить статью');
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [url]);
|
||||
|
||||
useEffect(() => {
|
||||
if (url) {
|
||||
loadPost();
|
||||
}
|
||||
}, [url, loadPost]);
|
||||
|
||||
const handleSubmitComment = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!commentContent.trim()) {
|
||||
addToast('Введите комментарий', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isLoggedIn && !commentAuthorName.trim()) {
|
||||
addToast('Укажите ваше имя', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setSubmittingComment(true);
|
||||
|
||||
// Подготовка заголовков с токеном для авторизованных пользователей
|
||||
const headers: Record<string, string> = {};
|
||||
if (isLoggedIn) {
|
||||
const token = localStorage.getItem('access_token');
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
}
|
||||
|
||||
await axios.post(`${API_URL}/api/blog/posts/${post?.id}/comments`, {
|
||||
content: commentContent,
|
||||
authorName: !isLoggedIn ? commentAuthorName : null
|
||||
}, { headers });
|
||||
|
||||
addToast('Комментарий отправлен на модерацию', 'success');
|
||||
setCommentContent('');
|
||||
setCommentAuthorName('');
|
||||
loadPost(); // Перезагрузить пост с комментариями
|
||||
} catch (err) {
|
||||
console.error('Ошибка отправки комментария:', err);
|
||||
addToast('Не удалось отправить комментарий', 'error');
|
||||
} finally {
|
||||
setSubmittingComment(false);
|
||||
}
|
||||
};
|
||||
|
||||
const formatDate = (dateString: string) => {
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleDateString('ru-RU', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
|
||||
<div className="text-xl text-gray-600">Загрузка...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error || !post) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<p className="text-2xl text-red-600 mb-4">{error}</p>
|
||||
<button
|
||||
onClick={() => navigate('/blog')}
|
||||
className="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
|
||||
>
|
||||
Вернуться к блогу
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 py-12">
|
||||
<div className="container mx-auto px-4 max-w-4xl">
|
||||
{/* Back Button */}
|
||||
<button
|
||||
onClick={() => navigate('/blog')}
|
||||
className="mb-6 flex items-center gap-2 text-blue-600 hover:text-blue-800 transition-colors"
|
||||
>
|
||||
<span>←</span> Вернуться к блогу
|
||||
</button>
|
||||
|
||||
{/* Cover Image */}
|
||||
{post.coverImage && (
|
||||
<div className="mb-8 rounded-lg overflow-hidden shadow-lg">
|
||||
<img
|
||||
src={post.coverImage}
|
||||
alt={post.title}
|
||||
className="w-full h-96 object-cover"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Article */}
|
||||
<article className="bg-white rounded-lg shadow-lg p-8 md:p-12 mb-8">
|
||||
{/* Title */}
|
||||
<h1 className="text-4xl md:text-5xl font-bold text-gray-900 mb-4">
|
||||
{post.title}
|
||||
</h1>
|
||||
|
||||
{/* Meta */}
|
||||
<div className="flex items-center gap-6 text-gray-500 mb-8 pb-6 border-b">
|
||||
<div className="flex items-center gap-2">
|
||||
<span>Автор:</span>
|
||||
<span>{post.author.username}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span>Дата:</span>
|
||||
<span>{formatDate(post.publishedAt || post.createdAt)}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span>Просмотров:</span>
|
||||
<span>{post.views}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content (HTML) */}
|
||||
<div
|
||||
className="prose prose-lg max-w-none"
|
||||
dangerouslySetInnerHTML={{ __html: post.content }}
|
||||
/>
|
||||
</article>
|
||||
|
||||
{/* Comments Section */}
|
||||
<div className="bg-white rounded-lg shadow-lg p-8 md:p-12">
|
||||
<h2 className="text-3xl font-bold text-gray-900 mb-6">
|
||||
Комментарии ({post.comments.length})
|
||||
</h2>
|
||||
|
||||
{/* Comment Form */}
|
||||
<form onSubmit={handleSubmitComment} className="mb-8 p-6 bg-gray-50 rounded-lg">
|
||||
<h3 className="text-xl font-semibold mb-4">Оставить комментарий</h3>
|
||||
|
||||
{!isLoggedIn && (
|
||||
<input
|
||||
type="text"
|
||||
value={commentAuthorName}
|
||||
onChange={(e) => setCommentAuthorName(e.target.value)}
|
||||
placeholder="Ваше имя"
|
||||
className="w-full px-4 py-2 border border-gray-300 rounded-lg mb-4 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
required
|
||||
/>
|
||||
)}
|
||||
|
||||
<textarea
|
||||
value={commentContent}
|
||||
onChange={(e) => setCommentContent(e.target.value)}
|
||||
placeholder="Напишите ваш комментарий..."
|
||||
rows={4}
|
||||
className="w-full px-4 py-2 border border-gray-300 rounded-lg mb-4 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
required
|
||||
/>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={submittingComment}
|
||||
className="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
{submittingComment ? 'Отправка...' : 'Отправить комментарий'}
|
||||
</button>
|
||||
|
||||
<p className="mt-2 text-sm text-gray-500">
|
||||
Комментарии проходят модерацию перед публикацией
|
||||
</p>
|
||||
</form>
|
||||
|
||||
{/* Comments List */}
|
||||
{post.comments.length === 0 ? (
|
||||
<p className="text-center text-gray-400 py-8">
|
||||
Пока нет комментариев. Будьте первым!
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-6">
|
||||
{post.comments.map((comment) => (
|
||||
<div key={comment.id} className="p-4 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<span className="font-semibold text-gray-900">
|
||||
{comment.user ? comment.user.username : comment.authorName}
|
||||
</span>
|
||||
<span className="text-sm text-gray-500">
|
||||
• {formatDate(comment.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-gray-700 whitespace-pre-wrap">{comment.content}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default BlogPost;
|
||||
@@ -1,9 +1,32 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import axios from 'axios';
|
||||
import { API_URL } from '../../config/api';
|
||||
import { useToast } from '../../components/Toast';
|
||||
import { useToast } from '../../hooks/useToast';
|
||||
import { showConfirm, showPrompt } from '../../components/modalHelpers';
|
||||
|
||||
interface Server {
|
||||
id: number;
|
||||
name: string;
|
||||
status: string;
|
||||
vmid: number;
|
||||
ipAddress: string | null;
|
||||
nextPaymentDate: string | null;
|
||||
tariff: {
|
||||
name: string;
|
||||
};
|
||||
os: {
|
||||
name: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface Transaction {
|
||||
id: number;
|
||||
type: string;
|
||||
amount: number;
|
||||
description: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface User {
|
||||
id: number;
|
||||
username: string;
|
||||
@@ -18,22 +41,28 @@ interface User {
|
||||
};
|
||||
}
|
||||
|
||||
interface UserDetails extends User {
|
||||
servers: Server[];
|
||||
transactions: Transaction[];
|
||||
}
|
||||
|
||||
interface Statistics {
|
||||
users: { total: number };
|
||||
servers: { total: number; active: number; suspended: number };
|
||||
balance: { total: number };
|
||||
checks: { pending: number };
|
||||
tickets: { open: number };
|
||||
recentTransactions: any[];
|
||||
recentTransactions: Transaction[];
|
||||
}
|
||||
|
||||
const AdminPanel = () => {
|
||||
const { addToast } = useToast();
|
||||
const [users, setUsers] = useState<User[]>([]);
|
||||
const [statistics, setStatistics] = useState<Statistics | null>(null);
|
||||
const [selectedUser, setSelectedUser] = useState<any>(null);
|
||||
const [selectedUser, setSelectedUser] = useState<UserDetails | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [activeTab, setActiveTab] = useState<'users' | 'stats'>('stats');
|
||||
const [testingPush, setTestingPush] = useState(false);
|
||||
|
||||
// Модальные окна
|
||||
const [showBalanceModal, setShowBalanceModal] = useState(false);
|
||||
@@ -54,10 +83,13 @@ const AdminPanel = () => {
|
||||
|
||||
setUsers(usersRes.data.data);
|
||||
setStatistics(statsRes.data.data);
|
||||
} catch (error: any) {
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки данных админки:', error);
|
||||
if (error.response?.status === 403) {
|
||||
addToast('У вас нет прав администратора', 'error');
|
||||
if (error && typeof error === 'object' && 'response' in error) {
|
||||
const axiosError = error as { response?: { status?: number } };
|
||||
if (axiosError.response?.status === 403) {
|
||||
addToast('У вас нет прав администратора', 'error');
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
@@ -148,6 +180,140 @@ const AdminPanel = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleTestPushNotification = async () => {
|
||||
console.log('🧪 [FRONTEND] Начинаем тестовую отправку Push-уведомления...');
|
||||
setTestingPush(true);
|
||||
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
console.log('📝 [FRONTEND] Токен найден:', token ? 'Да' : 'Нет');
|
||||
|
||||
if (!token) {
|
||||
addToast('Токен не найден. Пожалуйста, войдите снова.', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
// Проверяем разрешения
|
||||
console.log('🔍 [FRONTEND] Проверяем разрешения на уведомления...');
|
||||
console.log(' Notification.permission:', Notification.permission);
|
||||
|
||||
if (Notification.permission !== 'granted') {
|
||||
addToast('⚠️ Уведомления не разрешены! Включите их на странице "Уведомления"', 'error');
|
||||
console.log('❌ [FRONTEND] Уведомления не разрешены');
|
||||
return;
|
||||
}
|
||||
|
||||
// Проверяем Service Worker
|
||||
console.log('🔍 [FRONTEND] Проверяем Service Worker...');
|
||||
const registration = await navigator.serviceWorker.ready;
|
||||
console.log(' ✅ Service Worker готов:', registration);
|
||||
|
||||
// Проверяем Push подписку
|
||||
console.log('🔍 [FRONTEND] Проверяем Push подписку...');
|
||||
const subscription = await registration.pushManager.getSubscription();
|
||||
if (subscription) {
|
||||
console.log(' ✅ Push подписка найдена:', subscription.endpoint.substring(0, 50) + '...');
|
||||
} else {
|
||||
console.log(' ❌ Push подписка НЕ найдена');
|
||||
addToast('❌ Push подписка не найдена! Включите уведомления заново.', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
|
||||
console.log('📤 [FRONTEND] Отправляем запрос на:', `${API_URL}/api/notifications/test-push`);
|
||||
|
||||
const response = await axios.post(
|
||||
`${API_URL}/api/notifications/test-push`,
|
||||
{},
|
||||
{ headers }
|
||||
);
|
||||
|
||||
console.log('✅ [FRONTEND] Ответ от сервера:', response.data);
|
||||
|
||||
if (response.data.success) {
|
||||
addToast('✅ Тестовое уведомление отправлено! Ждите системное уведомление в углу экрана.', 'success');
|
||||
|
||||
console.log('💡 [FRONTEND] ВАЖНО: Уведомление должно появиться как СИСТЕМНОЕ уведомление');
|
||||
console.log(' Windows: правый нижний угол экрана (Action Center)');
|
||||
console.log(' macOS: правый верхний угол');
|
||||
console.log(' Это НЕ уведомление на сайте, а уведомление браузера/ОС!');
|
||||
|
||||
|
||||
if (response.data.data) {
|
||||
console.log('📊 [FRONTEND] Детали:', {
|
||||
notificationId: response.data.data.notificationId,
|
||||
subscriptionsCount: response.data.data.subscriptionsCount
|
||||
});
|
||||
}
|
||||
} else {
|
||||
addToast(`❌ ${response.data.message}`, 'error');
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ [FRONTEND] Ошибка отправки тестового уведомления:', error);
|
||||
|
||||
if (axios.isAxiosError(error)) {
|
||||
console.error('📋 [FRONTEND] Детали ошибки Axios:', {
|
||||
status: error.response?.status,
|
||||
statusText: error.response?.statusText,
|
||||
data: error.response?.data,
|
||||
url: error.config?.url
|
||||
});
|
||||
|
||||
const errorMessage = error.response?.data?.message || error.message;
|
||||
addToast(`Ошибка: ${errorMessage}`, 'error');
|
||||
|
||||
if (error.response?.status === 403) {
|
||||
console.log('⚠️ [FRONTEND] 403 Forbidden - проверьте права администратора');
|
||||
} else if (error.response?.status === 400) {
|
||||
console.log('⚠️ [FRONTEND] 400 Bad Request - возможно, нет активных подписок');
|
||||
}
|
||||
} else {
|
||||
addToast('Ошибка отправки тестового уведомления', 'error');
|
||||
}
|
||||
} finally {
|
||||
setTestingPush(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleTestLocalNotification = () => {
|
||||
console.log('🔔 [FRONTEND] Тестируем локальное уведомление (без сервера)...');
|
||||
|
||||
if (Notification.permission !== 'granted') {
|
||||
addToast('⚠️ Уведомления не разрешены!', 'error');
|
||||
console.log('❌ [FRONTEND] Notification.permission:', Notification.permission);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const notification = new Notification('🔔 Локальный тест', {
|
||||
body: 'Если вы видите это уведомление, значит браузер и ОС настроены правильно!',
|
||||
icon: '/logo192.png',
|
||||
badge: '/favicon.svg',
|
||||
tag: 'local-test',
|
||||
requireInteraction: false
|
||||
});
|
||||
|
||||
console.log('✅ [FRONTEND] Локальное уведомление создано:', notification);
|
||||
addToast('✅ Локальное уведомление отправлено!', 'success');
|
||||
|
||||
notification.onclick = () => {
|
||||
console.log('🖱️ [FRONTEND] Клик по локальному уведомлению');
|
||||
window.focus();
|
||||
notification.close();
|
||||
};
|
||||
|
||||
setTimeout(() => {
|
||||
notification.close();
|
||||
}, 5000);
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ [FRONTEND] Ошибка локального уведомления:', error);
|
||||
addToast('Ошибка создания уведомления', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex justify-center items-center h-screen">
|
||||
@@ -158,7 +324,40 @@ const AdminPanel = () => {
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<h1 className="text-3xl font-bold mb-8">Админ-панель</h1>
|
||||
<div className="flex justify-between items-center mb-8">
|
||||
<h1 className="text-3xl font-bold">Админ-панель</h1>
|
||||
|
||||
{/* Кнопки тестовых уведомлений */}
|
||||
<div className="flex gap-3">
|
||||
<button
|
||||
onClick={handleTestLocalNotification}
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2 transition-all"
|
||||
title="Локальный тест (без сервера) - должно появиться сразу в углу экрана"
|
||||
>
|
||||
<span className="text-xl">🔔</span>
|
||||
<span>Локальный тест</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={handleTestPushNotification}
|
||||
disabled={testingPush}
|
||||
className="px-6 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center gap-2 transition-all"
|
||||
title="Push-уведомление через сервер - требует подписку"
|
||||
>
|
||||
{testingPush ? (
|
||||
<>
|
||||
<div className="animate-spin h-5 w-5 border-2 border-white border-t-transparent rounded-full"></div>
|
||||
<span>Отправка...</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-xl">🧪</span>
|
||||
<span>Тест Push</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="flex gap-4 mb-6 border-b">
|
||||
@@ -229,7 +428,9 @@ const AdminPanel = () => {
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium">{user.balance.toFixed(2)} ₽</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm">{user._count.servers}</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm">
|
||||
{user.isAdmin ? '✅' : '❌'}
|
||||
<span className={user.isAdmin ? 'text-green-600 font-medium' : 'text-gray-400'}>
|
||||
{user.isAdmin ? 'Да' : 'Нет'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm space-x-2">
|
||||
<button
|
||||
@@ -297,7 +498,7 @@ const AdminPanel = () => {
|
||||
{/* Servers */}
|
||||
<h3 className="text-xl font-bold mb-4">Серверы ({selectedUser.servers.length})</h3>
|
||||
<div className="space-y-4 mb-6">
|
||||
{selectedUser.servers.map((server: any) => (
|
||||
{selectedUser.servers.map((server) => (
|
||||
<div key={server.id} className="border p-4 rounded">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
@@ -326,7 +527,7 @@ const AdminPanel = () => {
|
||||
{/* Transactions */}
|
||||
<h3 className="text-xl font-bold mb-4">Последние транзакции</h3>
|
||||
<div className="space-y-2">
|
||||
{selectedUser.transactions?.slice(0, 10).map((tx: any) => (
|
||||
{selectedUser.transactions?.slice(0, 10).map((tx) => (
|
||||
<div key={tx.id} className="flex justify-between border-b pb-2">
|
||||
<div>
|
||||
<p className="font-medium">{tx.description}</p>
|
||||
|
||||
@@ -1,139 +1,383 @@
|
||||
// 3. Исправляем frontend/src/pages/dashboard/billing.tsx
|
||||
|
||||
import { useState } from 'react';
|
||||
import axios from 'axios';
|
||||
import { useState, useEffect } from 'react';
|
||||
import apiClient from '../../utils/apiClient';
|
||||
import QRCode from 'react-qr-code';
|
||||
import { API_URL } from '../../config/api';
|
||||
|
||||
const sbpUrl = import.meta.env.VITE_SBP_QR_URL;
|
||||
const cardNumber = import.meta.env.VITE_CARD_NUMBER;
|
||||
|
||||
interface Check {
|
||||
id: number;
|
||||
amount: number;
|
||||
status: 'pending' | 'approved' | 'rejected';
|
||||
fileUrl: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
const Billing = () => {
|
||||
const [amount, setAmount] = useState(0);
|
||||
const [isPaymentGenerated, setIsPaymentGenerated] = useState(false);
|
||||
const [copyStatus, setCopyStatus] = useState('');
|
||||
const [amount, setAmount] = useState<number>(0);
|
||||
const [balance, setBalance] = useState<number>(0);
|
||||
const [checks, setChecks] = useState<Check[]>([]);
|
||||
const [checkFile, setCheckFile] = useState<File | null>(null);
|
||||
const [checkStatus, setCheckStatus] = useState('');
|
||||
const [uploadLoading, setUploadLoading] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [messageType, setMessageType] = useState<'success' | 'error'>('success');
|
||||
const [isPaymentGenerated, setIsPaymentGenerated] = useState(false);
|
||||
|
||||
const handleGeneratePayment = () => {
|
||||
if (amount > 0) setIsPaymentGenerated(true);
|
||||
const quickAmounts = [100, 500, 1000, 3000, 5000];
|
||||
|
||||
useEffect(() => {
|
||||
fetchBalance();
|
||||
fetchChecks();
|
||||
}, []);
|
||||
|
||||
// Получить защищённый URL для файла чека
|
||||
const getCheckFileUrl = (fileUrl: string): string => {
|
||||
const filename = fileUrl.split('/').pop();
|
||||
return `${API_URL}/api/check/file/${filename}`;
|
||||
};
|
||||
|
||||
const fetchBalance = async () => {
|
||||
try {
|
||||
console.log('[Billing] Загрузка баланса...');
|
||||
const res = await apiClient.get(`${API_URL}/api/user/balance`);
|
||||
console.log('[Billing] Ответ от сервера:', res.data);
|
||||
const balanceValue = res.data.balance || 0;
|
||||
setBalance(balanceValue);
|
||||
console.log('[Billing] Баланс загружен:', balanceValue);
|
||||
} catch (error) {
|
||||
console.error('[Billing] Ошибка загрузки баланса:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const fetchChecks = async () => {
|
||||
try {
|
||||
console.log('[Billing] Загрузка истории чеков...');
|
||||
const res = await apiClient.get(`${API_URL}/api/check/my`);
|
||||
const checksData = res.data.data || [];
|
||||
setChecks(checksData);
|
||||
console.log('[Billing] История чеков загружена:', checksData.length, 'чеков');
|
||||
} catch (error) {
|
||||
console.error('[Billing] Ошибка загрузки истории чеков:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const showMessage = (msg: string, type: 'success' | 'error' = 'success') => {
|
||||
setMessage(msg);
|
||||
setMessageType(type);
|
||||
setTimeout(() => setMessage(''), 5000);
|
||||
};
|
||||
|
||||
const handleCopyCard = () => {
|
||||
if (cardNumber) {
|
||||
navigator.clipboard.writeText(cardNumber);
|
||||
setCopyStatus('Скопировано!');
|
||||
setTimeout(() => setCopyStatus(''), 2000);
|
||||
showMessage('Номер карты скопирован!', 'success');
|
||||
}
|
||||
};
|
||||
|
||||
const handleGeneratePayment = () => {
|
||||
if (amount > 0) {
|
||||
setIsPaymentGenerated(true);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCheckUpload = async () => {
|
||||
if (!checkFile || amount <= 0) return;
|
||||
if (!checkFile || amount <= 0) {
|
||||
console.error('[Billing] Ошибка валидации:', { checkFile: !!checkFile, amount });
|
||||
showMessage('Укажите сумму и выберите файл', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[Billing] Начало загрузки чека:', {
|
||||
fileName: checkFile.name,
|
||||
fileSize: checkFile.size,
|
||||
amount
|
||||
});
|
||||
|
||||
setUploadLoading(true);
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const formData = new FormData();
|
||||
formData.append('file', checkFile);
|
||||
formData.append('amount', String(amount));
|
||||
const response = await axios.post('https://ospab.host:5000/api/check/upload', formData, {
|
||||
|
||||
console.log('[Billing] Отправка запроса на /api/check/upload...');
|
||||
const response = await apiClient.post(`${API_URL}/api/check/upload`, formData, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
// 'Content-Type' не указываем вручную для FormData!
|
||||
'Content-Type': 'multipart/form-data',
|
||||
},
|
||||
withCredentials: true,
|
||||
});
|
||||
setCheckStatus('Чек успешно загружен! Ожидайте проверки.');
|
||||
|
||||
console.log('[Billing] ✅ Чек успешно загружен:', response.data);
|
||||
showMessage('✅ Чек успешно отправлен! Ожидайте проверки оператором (обычно до 24 часов)', 'success');
|
||||
|
||||
setCheckFile(null);
|
||||
console.log('Чек успешно загружен:', response.data);
|
||||
setAmount(0);
|
||||
setIsPaymentGenerated(false);
|
||||
|
||||
// Обновляем список чеков
|
||||
await fetchChecks();
|
||||
console.log('[Billing] История чеков обновлена');
|
||||
} catch (error) {
|
||||
setCheckStatus('Ошибка загрузки чека.');
|
||||
console.error('Ошибка загрузки чека:', error);
|
||||
const err = error as { response?: { data?: { error?: string; message?: string }; status?: number }; message?: string };
|
||||
console.error('[Billing] Ошибка загрузки чека:', {
|
||||
message: err.message,
|
||||
response: err.response?.data,
|
||||
status: err.response?.status,
|
||||
});
|
||||
|
||||
const errorMessage = err.response?.data?.error ||
|
||||
err.response?.data?.message ||
|
||||
'Ошибка загрузки чека. Попробуйте снова';
|
||||
showMessage(`${errorMessage}`, 'error');
|
||||
}
|
||||
setUploadLoading(false);
|
||||
};
|
||||
|
||||
const getStatusText = (status: string) => {
|
||||
switch (status) {
|
||||
case 'approved':
|
||||
return 'Зачислено';
|
||||
case 'rejected':
|
||||
return 'Отклонено';
|
||||
default:
|
||||
return 'На проверке';
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusColor = (status: string) => {
|
||||
switch (status) {
|
||||
case 'approved':
|
||||
return 'text-green-600';
|
||||
case 'rejected':
|
||||
return 'text-red-600';
|
||||
default:
|
||||
return 'text-yellow-600';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-4 lg:p-8 bg-white rounded-2xl lg:rounded-3xl shadow-xl max-w-2xl mx-auto">
|
||||
<div className="p-4 lg:p-8 bg-white rounded-2xl lg:rounded-3xl shadow-xl max-w-4xl mx-auto">
|
||||
<h2 className="text-2xl lg:text-3xl font-bold text-gray-800 mb-4 lg:mb-6">Пополнение баланса</h2>
|
||||
{/* Только QR-код и карта, без реквизитов */}
|
||||
|
||||
{/* Сообщение */}
|
||||
{message && (
|
||||
<div className={`mb-4 p-3 border rounded-xl text-sm font-medium ${
|
||||
messageType === 'success'
|
||||
? 'bg-green-50 border-green-200 text-green-700'
|
||||
: 'bg-red-50 border-red-200 text-red-700'
|
||||
}`}>
|
||||
{message}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Текущий баланс */}
|
||||
<div className="bg-gray-100 p-4 lg:p-6 rounded-xl lg:rounded-2xl mb-6">
|
||||
<p className="text-sm text-gray-600 mb-1">Текущий баланс</p>
|
||||
<p className="text-3xl lg:text-4xl font-extrabold text-ospab-primary">{balance.toFixed(2)} ₽</p>
|
||||
</div>
|
||||
|
||||
{!isPaymentGenerated ? (
|
||||
<div>
|
||||
<p className="text-base lg:text-lg text-gray-500 mb-4">
|
||||
Пополните свой баланс, чтобы оплачивать услуги. Минимальная сумма пополнения: 1 руб.
|
||||
</p>
|
||||
{/* Ввод суммы */}
|
||||
<div className="mb-4">
|
||||
<label htmlFor="amount" className="block text-gray-700 font-medium mb-2">Сумма (₽)</label>
|
||||
<label htmlFor="amount" className="block text-gray-700 font-semibold mb-2">
|
||||
Сумма пополнения (₽)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
id="amount"
|
||||
value={amount}
|
||||
value={amount || ''}
|
||||
onChange={(e) => setAmount(Number(e.target.value))}
|
||||
className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-ospab-primary"
|
||||
min="1"
|
||||
placeholder="Введите сумму"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Быстрые суммы */}
|
||||
<div className="mb-6">
|
||||
<p className="text-sm text-gray-600 mb-2">Быстрый выбор:</p>
|
||||
<div className="grid grid-cols-3 md:grid-cols-5 gap-2">
|
||||
{quickAmounts.map((quickAmount) => (
|
||||
<button
|
||||
key={quickAmount}
|
||||
onClick={() => setAmount(quickAmount)}
|
||||
className={`px-3 py-2 rounded-lg text-sm font-medium transition ${
|
||||
amount === quickAmount
|
||||
? 'bg-ospab-primary text-white'
|
||||
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
|
||||
}`}
|
||||
>
|
||||
{quickAmount} ₽
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleGeneratePayment}
|
||||
className="w-full px-5 py-3 rounded-full text-white font-bold transition-colors transform hover:scale-105 bg-ospab-primary hover:bg-ospab-accent"
|
||||
disabled={amount <= 0}
|
||||
className="w-full px-5 py-3 rounded-xl text-white font-bold transition-colors bg-ospab-primary hover:bg-ospab-accent disabled:bg-gray-300 disabled:cursor-not-allowed"
|
||||
>
|
||||
Сгенерировать платеж
|
||||
Перейти к оплате
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center">
|
||||
<div>
|
||||
<p className="text-base lg:text-lg text-gray-700 mb-4">
|
||||
Для пополнения баланса переведите <strong>₽{amount}</strong>.
|
||||
</p>
|
||||
<p className="text-sm text-gray-500 mb-6">
|
||||
Ваш заказ будет обработан вручную после проверки чека.
|
||||
</p>
|
||||
<div>
|
||||
{/* Инструкция */}
|
||||
<div className="bg-blue-50 border border-blue-200 rounded-xl p-4 mb-6">
|
||||
<p className="font-bold text-blue-800 mb-2">Инструкция по оплате</p>
|
||||
<ol className="text-sm text-blue-700 space-y-1 list-decimal list-inside">
|
||||
<li>Переведите <strong>₽{amount}</strong> по СБП или на карту</li>
|
||||
<li>Сохраните чек об оплате</li>
|
||||
<li>Загрузите чек ниже для проверки</li>
|
||||
</ol>
|
||||
</div>
|
||||
{/* QR-код для оплаты по СБП */}
|
||||
<div className="bg-gray-100 p-4 lg:p-6 rounded-xl lg:rounded-2xl inline-block mb-6 w-full max-w-md mx-auto">
|
||||
<h3 className="text-lg lg:text-xl font-bold text-gray-800 mb-2">Оплата по СБП</h3>
|
||||
<div className="flex justify-center p-4 bg-white rounded-lg">
|
||||
<QRCode value={sbpUrl || 'https://qr.nspk.ru/FAKE-QR-LINK'} size={Math.min(window.innerWidth - 100, 256)} />
|
||||
|
||||
{/* QR-код и карта */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
|
||||
{/* QR СБП */}
|
||||
<div className="bg-gray-100 p-4 rounded-xl">
|
||||
<h3 className="text-lg font-bold text-gray-800 mb-3">Оплата по СБП</h3>
|
||||
<div className="flex justify-center p-4 bg-white rounded-lg">
|
||||
<QRCode value={sbpUrl || 'https://qr.nspk.ru/FAKE'} size={200} />
|
||||
</div>
|
||||
<p className="mt-3 text-xs text-gray-600 text-center">
|
||||
Отсканируйте QR-код в приложении банка
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Номер карты */}
|
||||
<div className="bg-gray-100 p-4 rounded-xl">
|
||||
<h3 className="text-lg font-bold text-gray-800 mb-3">Номер карты</h3>
|
||||
<p className="text-xl font-mono font-bold text-gray-800 break-all mb-3 bg-white p-4 rounded-lg">
|
||||
{cardNumber || '0000 0000 0000 0000'}
|
||||
</p>
|
||||
<button
|
||||
onClick={handleCopyCard}
|
||||
className="w-full px-4 py-2 rounded-lg text-white font-semibold bg-gray-700 hover:bg-gray-800 transition"
|
||||
>
|
||||
Скопировать номер карты
|
||||
</button>
|
||||
</div>
|
||||
<p className="mt-4 text-xs lg:text-sm text-gray-600">
|
||||
Отсканируйте QR-код через мобильное приложение вашего банка.
|
||||
</p>
|
||||
</div>
|
||||
{/* Номер карты с кнопкой копирования */}
|
||||
<div className="bg-gray-100 p-4 lg:p-6 rounded-xl lg:rounded-2xl mb-6">
|
||||
<h3 className="text-lg lg:text-xl font-bold text-gray-800 mb-2">Оплата по номеру карты</h3>
|
||||
<p className="text-xl lg:text-2xl font-bold text-gray-800 select-all break-words">{cardNumber || '0000 0000 0000 0000'}</p>
|
||||
<button
|
||||
onClick={handleCopyCard}
|
||||
className="mt-4 px-4 py-2 rounded-full text-white font-bold transition-colors transform hover:scale-105 bg-gray-500 hover:bg-gray-700 w-full lg:w-auto"
|
||||
>
|
||||
Скопировать номер карты
|
||||
</button>
|
||||
{copyStatus && <p className="mt-2 text-sm text-green-500">{copyStatus}</p>}
|
||||
|
||||
{/* Загрузка чека */}
|
||||
<div className="bg-gray-50 border-2 border-dashed border-gray-300 rounded-xl p-6 mb-4">
|
||||
<h3 className="text-lg font-bold text-gray-800 mb-3">Загрузка чека</h3>
|
||||
{checkFile ? (
|
||||
<div>
|
||||
<p className="text-gray-700 mb-2">
|
||||
<strong>Выбран файл:</strong> {checkFile.name}
|
||||
</p>
|
||||
<p className="text-sm text-gray-500 mb-3">
|
||||
Размер: {(checkFile.size / 1024 / 1024).toFixed(2)} МБ
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => setCheckFile(null)}
|
||||
className="px-4 py-2 bg-gray-300 rounded-lg hover:bg-gray-400 transition"
|
||||
>
|
||||
Удалить
|
||||
</button>
|
||||
<button
|
||||
onClick={handleCheckUpload}
|
||||
disabled={uploadLoading}
|
||||
className="flex-1 px-4 py-2 bg-ospab-primary text-white rounded-lg hover:bg-ospab-accent transition disabled:bg-gray-400"
|
||||
>
|
||||
{uploadLoading ? 'Загрузка...' : 'Отправить чек'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center">
|
||||
<p className="text-gray-600 mb-2">
|
||||
<label className="text-ospab-primary cursor-pointer hover:underline font-semibold">
|
||||
Нажмите, чтобы выбрать файл
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*,application/pdf"
|
||||
onChange={(e) => e.target.files && setCheckFile(e.target.files[0])}
|
||||
className="hidden"
|
||||
/>
|
||||
</label>
|
||||
</p>
|
||||
<p className="text-sm text-gray-500">JPG, PNG, PDF (до 10 МБ)</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{/* Форма загрузки чека и инструкции */}
|
||||
<div className="bg-blue-50 p-4 lg:p-6 rounded-xl lg:rounded-2xl border-l-4 border-blue-500 text-left mb-6">
|
||||
<p className="font-bold text-blue-800 text-sm lg:text-base">Загрузите чек для проверки:</p>
|
||||
<input type="file" accept="image/*,application/pdf" onChange={e => setCheckFile(e.target.files?.[0] || null)} className="mt-2 text-sm w-full" />
|
||||
<button onClick={handleCheckUpload} disabled={!checkFile || uploadLoading} className="mt-2 bg-blue-500 text-white px-4 py-2 rounded w-full lg:w-auto">
|
||||
{uploadLoading ? 'Загрузка...' : 'Отправить чек'}
|
||||
</button>
|
||||
{checkStatus && <div className="mt-2 text-green-600 text-sm">{checkStatus}</div>}
|
||||
</div>
|
||||
<div className="bg-red-50 p-4 lg:p-6 rounded-xl lg:rounded-2xl border-l-4 border-red-500 text-left mb-6">
|
||||
<p className="font-bold text-red-800 text-sm lg:text-base">Важно:</p>
|
||||
<p className="text-xs lg:text-sm text-red-700">
|
||||
После оплаты сделайте скриншот или сохраните чек и загрузите его для проверки.
|
||||
</p>
|
||||
</div>
|
||||
<p className="mt-4 text-gray-600 text-sm lg:text-base">
|
||||
После подтверждения ваш баланс будет пополнен. Ожидайте проверки чека оператором.
|
||||
</p>
|
||||
|
||||
<button
|
||||
onClick={() => {
|
||||
setIsPaymentGenerated(false);
|
||||
setAmount(0);
|
||||
}}
|
||||
className="w-full px-4 py-2 bg-gray-200 text-gray-700 rounded-xl hover:bg-gray-300 transition"
|
||||
>
|
||||
Изменить сумму
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* История чеков */}
|
||||
<div className="mt-8 pt-8 border-t border-gray-200">
|
||||
<h3 className="text-xl font-bold text-gray-800 mb-4">История чеков</h3>
|
||||
{checks.length > 0 ? (
|
||||
<div className="space-y-3">
|
||||
{checks.map((check) => (
|
||||
<div
|
||||
key={check.id}
|
||||
className="bg-gray-50 p-4 rounded-xl flex items-center justify-between"
|
||||
>
|
||||
<div>
|
||||
<p className="font-semibold text-gray-800">{check.amount} ₽</p>
|
||||
<p className="text-sm text-gray-500">
|
||||
{new Date(check.createdAt).toLocaleString('ru-RU')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className={`font-semibold ${getStatusColor(check.status)}`}>
|
||||
{getStatusText(check.status)}
|
||||
</span>
|
||||
<a
|
||||
href={getCheckFileUrl(check.fileUrl)}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-ospab-primary hover:underline text-sm"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
const token = localStorage.getItem('access_token');
|
||||
const url = getCheckFileUrl(check.fileUrl);
|
||||
|
||||
// Открываем в новом окне с токеном в заголовке через fetch
|
||||
fetch(url, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`
|
||||
}
|
||||
})
|
||||
.then(res => res.blob())
|
||||
.then(blob => {
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
window.open(objectUrl, '_blank');
|
||||
})
|
||||
.catch(err => {
|
||||
console.error('Ошибка загрузки чека:', err);
|
||||
showMessage('Не удалось загрузить чек', 'error');
|
||||
});
|
||||
}}
|
||||
>
|
||||
Чек
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-gray-500 text-center py-4">История чеков пуста</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Billing;
|
||||
export default Billing;
|
||||
|
||||
342
ospabhost/frontend/src/pages/dashboard/blogadmin.tsx
Normal file
342
ospabhost/frontend/src/pages/dashboard/blogadmin.tsx
Normal file
@@ -0,0 +1,342 @@
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import axios from 'axios';
|
||||
import { API_URL } from '../../config/api';
|
||||
import { useToast } from '../../hooks/useToast';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Modal } from '../../components/Modal';
|
||||
|
||||
interface Post {
|
||||
id: number;
|
||||
title: string;
|
||||
content: string;
|
||||
excerpt: string;
|
||||
coverImage: string | null;
|
||||
url: string;
|
||||
status: string;
|
||||
views: number;
|
||||
createdAt: string;
|
||||
publishedAt: string | null;
|
||||
author: {
|
||||
id: number;
|
||||
username: string;
|
||||
};
|
||||
_count: {
|
||||
comments: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface Comment {
|
||||
id: number;
|
||||
content: string;
|
||||
authorName: string | null;
|
||||
status: string;
|
||||
createdAt: string;
|
||||
user: {
|
||||
id: number;
|
||||
username: string;
|
||||
} | null;
|
||||
post: {
|
||||
id: number;
|
||||
title: string;
|
||||
};
|
||||
}
|
||||
|
||||
const BlogAdmin: React.FC = () => {
|
||||
const { addToast } = useToast();
|
||||
const navigate = useNavigate();
|
||||
const [posts, setPosts] = useState<Post[]>([]);
|
||||
const [comments, setComments] = useState<Comment[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [activeTab, setActiveTab] = useState<'posts' | 'comments'>('posts');
|
||||
|
||||
// Модальное окно удаления
|
||||
const [showDeleteModal, setShowDeleteModal] = useState(false);
|
||||
const [postToDelete, setPostToDelete] = useState<number | null>(null);
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
|
||||
const [postsRes, commentsRes] = await Promise.all([
|
||||
axios.get(`${API_URL}/api/blog/admin/posts`, { headers }),
|
||||
axios.get(`${API_URL}/api/blog/admin/comments`, { headers })
|
||||
]);
|
||||
|
||||
setPosts(postsRes.data.data);
|
||||
setComments(commentsRes.data.data);
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки данных:', error);
|
||||
addToast('Не удалось загрузить данные', 'error');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [addToast]);
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
|
||||
// Открыть редактор для нового поста
|
||||
const handleNewPost = () => {
|
||||
navigate('/dashboard/blogeditor');
|
||||
};
|
||||
|
||||
// Открыть редактор для редактирования поста
|
||||
const handleEditPost = (postId: number) => {
|
||||
navigate(`/dashboard/blogeditor/${postId}`);
|
||||
};
|
||||
|
||||
// Удалить пост
|
||||
const handleDeletePost = async () => {
|
||||
if (!postToDelete) return;
|
||||
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
|
||||
await axios.delete(`${API_URL}/api/blog/admin/posts/${postToDelete}`, { headers });
|
||||
addToast('Пост удалён', 'success');
|
||||
setShowDeleteModal(false);
|
||||
setPostToDelete(null);
|
||||
loadData();
|
||||
} catch (error) {
|
||||
console.error('Ошибка удаления поста:', error);
|
||||
addToast('Не удалось удалить пост', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
// Модерация комментария
|
||||
const handleModerateComment = async (commentId: number, status: 'approved' | 'rejected') => {
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
|
||||
await axios.patch(`${API_URL}/api/blog/admin/comments/${commentId}`, { status }, { headers });
|
||||
addToast(`Комментарий ${status === 'approved' ? 'одобрен' : 'отклонён'}`, 'success');
|
||||
loadData();
|
||||
} catch (error) {
|
||||
console.error('Ошибка модерации:', error);
|
||||
addToast('Ошибка модерации комментария', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
// Удалить комментарий
|
||||
const handleDeleteComment = async (commentId: number) => {
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
|
||||
await axios.delete(`${API_URL}/api/blog/admin/comments/${commentId}`, { headers });
|
||||
addToast('Комментарий удалён', 'success');
|
||||
loadData();
|
||||
} catch (error) {
|
||||
console.error('Ошибка удаления комментария:', error);
|
||||
addToast('Не удалось удалить комментарий', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusBadge = (status: string) => {
|
||||
const styles = {
|
||||
draft: 'bg-gray-200 text-gray-700',
|
||||
published: 'bg-green-200 text-green-700',
|
||||
archived: 'bg-red-200 text-red-700',
|
||||
pending: 'bg-yellow-200 text-yellow-700',
|
||||
approved: 'bg-green-200 text-green-700',
|
||||
rejected: 'bg-red-200 text-red-700'
|
||||
};
|
||||
|
||||
const labels = {
|
||||
draft: 'Черновик',
|
||||
published: 'Опубликовано',
|
||||
archived: 'Архив',
|
||||
pending: 'На модерации',
|
||||
approved: 'Одобрен',
|
||||
rejected: 'Отклонён'
|
||||
};
|
||||
|
||||
return (
|
||||
<span className={`px-2 py-1 rounded text-xs font-semibold ${styles[status as keyof typeof styles]}`}>
|
||||
{labels[status as keyof typeof labels]}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
const formatDate = (dateString: string) => {
|
||||
return new Date(dateString).toLocaleString('ru-RU');
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex justify-center items-center h-screen">
|
||||
<div className="text-xl">Загрузка...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<h1 className="text-4xl font-bold mb-8">Управление блогом</h1>
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="flex gap-4 mb-6 border-b">
|
||||
<button
|
||||
className={`px-4 py-2 ${activeTab === 'posts' ? 'border-b-2 border-blue-500 font-bold' : ''}`}
|
||||
onClick={() => setActiveTab('posts')}
|
||||
>
|
||||
Статьи ({posts.length})
|
||||
</button>
|
||||
<button
|
||||
className={`px-4 py-2 ${activeTab === 'comments' ? 'border-b-2 border-blue-500 font-bold' : ''}`}
|
||||
onClick={() => setActiveTab('comments')}
|
||||
>
|
||||
Комментарии ({comments.filter(c => c.status === 'pending').length})
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Posts Tab */}
|
||||
{activeTab === 'posts' && (
|
||||
<div>
|
||||
<button
|
||||
onClick={handleNewPost}
|
||||
className="mb-6 px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
➕ Создать статью
|
||||
</button>
|
||||
|
||||
<div className="bg-white rounded-lg shadow overflow-hidden">
|
||||
<table className="min-w-full">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Заголовок</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">URL</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Статус</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Просмотры</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Комментарии</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Дата</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Действия</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{posts.map((post) => (
|
||||
<tr key={post.id} className="hover:bg-gray-50">
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<div className="text-sm font-medium text-gray-900">{post.title}</div>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
|
||||
/blog/{post.url}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
{getStatusBadge(post.status)}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
|
||||
Просмотров: {post.views}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
|
||||
Комментариев: {post._count.comments}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
|
||||
{formatDate(post.createdAt)}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm space-x-2">
|
||||
<button
|
||||
onClick={() => handleEditPost(post.id)}
|
||||
className="text-blue-600 hover:text-blue-800"
|
||||
>
|
||||
Редактировать
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
setPostToDelete(post.id);
|
||||
setShowDeleteModal(true);
|
||||
}}
|
||||
className="text-red-600 hover:text-red-800"
|
||||
>
|
||||
Удалить
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Comments Tab */}
|
||||
{activeTab === 'comments' && (
|
||||
<div className="space-y-4">
|
||||
{comments.map((comment) => (
|
||||
<div key={comment.id} className="bg-white p-6 rounded-lg shadow">
|
||||
<div className="flex justify-between items-start mb-4">
|
||||
<div>
|
||||
<p className="text-sm text-gray-500">
|
||||
К статье: <strong>{comment.post.title}</strong>
|
||||
</p>
|
||||
<p className="text-sm text-gray-500">
|
||||
Автор: <strong>{comment.user ? comment.user.username : comment.authorName}</strong>
|
||||
{' '} • {formatDate(comment.createdAt)}
|
||||
</p>
|
||||
</div>
|
||||
{getStatusBadge(comment.status)}
|
||||
</div>
|
||||
|
||||
<p className="text-gray-700 mb-4 whitespace-pre-wrap">{comment.content}</p>
|
||||
|
||||
<div className="flex gap-2">
|
||||
{comment.status === 'pending' && (
|
||||
<>
|
||||
<button
|
||||
onClick={() => handleModerateComment(comment.id, 'approved')}
|
||||
className="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700"
|
||||
>
|
||||
Одобрить
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleModerateComment(comment.id, 'rejected')}
|
||||
className="px-4 py-2 bg-yellow-600 text-white rounded hover:bg-yellow-700"
|
||||
>
|
||||
Отклонить
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
<button
|
||||
onClick={() => handleDeleteComment(comment.id)}
|
||||
className="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
|
||||
>
|
||||
Удалить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{comments.length === 0 && (
|
||||
<p className="text-center text-gray-400 py-8">Комментариев нет</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Delete Confirmation Modal */}
|
||||
<Modal
|
||||
isOpen={showDeleteModal}
|
||||
onClose={() => {
|
||||
setShowDeleteModal(false);
|
||||
setPostToDelete(null);
|
||||
}}
|
||||
title="Удаление статьи"
|
||||
type="danger"
|
||||
onConfirm={handleDeletePost}
|
||||
confirmText="Да, удалить"
|
||||
cancelText="Отмена"
|
||||
>
|
||||
<p>Вы уверены, что хотите удалить эту статью?</p>
|
||||
<p className="mt-2 text-sm text-gray-600">
|
||||
Все комментарии к статье также будут удалены. Это действие необратимо.
|
||||
</p>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default BlogAdmin;
|
||||
321
ospabhost/frontend/src/pages/dashboard/blogeditor.tsx
Normal file
321
ospabhost/frontend/src/pages/dashboard/blogeditor.tsx
Normal file
@@ -0,0 +1,321 @@
|
||||
import React, { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import axios from 'axios';
|
||||
import { API_URL } from '../../config/api';
|
||||
import { useToast } from '../../hooks/useToast';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import ReactQuill from 'react-quill';
|
||||
import 'react-quill/dist/quill.snow.css';
|
||||
|
||||
const BlogEditor: React.FC = () => {
|
||||
const { addToast } = useToast();
|
||||
const navigate = useNavigate();
|
||||
const { postId } = useParams<{ postId?: string }>();
|
||||
const quillRef = useRef<ReactQuill>(null);
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [formData, setFormData] = useState({
|
||||
title: '',
|
||||
content: '',
|
||||
excerpt: '',
|
||||
coverImage: '',
|
||||
url: '',
|
||||
status: 'draft'
|
||||
});
|
||||
|
||||
const loadPost = useCallback(async (id: number) => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
|
||||
const response = await axios.get(`${API_URL}/api/blog/admin/posts/${id}`, { headers });
|
||||
const post = response.data.data;
|
||||
|
||||
setFormData({
|
||||
title: post.title,
|
||||
content: post.content,
|
||||
excerpt: post.excerpt || '',
|
||||
coverImage: post.coverImage || '',
|
||||
url: post.url,
|
||||
status: post.status
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки поста:', error);
|
||||
addToast('Не удалось загрузить пост', 'error');
|
||||
navigate('/dashboard/blogadmin');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [addToast, navigate]);
|
||||
|
||||
// Загрузить пост для редактирования
|
||||
useEffect(() => {
|
||||
if (postId) {
|
||||
loadPost(parseInt(postId));
|
||||
}
|
||||
}, [postId, loadPost]);
|
||||
|
||||
// Сохранить пост
|
||||
const handleSavePost = async () => {
|
||||
if (!formData.title || !formData.content || !formData.url) {
|
||||
addToast('Заполните обязательные поля (Заголовок, URL, Содержание)', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
|
||||
if (postId) {
|
||||
// Обновление
|
||||
await axios.put(`${API_URL}/api/blog/admin/posts/${postId}`, formData, { headers });
|
||||
addToast('Пост обновлён', 'success');
|
||||
} else {
|
||||
// Создание
|
||||
await axios.post(`${API_URL}/api/blog/admin/posts`, formData, { headers });
|
||||
addToast('Пост создан', 'success');
|
||||
}
|
||||
|
||||
navigate('/dashboard/blogadmin');
|
||||
} catch (error) {
|
||||
console.error('Ошибка сохранения поста:', error);
|
||||
const message = error instanceof Error && 'response' in error
|
||||
? (error as { response?: { data?: { message?: string } } }).response?.data?.message
|
||||
: 'Ошибка сохранения';
|
||||
addToast(message || 'Ошибка сохранения', 'error');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Обработчик загрузки изображений для Quill
|
||||
const imageHandler = useCallback(() => {
|
||||
const input = document.createElement('input');
|
||||
input.setAttribute('type', 'file');
|
||||
input.setAttribute('accept', 'image/*');
|
||||
input.click();
|
||||
|
||||
input.onchange = async () => {
|
||||
const file = input.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
// Проверка размера файла (макс 10MB)
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
addToast('Файл слишком большой. Максимальный размер: 10MB', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('image', file);
|
||||
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'multipart/form-data'
|
||||
};
|
||||
|
||||
const response = await axios.post(
|
||||
`${API_URL}/api/blog/admin/upload-image`,
|
||||
formData,
|
||||
{ headers }
|
||||
);
|
||||
|
||||
const imageUrl = response.data.data.url;
|
||||
|
||||
// Вставляем изображение в редактор
|
||||
if (quillRef.current) {
|
||||
const editor = quillRef.current.getEditor();
|
||||
const range = editor.getSelection();
|
||||
editor.insertEmbed(range?.index || 0, 'image', imageUrl);
|
||||
}
|
||||
|
||||
addToast('Изображение загружено', 'success');
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки изображения:', error);
|
||||
addToast('Не удалось загрузить изображение', 'error');
|
||||
}
|
||||
};
|
||||
}, [addToast]);
|
||||
|
||||
// Конфигурация Quill
|
||||
const quillModules = {
|
||||
toolbar: {
|
||||
container: [
|
||||
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
|
||||
[{ 'font': [] }],
|
||||
[{ 'size': ['small', false, 'large', 'huge'] }],
|
||||
['bold', 'italic', 'underline', 'strike'],
|
||||
[{ 'color': [] }, { 'background': [] }],
|
||||
[{ 'list': 'ordered'}, { 'list': 'bullet' }],
|
||||
[{ 'align': [] }],
|
||||
['link', 'image', 'video'],
|
||||
['blockquote', 'code-block'],
|
||||
['clean']
|
||||
],
|
||||
handlers: {
|
||||
image: imageHandler
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex justify-center items-center h-screen">
|
||||
<div className="text-xl">Загрузка...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<div className="container mx-auto px-4 py-6">
|
||||
{/* Header */}
|
||||
<div className="bg-white rounded-lg shadow-sm p-4 mb-6 flex justify-between items-center">
|
||||
<h1 className="text-2xl font-bold">
|
||||
{postId ? 'Редактирование статьи' : 'Новая статья'}
|
||||
</h1>
|
||||
<div className="flex gap-3">
|
||||
<button
|
||||
onClick={() => navigate('/dashboard/blogadmin')}
|
||||
className="px-6 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors"
|
||||
disabled={loading}
|
||||
>
|
||||
← Назад
|
||||
</button>
|
||||
<button
|
||||
onClick={handleSavePost}
|
||||
className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50"
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? 'Сохранение...' : 'Сохранить'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Main Content */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
{/* Editor Area */}
|
||||
<div className="lg:col-span-2 space-y-6">
|
||||
{/* Title */}
|
||||
<div className="bg-white rounded-lg shadow-sm p-6">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Заголовок статьи <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.title}
|
||||
onChange={(e) => setFormData({ ...formData, title: e.target.value })}
|
||||
className="w-full px-4 py-3 text-lg border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
placeholder="Введите заголовок статьи..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Content Editor */}
|
||||
<div className="bg-white rounded-lg shadow-sm p-6">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Содержание статьи <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<div className="border border-gray-300 rounded-lg overflow-hidden">
|
||||
<ReactQuill
|
||||
ref={quillRef}
|
||||
theme="snow"
|
||||
value={formData.content}
|
||||
onChange={(value) => setFormData({ ...formData, content: value })}
|
||||
modules={quillModules}
|
||||
className="bg-white"
|
||||
style={{ minHeight: '500px' }}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-2">
|
||||
Используйте кнопку изображения для загрузки картинок в статью
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Sidebar - Settings */}
|
||||
<div className="space-y-6">
|
||||
{/* URL */}
|
||||
<div className="bg-white rounded-lg shadow-sm p-6">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
URL статьи <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<div className="flex items-center mb-2">
|
||||
<span className="text-gray-500 text-sm mr-2">/blog/</span>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.url}
|
||||
onChange={(e) => setFormData({ ...formData, url: e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, '-') })}
|
||||
className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
|
||||
placeholder="my-awesome-post"
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">
|
||||
Используйте латиницу, цифры и дефисы
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Status */}
|
||||
<div className="bg-white rounded-lg shadow-sm p-6">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Статус публикации
|
||||
</label>
|
||||
<select
|
||||
value={formData.status}
|
||||
onChange={(e) => setFormData({ ...formData, status: e.target.value })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
>
|
||||
<option value="draft">Черновик</option>
|
||||
<option value="published">Опубликовано</option>
|
||||
<option value="archived">📦 Архив</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Excerpt */}
|
||||
<div className="bg-white rounded-lg shadow-sm p-6">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Краткое описание
|
||||
</label>
|
||||
<textarea
|
||||
value={formData.excerpt}
|
||||
onChange={(e) => setFormData({ ...formData, excerpt: e.target.value })}
|
||||
rows={4}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
|
||||
placeholder="Краткое описание для отображения в ленте блога..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Cover Image */}
|
||||
<div className="bg-white rounded-lg shadow-sm p-6">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Обложка статьи
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.coverImage}
|
||||
onChange={(e) => setFormData({ ...formData, coverImage: e.target.value })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
|
||||
placeholder="https://example.com/image.jpg"
|
||||
/>
|
||||
{formData.coverImage && (
|
||||
<div className="mt-3">
|
||||
<img
|
||||
src={formData.coverImage}
|
||||
alt="Preview"
|
||||
className="w-full h-32 object-cover rounded-lg"
|
||||
onError={(e) => {
|
||||
e.currentTarget.src = 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="100" height="100"%3E%3Crect fill="%23ddd" width="100" height="100"/%3E%3Ctext x="50%25" y="50%25" text-anchor="middle" dy=".3em" fill="%23999"%3EНе загружено%3C/text%3E%3C/svg%3E';
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default BlogEditor;
|
||||
@@ -1,148 +1,317 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import axios from 'axios';
|
||||
|
||||
interface Tariff {
|
||||
id: number;
|
||||
name: string;
|
||||
price: number;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
interface OperatingSystem {
|
||||
id: number;
|
||||
name: string;
|
||||
type: string;
|
||||
template?: string;
|
||||
}
|
||||
import React, { useCallback, useEffect, useState } from 'react';
|
||||
import { useLocation, useNavigate } from 'react-router-dom';
|
||||
import { FiAlertCircle, FiArrowLeft, FiDatabase, FiDollarSign, FiInfo, FiShoppingCart } from 'react-icons/fi';
|
||||
import apiClient from '../../utils/apiClient';
|
||||
import { API_URL } from '../../config/api';
|
||||
import { DEFAULT_STORAGE_PLAN_ID, STORAGE_PLAN_IDS, STORAGE_PLAN_MAP, type StoragePlanId } from '../../constants/storagePlans';
|
||||
|
||||
// Упрощённый Checkout только для S3 Bucket
|
||||
interface CheckoutProps {
|
||||
onSuccess: () => void;
|
||||
onSuccess?: () => void;
|
||||
}
|
||||
|
||||
const Checkout: React.FC<CheckoutProps> = ({ onSuccess }) => {
|
||||
const [tariffs, setTariffs] = useState<Tariff[]>([]);
|
||||
const [oses, setOses] = useState<OperatingSystem[]>([]);
|
||||
const [selectedTariff, setSelectedTariff] = useState<number | null>(null);
|
||||
const [selectedOs, setSelectedOs] = useState<number | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [planName, setPlanName] = useState<StoragePlanId>(DEFAULT_STORAGE_PLAN_ID);
|
||||
const [planPrice, setPlanPrice] = useState<number>(STORAGE_PLAN_MAP[DEFAULT_STORAGE_PLAN_ID].price);
|
||||
const [balance, setBalance] = useState<number>(0);
|
||||
const [bucketName, setBucketName] = useState<string>('');
|
||||
const [region, setRegion] = useState<string>('ru-central-1');
|
||||
const [storageClass, setStorageClass] = useState<string>('standard');
|
||||
const [isPublic, setIsPublic] = useState<boolean>(false);
|
||||
const [versioning, setVersioning] = useState<boolean>(false);
|
||||
const [loading, setLoading] = useState<boolean>(false);
|
||||
const [error, setError] = useState<string>('');
|
||||
|
||||
// Загружаем параметры из query (?plan=basic&price=199)
|
||||
const fetchBalance = useCallback(async () => {
|
||||
try {
|
||||
const res = await apiClient.get(`${API_URL}/api/user/balance`);
|
||||
setBalance(res.data.balance || 0);
|
||||
} catch (e) {
|
||||
console.error('Ошибка загрузки баланса', e);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
// Загрузка тарифов и ОС
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
const [tariffRes, osRes] = await Promise.all([
|
||||
axios.get(`${process.env.VITE_API_URL || 'https://ospab.host:5000'}/api/tariff`, { headers }),
|
||||
axios.get(`${process.env.VITE_API_URL || 'https://ospab.host:5000'}/api/os`, { headers }),
|
||||
]);
|
||||
setTariffs(tariffRes.data);
|
||||
setOses(osRes.data);
|
||||
// Автовыбор тарифа из query
|
||||
const params = new URLSearchParams(location.search);
|
||||
const tariffId = params.get('tariff');
|
||||
if (tariffId) {
|
||||
setSelectedTariff(Number(tariffId));
|
||||
}
|
||||
} catch {
|
||||
setError('Ошибка загрузки тарифов или ОС');
|
||||
}
|
||||
};
|
||||
fetchData();
|
||||
}, [location.search]);
|
||||
const params = new URLSearchParams(location.search);
|
||||
const rawPlan = params.get('plan');
|
||||
const match = rawPlan ? rawPlan.toLowerCase() : '';
|
||||
const planId = STORAGE_PLAN_IDS.includes(match as StoragePlanId)
|
||||
? (match as StoragePlanId)
|
||||
: DEFAULT_STORAGE_PLAN_ID;
|
||||
setPlanName(planId);
|
||||
|
||||
const handleBuy = async () => {
|
||||
if (!selectedTariff || !selectedOs) {
|
||||
setError('Выберите тариф и ОС');
|
||||
const priceParam = params.get('price');
|
||||
if (priceParam) {
|
||||
const numeric = Number(priceParam);
|
||||
setPlanPrice(Number.isFinite(numeric) && numeric > 0 ? numeric : STORAGE_PLAN_MAP[planId].price);
|
||||
} else {
|
||||
setPlanPrice(STORAGE_PLAN_MAP[planId].price);
|
||||
}
|
||||
|
||||
fetchBalance();
|
||||
}, [location.search, fetchBalance]);
|
||||
|
||||
const meta = STORAGE_PLAN_MAP[planName];
|
||||
|
||||
const canCreate = () => {
|
||||
if (!planPrice || !bucketName.trim() || !meta) return false;
|
||||
if (balance < planPrice) return false;
|
||||
// Простая валидация имени (можно расширить): маленькие буквы, цифры, тире
|
||||
return /^[a-z0-9-]{3,40}$/.test(bucketName.trim());
|
||||
};
|
||||
|
||||
const handleCreate = async () => {
|
||||
if (!canCreate()) {
|
||||
setError('Проверьте корректность данных и баланс');
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
const token = localStorage.getItem('access_token') || localStorage.getItem('token');
|
||||
console.log('Покупка сервера:', { tariffId: selectedTariff, osId: selectedOs });
|
||||
const res = await axios.post(`${process.env.VITE_API_URL || 'https://ospab.host:5000'}/api/server/create`, {
|
||||
tariffId: selectedTariff,
|
||||
osId: selectedOs,
|
||||
}, {
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||
withCredentials: true,
|
||||
// POST на будущий endpoint S3
|
||||
const res = await apiClient.post(`${API_URL}/api/storage/buckets`, {
|
||||
name: bucketName.trim(),
|
||||
plan: planName,
|
||||
quotaGb: meta?.quotaGb || 0,
|
||||
region,
|
||||
storageClass,
|
||||
public: isPublic,
|
||||
versioning
|
||||
});
|
||||
if (res.data && res.data.error === 'Недостаточно средств на балансе') {
|
||||
setError('Недостаточно средств на балансе. Пополните баланс и попробуйте снова.');
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
// После успешной покупки обновляем userData
|
||||
try {
|
||||
const userRes = await axios.get(`${process.env.VITE_API_URL || 'https://ospab.host:5000'}/api/auth/me`, { headers: token ? { Authorization: `Bearer ${token}` } : {} });
|
||||
window.dispatchEvent(new CustomEvent('userDataUpdate', {
|
||||
detail: {
|
||||
user: userRes.data.user,
|
||||
balance: userRes.data.user.balance ?? 0,
|
||||
servers: userRes.data.user.servers ?? [],
|
||||
tickets: userRes.data.user.tickets ?? [],
|
||||
}
|
||||
}));
|
||||
} catch (err) {
|
||||
console.error('Ошибка обновления userData после покупки:', err);
|
||||
}
|
||||
onSuccess();
|
||||
} catch (err) {
|
||||
if (axios.isAxiosError(err) && err.response?.data?.error === 'Недостаточно средств на балансе') {
|
||||
setError('Недостаточно средств на балансе. Пополните баланс и попробуйте снова.');
|
||||
|
||||
if (res.data?.error) {
|
||||
setError(res.data.error);
|
||||
} else {
|
||||
setError('Ошибка покупки сервера');
|
||||
// Обновляем пользовательские данные и баланс (если списание произошло на сервере)
|
||||
try {
|
||||
const userRes = await apiClient.get(`${API_URL}/api/auth/me`);
|
||||
window.dispatchEvent(new CustomEvent('userDataUpdate', {
|
||||
detail: { user: userRes.data.user }
|
||||
}));
|
||||
} catch (e) {
|
||||
console.error('Ошибка обновления userData', e);
|
||||
}
|
||||
if (onSuccess) onSuccess();
|
||||
navigate('/dashboard/storage');
|
||||
}
|
||||
console.error('Ошибка покупки сервера:', err);
|
||||
} catch (e: unknown) {
|
||||
let message = 'Ошибка создания бакета';
|
||||
if (e && typeof e === 'object' && 'response' in e) {
|
||||
const resp = (e as { response?: { data?: { message?: string } } }).response;
|
||||
if (resp?.data?.message) message = resp.data.message;
|
||||
}
|
||||
setError(message);
|
||||
console.error(e);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-8 bg-white rounded-3xl shadow-xl max-w-xl mx-auto">
|
||||
<h2 className="text-2xl font-bold mb-4">Покупка сервера</h2>
|
||||
{error && <p className="text-red-500 mb-2">{error}</p>}
|
||||
<div className="mb-4">
|
||||
<label className="block font-semibold mb-2">Тариф:</label>
|
||||
<select
|
||||
className="w-full border rounded px-3 py-2"
|
||||
value={selectedTariff ?? ''}
|
||||
onChange={e => setSelectedTariff(Number(e.target.value))}
|
||||
<div className="max-w-5xl mx-auto">
|
||||
{/* Header */}
|
||||
<div className="mb-6">
|
||||
<button
|
||||
onClick={() => navigate('/dashboard/storage')}
|
||||
className="flex items-center gap-2 px-4 py-2 text-ospab-primary hover:bg-ospab-primary/5 rounded-lg transition-colors mb-4"
|
||||
>
|
||||
<option value="">Выберите тариф</option>
|
||||
{tariffs.map(t => (
|
||||
<option key={t.id} value={t.id}>
|
||||
{t.name} — ₽{t.price}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<FiArrowLeft />
|
||||
<span>Назад к хранилищу</span>
|
||||
</button>
|
||||
<h1 className="text-3xl font-bold text-gray-800 flex items-center gap-2">
|
||||
<FiDatabase className="text-ospab-primary" /> Создание S3 Bucket
|
||||
</h1>
|
||||
<p className="text-gray-600 mt-1">План: {meta?.title}{planPrice ? ` • ₽${planPrice}/мес` : ''}</p>
|
||||
</div>
|
||||
<div className="mb-4">
|
||||
<label className="block font-semibold mb-2">Операционная система:</label>
|
||||
<select
|
||||
className="w-full border rounded px-3 py-2"
|
||||
value={selectedOs ?? ''}
|
||||
onChange={e => setSelectedOs(Number(e.target.value))}
|
||||
>
|
||||
<option value="">Выберите ОС</option>
|
||||
{oses.map(os => (
|
||||
<option key={os.id} value={os.id}>
|
||||
{os.name} ({os.type})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-50 border border-red-200 rounded-xl p-4 mb-6 flex items-start gap-3">
|
||||
<FiAlertCircle className="text-red-500 text-xl flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="text-red-700 font-semibold">Ошибка</p>
|
||||
<p className="text-red-600 text-sm">{error}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
{/* Left */}
|
||||
<div className="lg:col-span-2 space-y-6">
|
||||
{/* Bucket settings */}
|
||||
<div className="bg-white rounded-xl shadow-md p-6">
|
||||
<h2 className="text-xl font-bold text-gray-800 mb-4">Параметры бакета</h2>
|
||||
<div className="space-y-5">
|
||||
<div>
|
||||
<label className="block text-sm font-semibold text-gray-700 mb-2">Имя бакета</label>
|
||||
<input
|
||||
type="text"
|
||||
value={bucketName}
|
||||
onChange={(e) => setBucketName(e.target.value)}
|
||||
placeholder="например: media-assets"
|
||||
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-ospab-primary focus:border-transparent transition-all"
|
||||
/>
|
||||
<p className="text-xs text-gray-500 mt-1">Допустимы: a-z 0-9 - (3–40 символов)</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-semibold text-gray-700 mb-2">Регион</label>
|
||||
<select
|
||||
value={region}
|
||||
onChange={(e) => setRegion(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-ospab-primary focus:border-transparent"
|
||||
>
|
||||
<option value="ru-central-1">ru-central-1</option>
|
||||
<option value="eu-east-1">eu-east-1</option>
|
||||
<option value="eu-west-1">eu-west-1</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-semibold text-gray-700 mb-2">Класс хранения</label>
|
||||
<select
|
||||
value={storageClass}
|
||||
onChange={(e) => setStorageClass(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-ospab-primary focus:border-transparent"
|
||||
>
|
||||
<option value="standard">Standard</option>
|
||||
<option value="infrequent">Infrequent</option>
|
||||
<option value="archive">Archive</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<label className="flex items-center gap-2 cursor-pointer select-none">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isPublic}
|
||||
onChange={(e) => setIsPublic(e.target.checked)}
|
||||
className="rounded"
|
||||
/>
|
||||
<span className="text-sm text-gray-700">Публичный доступ</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2 cursor-pointer select-none">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={versioning}
|
||||
onChange={(e) => setVersioning(e.target.checked)}
|
||||
className="rounded"
|
||||
/>
|
||||
<span className="text-sm text-gray-700">Версионирование</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Plan info */}
|
||||
<div className="bg-white rounded-xl shadow-md p-6">
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<FiInfo className="text-ospab-primary text-xl" />
|
||||
<h2 className="text-xl font-bold text-gray-800">Информация о плане</h2>
|
||||
</div>
|
||||
{meta ? (
|
||||
<div className="space-y-3">
|
||||
<p className="text-gray-700 text-sm">Включённый объём: <span className="font-semibold">{meta.quotaGb} GB</span></p>
|
||||
<ul className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm text-gray-600">
|
||||
{meta.included.slice(0, 4).map((d) => (
|
||||
<li key={d} className="flex items-center gap-2">
|
||||
<span className="w-1.5 h-1.5 bg-ospab-primary rounded-full"></span>{d}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 text-sm text-gray-700">
|
||||
Оплата списывается помесячно при создании бакета. Использование сверх квоты будет тарифицироваться позже.
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-gray-500 text-sm">Параметры плана не найдены. Вернитесь на страницу тарифов.</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right */}
|
||||
<div className="lg:col-span-1">
|
||||
<div className="bg-white rounded-xl shadow-md p-6 sticky top-4">
|
||||
<div className="flex items-center gap-2 mb-6">
|
||||
<FiShoppingCart className="text-ospab-primary text-xl" />
|
||||
<h2 className="text-xl font-bold text-gray-800">Итого</h2>
|
||||
</div>
|
||||
|
||||
<div className="bg-gradient-to-br from-ospab-primary to-ospab-accent rounded-lg p-4 mb-6 text-white">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<FiDollarSign className="text-lg" />
|
||||
<p className="text-white/80 text-sm">Баланс</p>
|
||||
</div>
|
||||
<p className="text-2xl font-bold mb-3">₽{balance.toFixed(2)}</p>
|
||||
<button
|
||||
onClick={() => navigate('/dashboard/billing')}
|
||||
className="w-full bg-white/20 hover:bg-white/30 px-4 py-2 rounded-lg transition-colors text-sm font-semibold"
|
||||
>Пополнить баланс</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 mb-6">
|
||||
<div>
|
||||
<p className="text-sm text-gray-500 mb-1">План</p>
|
||||
{meta ? (
|
||||
<div className="bg-gray-50 rounded-lg p-3">
|
||||
<p className="font-semibold text-gray-800 mb-1">{meta.title}</p>
|
||||
<p className="text-sm text-gray-600">₽{planPrice}/мес</p>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-gray-400 text-sm">Не выбран</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="text-sm text-gray-500 mb-1">Имя бакета</p>
|
||||
{bucketName ? (
|
||||
<div className="bg-gray-50 rounded-lg p-3">
|
||||
<p className="font-semibold text-gray-800">{bucketName}</p>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-gray-400 text-sm">Не указано</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{planName && (
|
||||
<div className="pt-4 border-t border-gray-200">
|
||||
<div className="space-y-2 mb-3 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-600">Стоимость:</span>
|
||||
<span className="font-semibold">₽{planPrice}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-600">Баланс:</span>
|
||||
<span className="font-semibold">₽{balance.toFixed(2)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-between pt-3 border-t border-gray-200">
|
||||
<span className="text-gray-800 font-semibold">Остаток:</span>
|
||||
<span className={`font-bold text-lg ${balance - planPrice >= 0 ? 'text-green-600' : 'text-red-600'}`}>₽{(balance - planPrice).toFixed(2)}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleCreate}
|
||||
disabled={!canCreate() || loading}
|
||||
className={`w-full py-3 rounded-lg font-bold flex items-center justify-center gap-2 transition-colors ${
|
||||
!canCreate() || loading ? 'bg-gray-300 text-gray-500 cursor-not-allowed' : 'bg-ospab-primary text-white hover:bg-ospab-primary/90 shadow-lg hover:shadow-xl'
|
||||
}`}
|
||||
>
|
||||
{loading ? (<><div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div><span>Создание...</span></>) : (<><FiShoppingCart /><span>Создать бакет</span></>)}
|
||||
</button>
|
||||
{!canCreate() && (
|
||||
<p className="text-xs text-gray-500 text-center mt-3">Заполните имя бакета, выберите план и убедитесь в достаточном балансе</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
className="bg-ospab-primary text-white px-6 py-2 rounded font-bold w-full"
|
||||
onClick={handleBuy}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? 'Покупка...' : 'Купить сервер'}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import axios from 'axios';
|
||||
import apiClient from '../../utils/apiClient';
|
||||
import { API_URL } from '../../config/api';
|
||||
|
||||
interface IUser {
|
||||
@@ -25,18 +25,48 @@ const CheckVerification: React.FC = () => {
|
||||
const [actionLoading, setActionLoading] = useState<number | null>(null);
|
||||
const [error, setError] = useState<string>('');
|
||||
|
||||
// Получить защищённый URL для файла чека
|
||||
const getCheckFileUrl = (fileUrl: string): string => {
|
||||
const filename = fileUrl.split('/').pop();
|
||||
return `${API_URL}/api/check/file/${filename}`;
|
||||
};
|
||||
|
||||
// Открыть изображение чека в новом окне с авторизацией
|
||||
const openCheckImage = async (fileUrl: string) => {
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const url = getCheckFileUrl(fileUrl);
|
||||
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Ошибка загрузки изображения');
|
||||
}
|
||||
|
||||
const blob = await response.blob();
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
window.open(objectUrl, '_blank');
|
||||
} catch (error) {
|
||||
console.error('[CheckVerification] Ошибка загрузки изображения:', error);
|
||||
alert('Не удалось загрузить изображение чека');
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const fetchChecks = async (): Promise<void> => {
|
||||
console.log('[CheckVerification] Загрузка чеков для проверки...');
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const res = await axios.get<ICheck[]>(`${API_URL}/api/check`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
withCredentials: true,
|
||||
});
|
||||
const res = await apiClient.get<ICheck[]>(`${API_URL}/api/check`);
|
||||
setChecks(res.data);
|
||||
} catch {
|
||||
console.log('[CheckVerification] Загружено чеков:', res.data.length);
|
||||
} catch (err) {
|
||||
console.error('[CheckVerification] Ошибка загрузки чеков:', err);
|
||||
setError('Ошибка загрузки чеков');
|
||||
setChecks([]);
|
||||
}
|
||||
@@ -46,35 +76,41 @@ const CheckVerification: React.FC = () => {
|
||||
}, []);
|
||||
|
||||
const handleAction = async (checkId: number, action: 'approve' | 'reject'): Promise<void> => {
|
||||
console.log(`[CheckVerification] ${action === 'approve' ? 'Подтверждение' : 'Отклонение'} чека #${checkId}`);
|
||||
setActionLoading(checkId);
|
||||
setError('');
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
await axios.post(`${API_URL}/api/check/${action}`, { checkId }, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
withCredentials: true,
|
||||
});
|
||||
setChecks((prevChecks: ICheck[]) => prevChecks.map((c: ICheck) => c.id === checkId ? { ...c, status: action === 'approve' ? 'approved' : 'rejected' } : c));
|
||||
await apiClient.post(`${API_URL}/api/check/${action}`, { checkId });
|
||||
|
||||
console.log(`[CheckVerification] Чек #${checkId} ${action === 'approve' ? 'подтверждён' : 'отклонён'}`);
|
||||
|
||||
setChecks((prevChecks: ICheck[]) =>
|
||||
prevChecks.map((c: ICheck) =>
|
||||
c.id === checkId ? { ...c, status: action === 'approve' ? 'approved' : 'rejected' } : c
|
||||
)
|
||||
);
|
||||
|
||||
// Если подтверждение — обновить баланс пользователя
|
||||
if (action === 'approve') {
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
const userRes = await axios.get(`${API_URL}/api/auth/me`, { headers });
|
||||
console.log('[CheckVerification] Обновление данных пользователя...');
|
||||
const userRes = await apiClient.get(`${API_URL}/api/auth/me`);
|
||||
|
||||
// Глобально обновить userData через типизированное событие (для Dashboard)
|
||||
window.dispatchEvent(new CustomEvent<import('./types').UserData>('userDataUpdate', {
|
||||
detail: {
|
||||
user: userRes.data.user,
|
||||
balance: userRes.data.user.balance ?? 0,
|
||||
servers: userRes.data.user.servers ?? [],
|
||||
tickets: userRes.data.user.tickets ?? [],
|
||||
}
|
||||
}));
|
||||
console.log('[CheckVerification] Данные пользователя обновлены');
|
||||
} catch (error) {
|
||||
console.error('Ошибка обновления userData:', error);
|
||||
console.error('[CheckVerification] Ошибка обновления userData:', error);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(`[CheckVerification] Ошибка ${action === 'approve' ? 'подтверждения' : 'отклонения'}:`, err);
|
||||
setError('Ошибка действия');
|
||||
}
|
||||
setActionLoading(null);
|
||||
@@ -108,9 +144,16 @@ const CheckVerification: React.FC = () => {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col items-center gap-2 md:ml-8">
|
||||
<a href={`${API_URL}${check.fileUrl}`} target="_blank" rel="noopener noreferrer" className="block mb-2">
|
||||
<img src={`${API_URL}${check.fileUrl}`} alt="Чек" className="w-32 h-32 object-contain rounded-xl border" />
|
||||
</a>
|
||||
<button
|
||||
onClick={() => openCheckImage(check.fileUrl)}
|
||||
className="block mb-2 cursor-pointer hover:opacity-80 transition-opacity"
|
||||
>
|
||||
<div className="w-32 h-32 flex items-center justify-center bg-gray-200 rounded-xl border">
|
||||
<span className="text-gray-600 text-sm text-center px-2">
|
||||
Нажмите для просмотра чека
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
{check.status === 'pending' && (
|
||||
<>
|
||||
<button
|
||||
|
||||
@@ -1,31 +1,34 @@
|
||||
// frontend/src/pages/dashboard/mainpage.tsx
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useContext } from 'react';
|
||||
import { Routes, Route, Link, useNavigate, useLocation } from 'react-router-dom';
|
||||
import axios from 'axios';
|
||||
import { isAxiosError } from 'axios';
|
||||
import apiClient from '../../utils/apiClient';
|
||||
import AuthContext from '../../context/authcontext';
|
||||
import { useContext } from 'react';
|
||||
|
||||
// Импортируем компоненты для вкладок
|
||||
import Summary from './summary';
|
||||
import Servers from './servers';
|
||||
import ServerPanel from './serverpanel';
|
||||
import TicketsPage from './tickets';
|
||||
import Billing from './billing';
|
||||
import Settings from './settings';
|
||||
import Notifications from './notificatons';
|
||||
import NotificationsPage from './notifications';
|
||||
import CheckVerification from './checkverification';
|
||||
import TicketResponse from './ticketresponse';
|
||||
import Checkout from './checkout';
|
||||
import TariffsPage from '../tariffs';
|
||||
import StoragePage from './storage';
|
||||
import AdminPanel from './admin';
|
||||
import BlogAdmin from './blogadmin';
|
||||
import BlogEditor from './blogeditor';
|
||||
|
||||
// Новые компоненты для тикетов
|
||||
import TicketDetailPage from './tickets/detail';
|
||||
import NewTicketPage from './tickets/new';
|
||||
|
||||
const Dashboard = () => {
|
||||
const [userData, setUserData] = useState<import('./types').UserData | null>(null);
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState<boolean>(false);
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const { logout } = useContext(AuthContext);
|
||||
const { userData, setUserData, logout, refreshUser, isInitialized } = useContext(AuthContext);
|
||||
|
||||
const [activeTab, setActiveTab] = useState('summary');
|
||||
|
||||
@@ -46,17 +49,10 @@ const Dashboard = () => {
|
||||
navigate('/login');
|
||||
return;
|
||||
}
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
const userRes = await axios.get('https://ospab.host:5000/api/auth/me', { headers });
|
||||
setUserData({
|
||||
user: userRes.data.user,
|
||||
balance: userRes.data.user.balance ?? 0,
|
||||
servers: userRes.data.user.servers ?? [],
|
||||
tickets: userRes.data.user.tickets ?? [],
|
||||
});
|
||||
await refreshUser();
|
||||
} catch (err) {
|
||||
console.error('Ошибка загрузки данных:', err);
|
||||
if (axios.isAxiosError(err) && err.response?.status === 401) {
|
||||
if (isAxiosError(err) && err.response?.status === 401) {
|
||||
logout();
|
||||
navigate('/login');
|
||||
}
|
||||
@@ -72,12 +68,10 @@ const Dashboard = () => {
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
if (!token) return;
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
const userRes = await axios.get('https://ospab.host:5000/api/auth/me', { headers });
|
||||
const userRes = await apiClient.get('/api/auth/me');
|
||||
setUserData({
|
||||
user: userRes.data.user,
|
||||
balance: userRes.data.user.balance ?? 0,
|
||||
servers: userRes.data.user.servers ?? [],
|
||||
tickets: userRes.data.user.tickets ?? [],
|
||||
});
|
||||
} catch (err) {
|
||||
@@ -102,7 +96,7 @@ const Dashboard = () => {
|
||||
const isOperator = userData?.user?.operator === 1;
|
||||
const isAdmin = userData?.user?.isAdmin === true;
|
||||
|
||||
if (loading) {
|
||||
if (!isInitialized || loading) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<span className="text-gray-500 text-lg">Загрузка...</span>
|
||||
@@ -113,7 +107,7 @@ const Dashboard = () => {
|
||||
// Вкладки для сайдбара
|
||||
const tabs = [
|
||||
{ key: 'summary', label: 'Сводка', to: '/dashboard' },
|
||||
{ key: 'servers', label: 'Серверы', to: '/dashboard/servers' },
|
||||
{ key: 'storage', label: 'Хранилище', to: '/dashboard/storage' },
|
||||
{ key: 'tickets', label: 'Тикеты', to: '/dashboard/tickets' },
|
||||
{ key: 'billing', label: 'Баланс', to: '/dashboard/billing' },
|
||||
{ key: 'settings', label: 'Настройки', to: '/dashboard/settings' },
|
||||
@@ -125,7 +119,8 @@ const Dashboard = () => {
|
||||
];
|
||||
|
||||
const superAdminTabs = [
|
||||
{ key: 'admin', label: '👑 Админ-панель', to: '/dashboard/admin' },
|
||||
{ key: 'admin', label: 'Админ-панель', to: '/dashboard/admin' },
|
||||
{ key: 'blogadmin', label: 'Блог', to: '/dashboard/blogadmin' },
|
||||
];
|
||||
|
||||
return (
|
||||
@@ -163,7 +158,7 @@ const Dashboard = () => {
|
||||
)}
|
||||
{isAdmin && (
|
||||
<span className="inline-block px-2 py-1 bg-red-100 text-red-800 text-xs font-semibold rounded-full">
|
||||
👑 Супер Админ
|
||||
Супер Админ
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
@@ -260,19 +255,21 @@ const Dashboard = () => {
|
||||
</div>
|
||||
<div className="flex-1 p-4 lg:p-8 pt-6 lg:pt-12 overflow-x-hidden">
|
||||
<Routes>
|
||||
<Route path="/" element={<Summary userData={userData ?? { user: { username: '', operator: 0 }, balance: 0, servers: [], tickets: [] }} />} />
|
||||
<Route path="servers" element={<Servers />} />
|
||||
<Route path="server/:id" element={<ServerPanel />} />
|
||||
<Route path="checkout" element={<Checkout onSuccess={() => navigate('/dashboard')} />} />
|
||||
<Route path="tariffs" element={<TariffsPage />} />
|
||||
<Route path="/" element={<Summary userData={userData ?? { user: { username: '', operator: 0 }, balance: 0, tickets: [] }} />} />
|
||||
<Route path="storage" element={<StoragePage />} />
|
||||
<Route path="checkout" element={<Checkout onSuccess={() => navigate('/dashboard/storage')} />} />
|
||||
{userData && (
|
||||
<Route path="tickets" element={<TicketsPage setUserData={setUserData} />} />
|
||||
<>
|
||||
<Route path="tickets" element={<TicketsPage setUserData={setUserData} />} />
|
||||
<Route path="tickets/:id" element={<TicketDetailPage />} />
|
||||
<Route path="tickets/new" element={<NewTicketPage />} />
|
||||
</>
|
||||
)}
|
||||
{userData && (
|
||||
<Route path="billing" element={<Billing />} />
|
||||
)}
|
||||
<Route path="settings" element={<Settings />} />
|
||||
<Route path="notifications" element={<Notifications />} />
|
||||
<Route path="notifications" element={<NotificationsPage />} />
|
||||
{isOperator && (
|
||||
<>
|
||||
<Route path="checkverification" element={<CheckVerification />} />
|
||||
@@ -280,7 +277,12 @@ const Dashboard = () => {
|
||||
</>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<Route path="admin" element={<AdminPanel />} />
|
||||
<>
|
||||
<Route path="admin" element={<AdminPanel />} />
|
||||
<Route path="blogadmin" element={<BlogAdmin />} />
|
||||
<Route path="blogeditor" element={<BlogEditor />} />
|
||||
<Route path="blogeditor/:postId" element={<BlogEditor />} />
|
||||
</>
|
||||
)}
|
||||
</Routes>
|
||||
</div>
|
||||
|
||||
364
ospabhost/frontend/src/pages/dashboard/notifications.tsx
Normal file
364
ospabhost/frontend/src/pages/dashboard/notifications.tsx
Normal file
@@ -0,0 +1,364 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import {
|
||||
getNotifications,
|
||||
markAsRead,
|
||||
markAllAsRead,
|
||||
deleteNotification,
|
||||
deleteAllRead,
|
||||
requestPushPermission,
|
||||
type Notification
|
||||
} from '../../services/notificationService';
|
||||
|
||||
const NotificationsPage = () => {
|
||||
const [notifications, setNotifications] = useState<Notification[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [filter, setFilter] = useState<'all' | 'unread'>('all');
|
||||
const [pushEnabled, setPushEnabled] = useState(false);
|
||||
const [pushPermission, setPushPermission] = useState<NotificationPermission>('default');
|
||||
|
||||
const checkPushPermission = () => {
|
||||
if ('Notification' in window) {
|
||||
const permission = Notification.permission;
|
||||
setPushPermission(permission);
|
||||
setPushEnabled(permission === 'granted');
|
||||
}
|
||||
};
|
||||
|
||||
const loadNotifications = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await getNotifications({
|
||||
page: 1,
|
||||
limit: 50,
|
||||
unreadOnly: filter === 'unread'
|
||||
});
|
||||
// Проверяем, что response имеет правильную структуру
|
||||
if (response && Array.isArray(response.notifications)) {
|
||||
setNotifications(response.notifications);
|
||||
} else {
|
||||
console.error('Неверный формат ответа от сервера:', response);
|
||||
setNotifications([]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки уведомлений:', error);
|
||||
setNotifications([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [filter]);
|
||||
|
||||
useEffect(() => {
|
||||
loadNotifications();
|
||||
checkPushPermission();
|
||||
}, [loadNotifications]);
|
||||
|
||||
const handleMarkAsRead = async (id: number) => {
|
||||
try {
|
||||
await markAsRead(id);
|
||||
setNotifications((prev) =>
|
||||
prev.map((n) => (n.id === id ? { ...n, isRead: true } : n))
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Ошибка пометки прочитанным:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleMarkAllAsRead = async () => {
|
||||
try {
|
||||
await markAllAsRead();
|
||||
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
|
||||
} catch (error) {
|
||||
console.error('Ошибка пометки всех прочитанными:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
try {
|
||||
await deleteNotification(id);
|
||||
setNotifications((prev) => prev.filter((n) => n.id !== id));
|
||||
} catch (error) {
|
||||
console.error('Ошибка удаления уведомления:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteAllRead = async () => {
|
||||
if (!window.confirm('Удалить все прочитанные уведомления?')) return;
|
||||
|
||||
try {
|
||||
await deleteAllRead();
|
||||
setNotifications((prev) => prev.filter((n) => !n.isRead));
|
||||
} catch (error) {
|
||||
console.error('Ошибка удаления прочитанных:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEnablePush = async () => {
|
||||
const success = await requestPushPermission();
|
||||
if (success) {
|
||||
setPushEnabled(true);
|
||||
setPushPermission('granted');
|
||||
alert('Push-уведомления успешно подключены!');
|
||||
} else {
|
||||
alert('Не удалось подключить Push-уведомления. Проверьте разрешения браузера.');
|
||||
// Обновляем состояние на случай, если пользователь отклонил
|
||||
checkPushPermission();
|
||||
}
|
||||
};
|
||||
|
||||
const formatDate = (dateString: string) => {
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleString('ru-RU', {
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
};
|
||||
|
||||
const groupNotificationsByDate = (notifications: Notification[]) => {
|
||||
const now = new Date();
|
||||
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
const yesterday = new Date(today);
|
||||
yesterday.setDate(yesterday.getDate() - 1);
|
||||
const weekAgo = new Date(today);
|
||||
weekAgo.setDate(weekAgo.getDate() - 7);
|
||||
|
||||
const groups: Record<string, Notification[]> = {
|
||||
'Сегодня': [],
|
||||
'Вчера': [],
|
||||
'За последние 7 дней': [],
|
||||
'Ранее': []
|
||||
};
|
||||
|
||||
notifications.forEach((notification) => {
|
||||
const notifDate = new Date(notification.createdAt);
|
||||
const notifDay = new Date(notifDate.getFullYear(), notifDate.getMonth(), notifDate.getDate());
|
||||
|
||||
if (notifDay.getTime() === today.getTime()) {
|
||||
groups['Сегодня'].push(notification);
|
||||
} else if (notifDay.getTime() === yesterday.getTime()) {
|
||||
groups['Вчера'].push(notification);
|
||||
} else if (notifDate >= weekAgo) {
|
||||
groups['За последние 7 дней'].push(notification);
|
||||
} else {
|
||||
groups['Ранее'].push(notification);
|
||||
}
|
||||
});
|
||||
|
||||
return groups;
|
||||
};
|
||||
|
||||
const unreadCount = notifications.filter((n) => !n.isRead).length;
|
||||
const groupedNotifications = groupNotificationsByDate(notifications);
|
||||
|
||||
return (
|
||||
<div className="p-4 lg:p-8">
|
||||
<div className="max-w-4xl mx-auto">
|
||||
<h1 className="text-3xl font-bold text-gray-900 mb-6">Уведомления</h1>
|
||||
|
||||
{/* Панель действий */}
|
||||
<div className="bg-white rounded-lg shadow-sm p-4 mb-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
{/* Фильтры */}
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => setFilter('all')}
|
||||
className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
|
||||
filter === 'all'
|
||||
? 'bg-ospab-primary text-white'
|
||||
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
|
||||
}`}
|
||||
>
|
||||
Все ({notifications.length})
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setFilter('unread')}
|
||||
className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
|
||||
filter === 'unread'
|
||||
? 'bg-ospab-primary text-white'
|
||||
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
|
||||
}`}
|
||||
>
|
||||
Непрочитанные ({unreadCount})
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Действия */}
|
||||
<div className="flex gap-2">
|
||||
{unreadCount > 0 && (
|
||||
<button
|
||||
onClick={handleMarkAllAsRead}
|
||||
className="px-4 py-2 rounded-md text-sm font-medium bg-blue-100 text-blue-700 hover:bg-blue-200 transition-colors"
|
||||
>
|
||||
Прочитать все
|
||||
</button>
|
||||
)}
|
||||
{notifications.some((n) => n.isRead) && (
|
||||
<button
|
||||
onClick={handleDeleteAllRead}
|
||||
className="px-4 py-2 rounded-md text-sm font-medium bg-red-100 text-red-700 hover:bg-red-200 transition-colors"
|
||||
>
|
||||
Удалить прочитанные
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Push-уведомления */}
|
||||
{!pushEnabled && 'Notification' in window && pushPermission !== 'denied' && (
|
||||
<div className="mt-4 p-4 bg-blue-50 border border-blue-200 rounded-md flex items-start gap-3">
|
||||
<svg className="w-6 h-6 text-blue-600 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
|
||||
</svg>
|
||||
<div className="flex-1">
|
||||
<h3 className="text-sm font-semibold text-blue-900 mb-1">
|
||||
Подключите Push-уведомления
|
||||
</h3>
|
||||
<p className="text-sm text-blue-700 mb-3">
|
||||
Получайте мгновенные уведомления на компьютер или телефон при важных событиях
|
||||
</p>
|
||||
<button
|
||||
onClick={handleEnablePush}
|
||||
className="px-4 py-2 rounded-md text-sm font-medium bg-blue-600 text-white hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
Включить уведомления
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Уведомления заблокированы */}
|
||||
{pushPermission === 'denied' && (
|
||||
<div className="mt-4 p-4 bg-red-50 border border-red-200 rounded-md flex items-start gap-3">
|
||||
<svg className="w-6 h-6 text-red-600 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
|
||||
</svg>
|
||||
<div className="flex-1">
|
||||
<h3 className="text-sm font-semibold text-red-900 mb-1">
|
||||
Push-уведомления заблокированы
|
||||
</h3>
|
||||
<p className="text-sm text-red-700">
|
||||
Вы заблокировали уведомления для этого сайта. Чтобы включить их, разрешите уведомления в настройках браузера.
|
||||
</p>
|
||||
<p className="text-xs text-red-600 mt-2">
|
||||
Chrome/Edge: Нажмите на иконку замка слева от адресной строки → Уведомления → Разрешить<br/>
|
||||
Firefox: Настройки → Приватность и защита → Разрешения → Уведомления → Настройки
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Список уведомлений */}
|
||||
{loading ? (
|
||||
<div className="flex justify-center items-center py-12">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-ospab-primary"></div>
|
||||
</div>
|
||||
) : notifications.length === 0 ? (
|
||||
<div className="bg-white rounded-lg shadow-sm p-12 text-center">
|
||||
<svg className="mx-auto h-16 w-16 text-gray-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
|
||||
</svg>
|
||||
<h3 className="text-lg font-medium text-gray-900 mb-2">Нет уведомлений</h3>
|
||||
<p className="text-gray-600">
|
||||
{filter === 'unread' ? 'Все уведомления прочитаны' : 'У вас пока нет уведомлений'}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-6">
|
||||
{Object.entries(groupedNotifications).map(([groupName, groupNotifications]) => {
|
||||
if (groupNotifications.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div key={groupName}>
|
||||
<h2 className="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-3">
|
||||
{groupName}
|
||||
</h2>
|
||||
<div className="space-y-2">
|
||||
{groupNotifications.map((notification) => (
|
||||
<div
|
||||
key={notification.id}
|
||||
className={`bg-white rounded-lg shadow-sm border-l-4 overflow-hidden transition-all ${
|
||||
notification.isRead ? 'border-transparent' : 'border-ospab-primary'
|
||||
}`}
|
||||
>
|
||||
<div className="p-4">
|
||||
<div className="flex items-start gap-4">
|
||||
{/* Цветовой индикатор */}
|
||||
<div className={`flex-shrink-0 w-3 h-3 rounded-full mt-2 ${
|
||||
notification.color === 'green' ? 'bg-green-500' :
|
||||
notification.color === 'blue' ? 'bg-blue-500' :
|
||||
notification.color === 'orange' ? 'bg-orange-500' :
|
||||
notification.color === 'red' ? 'bg-red-500' :
|
||||
notification.color === 'purple' ? 'bg-purple-500' :
|
||||
'bg-gray-500'
|
||||
}`}></div>
|
||||
|
||||
{/* Контент */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex-1">
|
||||
<h3 className={`text-base font-semibold ${notification.isRead ? 'text-gray-800' : 'text-gray-900'}`}>
|
||||
{notification.title}
|
||||
</h3>
|
||||
<p className="text-gray-600 mt-1">
|
||||
{notification.message}
|
||||
</p>
|
||||
<p className="text-sm text-gray-400 mt-2">
|
||||
{formatDate(notification.createdAt)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Действия */}
|
||||
<div className="flex gap-2">
|
||||
{!notification.isRead && (
|
||||
<button
|
||||
onClick={() => handleMarkAsRead(notification.id)}
|
||||
className="p-2 text-gray-400 hover:text-blue-600 transition-colors"
|
||||
title="Пометить прочитанным"
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => handleDelete(notification.id)}
|
||||
className="p-2 text-gray-400 hover:text-red-600 transition-colors"
|
||||
title="Удалить"
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Ссылка для перехода */}
|
||||
{notification.actionUrl && (
|
||||
<Link
|
||||
to={notification.actionUrl}
|
||||
className="inline-block mt-3 text-sm text-ospab-primary hover:underline"
|
||||
>
|
||||
Перейти →
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default NotificationsPage;
|
||||
@@ -1,41 +0,0 @@
|
||||
const notificationsList = [
|
||||
{
|
||||
title: "Создание сервера",
|
||||
description: "Вы получите уведомление при успешном создании нового сервера или контейнера.",
|
||||
},
|
||||
{
|
||||
title: "Списание оплаты за месяц",
|
||||
description: "Напоминание о предстоящем списании средств за продление тарифа.",
|
||||
},
|
||||
{
|
||||
title: "Истечение срока действия тарифа",
|
||||
description: "Уведомление о необходимости продлить тариф, чтобы избежать отключения.",
|
||||
},
|
||||
{
|
||||
title: "Ответ на тикет",
|
||||
description: "Вы получите уведомление, когда оператор ответит на ваш тикет поддержки.",
|
||||
},
|
||||
{
|
||||
title: "Поступление оплаты",
|
||||
description: "Уведомление о зачислении средств на ваш баланс.",
|
||||
},
|
||||
];
|
||||
|
||||
const Notifications = () => {
|
||||
return (
|
||||
<div className="p-8 bg-white rounded-3xl shadow-xl max-w-xl mx-auto mt-6">
|
||||
<h2 className="text-2xl font-bold mb-6">Типы уведомлений</h2>
|
||||
<ul className="space-y-6">
|
||||
{notificationsList.map((n, idx) => (
|
||||
<li key={idx} className="bg-gray-50 border border-gray-200 rounded-xl p-4">
|
||||
<div className="font-semibold text-lg text-ospab-primary mb-1">{n.title}</div>
|
||||
<div className="text-gray-700 text-sm">{n.description}</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="text-gray-400 text-sm mt-8">Настройка каналов уведомлений (email, Telegram) появится позже.</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Notifications;
|
||||
@@ -3,7 +3,7 @@ import { useParams, useNavigate } from 'react-router-dom';
|
||||
import axios from 'axios';
|
||||
import { API_URL } from '../../config/api';
|
||||
import { Modal } from '../../components/Modal';
|
||||
import { useToast } from '../../components/Toast';
|
||||
import { useToast } from '../../hooks/useToast';
|
||||
|
||||
interface ServerData {
|
||||
id: number;
|
||||
@@ -222,7 +222,7 @@ const ServerPanel: React.FC = () => {
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="text-blue-600 hover:text-blue-800"
|
||||
>
|
||||
{showPassword ? '👁️' : '👁️🗨️'}
|
||||
{showPassword ? 'Скрыть' : 'Показать'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -238,7 +238,7 @@ const ServerPanel: React.FC = () => {
|
||||
)}
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-600">Автопродление:</span>
|
||||
<span>{server.autoRenew ? '✅ Включено' : '❌ Выключено'}</span>
|
||||
<span>{server.autoRenew ? 'Включено' : 'Выключено'}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -288,14 +288,14 @@ const ServerPanel: React.FC = () => {
|
||||
disabled={actionLoading || server.status === 'running'}
|
||||
className="px-4 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition"
|
||||
>
|
||||
▶️ Запустить
|
||||
Запустить
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleAction('stop')}
|
||||
disabled={actionLoading || server.status === 'stopped'}
|
||||
className="px-4 py-3 bg-gray-600 text-white rounded-lg hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed transition"
|
||||
>
|
||||
⏹️ Остановить
|
||||
Остановить
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleAction('restart')}
|
||||
@@ -325,7 +325,7 @@ const ServerPanel: React.FC = () => {
|
||||
|
||||
{/* Danger Zone */}
|
||||
<div className="bg-red-50 border border-red-200 rounded-lg p-6">
|
||||
<h2 className="text-xl font-semibold text-red-800 mb-4">⚠️ Опасная зона</h2>
|
||||
<h2 className="text-xl font-semibold text-red-800 mb-4">Опасная зона</h2>
|
||||
<p className="text-red-700 mb-4">
|
||||
Удаление сервера - необратимое действие. Все данные будут утеряны!
|
||||
</p>
|
||||
@@ -334,7 +334,7 @@ const ServerPanel: React.FC = () => {
|
||||
disabled={actionLoading}
|
||||
className="px-6 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed transition"
|
||||
>
|
||||
🗑️ Удалить сервер
|
||||
Удалить сервер
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -1,174 +0,0 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import axios from 'axios';
|
||||
import { API_URL } from '../../config/api';
|
||||
|
||||
interface Server {
|
||||
id: number;
|
||||
status: string;
|
||||
createdAt: string;
|
||||
ipAddress: string | null;
|
||||
tariff: {
|
||||
name: string;
|
||||
price: number;
|
||||
};
|
||||
os: {
|
||||
name: string;
|
||||
};
|
||||
nextPaymentDate: string | null;
|
||||
autoRenew: boolean;
|
||||
}
|
||||
|
||||
const Servers: React.FC = () => {
|
||||
const [servers, setServers] = useState<Server[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
loadServers();
|
||||
}, []);
|
||||
|
||||
const loadServers = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
|
||||
const response = await axios.get(`${API_URL}/api/auth/me`, { headers });
|
||||
setServers(response.data.user.servers || []);
|
||||
setError(null);
|
||||
} catch (err: any) {
|
||||
console.error('Ошибка загрузки серверов:', err);
|
||||
setError('Не удалось загрузить список серверов');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusColor = (status: string) => {
|
||||
switch (status) {
|
||||
case 'running':
|
||||
return 'bg-green-100 text-green-800';
|
||||
case 'stopped':
|
||||
return 'bg-gray-100 text-gray-800';
|
||||
case 'creating':
|
||||
return 'bg-blue-100 text-blue-800';
|
||||
case 'suspended':
|
||||
return 'bg-red-100 text-red-800';
|
||||
default:
|
||||
return 'bg-gray-100 text-gray-800';
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusText = (status: string) => {
|
||||
switch (status) {
|
||||
case 'running':
|
||||
return 'Работает';
|
||||
case 'stopped':
|
||||
return 'Остановлен';
|
||||
case 'creating':
|
||||
return 'Создаётся';
|
||||
case 'suspended':
|
||||
return 'Приостановлен';
|
||||
default:
|
||||
return status;
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-screen">
|
||||
<div className="text-xl text-gray-600">Загрузка...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h1 className="text-3xl font-bold text-gray-800">Мои серверы</h1>
|
||||
<Link
|
||||
to="/dashboard/checkout"
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition"
|
||||
>
|
||||
+ Купить сервер
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg">
|
||||
<p className="text-red-800">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{servers.length === 0 ? (
|
||||
<div className="bg-white rounded-lg shadow p-8 text-center">
|
||||
<div className="text-gray-400 text-6xl mb-4">🖥️</div>
|
||||
<h2 className="text-2xl font-semibold text-gray-700 mb-2">
|
||||
У вас пока нет серверов
|
||||
</h2>
|
||||
<p className="text-gray-600 mb-6">
|
||||
Купите свой первый сервер, чтобы начать работу
|
||||
</p>
|
||||
<Link
|
||||
to="/dashboard/checkout"
|
||||
className="inline-block px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition"
|
||||
>
|
||||
Выбрать тариф
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{servers.map((server) => (
|
||||
<div
|
||||
key={server.id}
|
||||
className="bg-white rounded-lg shadow hover:shadow-lg transition p-6"
|
||||
>
|
||||
<div className="flex justify-between items-start mb-4">
|
||||
<div>
|
||||
<h3 className="text-xl font-semibold text-gray-800">
|
||||
Сервер #{server.id}
|
||||
</h3>
|
||||
<span className={`inline-block px-2 py-1 rounded text-xs font-medium mt-2 ${getStatusColor(server.status)}`}>
|
||||
{getStatusText(server.status)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 mb-4 text-sm text-gray-600">
|
||||
<p>
|
||||
<span className="font-medium">Тариф:</span> {server.tariff.name}
|
||||
</p>
|
||||
<p>
|
||||
<span className="font-medium">ОС:</span> {server.os.name}
|
||||
</p>
|
||||
<p>
|
||||
<span className="font-medium">IP:</span> {server.ipAddress || 'Н/Д'}
|
||||
</p>
|
||||
{server.nextPaymentDate && (
|
||||
<p>
|
||||
<span className="font-medium">След. платёж:</span>{' '}
|
||||
{new Date(server.nextPaymentDate).toLocaleDateString('ru-RU')}
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
<span className="font-medium">Автопродление:</span>{' '}
|
||||
{server.autoRenew ? '✅ Включено' : '❌ Выключено'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Link
|
||||
to={`/dashboard/server/${server.id}`}
|
||||
className="block w-full text-center px-4 py-2 bg-gray-800 text-white rounded-lg hover:bg-gray-900 transition"
|
||||
>
|
||||
Управление
|
||||
</Link>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Servers;
|
||||
436
ospabhost/frontend/src/pages/dashboard/settings-old-backup.tsx
Normal file
436
ospabhost/frontend/src/pages/dashboard/settings-old-backup.tsx
Normal file
@@ -0,0 +1,436 @@
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import axios from "axios";
|
||||
import { API_URL } from "../../config/api";
|
||||
import { Modal } from "../../components/Modal";
|
||||
import { useToast } from "../../hooks/useToast";
|
||||
|
||||
interface AccountInfo {
|
||||
id: number;
|
||||
email: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
const Settings = () => {
|
||||
const { addToast } = useToast();
|
||||
const [tab, setTab] = useState<'password' | 'username' | 'delete'>('password');
|
||||
const [accountInfo, setAccountInfo] = useState<AccountInfo | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
|
||||
|
||||
// Password change states
|
||||
const [currentPassword, setCurrentPassword] = useState("");
|
||||
const [newPassword, setNewPassword] = useState("");
|
||||
const [confirmPassword, setConfirmPassword] = useState("");
|
||||
const [passwordCode, setPasswordCode] = useState("");
|
||||
const [passwordCodeSent, setPasswordCodeSent] = useState(false);
|
||||
|
||||
// Username change states
|
||||
const [newUsername, setNewUsername] = useState("");
|
||||
const [usernameCode, setUsernameCode] = useState("");
|
||||
const [usernameCodeSent, setUsernameCodeSent] = useState(false);
|
||||
|
||||
// Delete account states
|
||||
const [deleteCode, setDeleteCode] = useState("");
|
||||
const [deleteCodeSent, setDeleteCodeSent] = useState(false);
|
||||
|
||||
const [message, setMessage] = useState<{ text: string; type: 'success' | 'error' } | null>(null);
|
||||
|
||||
const showMessage = useCallback((text: string, type: 'success' | 'error') => {
|
||||
setMessage({ text, type });
|
||||
setTimeout(() => setMessage(null), 5000);
|
||||
}, []);
|
||||
|
||||
const fetchAccountInfo = useCallback(async () => {
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const response = await axios.get(`${API_URL}/api/account/info`, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
setAccountInfo(response.data);
|
||||
} catch (error) {
|
||||
const err = error as { response?: { data?: { error?: string } } };
|
||||
showMessage(err.response?.data?.error || 'Ошибка загрузки данных', 'error');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [showMessage]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchAccountInfo();
|
||||
}, [fetchAccountInfo]);
|
||||
|
||||
// Password change handlers
|
||||
const handleRequestPasswordChange = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (newPassword !== confirmPassword) {
|
||||
showMessage('Пароли не совпадают', 'error');
|
||||
return;
|
||||
}
|
||||
if (newPassword.length < 6) {
|
||||
showMessage('Пароль должен быть не менее 6 символов', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
await axios.post(`${API_URL}/api/account/password/request`, {
|
||||
currentPassword,
|
||||
newPassword
|
||||
}, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
setPasswordCodeSent(true);
|
||||
showMessage('Код отправлен на вашу почту', 'success');
|
||||
} catch (error) {
|
||||
const err = error as { response?: { data?: { error?: string } } };
|
||||
showMessage(err.response?.data?.error || 'Ошибка отправки кода', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const handleConfirmPasswordChange = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
await axios.post(`${API_URL}/api/account/password/confirm`, {
|
||||
code: passwordCode
|
||||
}, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
showMessage('Пароль успешно изменён', 'success');
|
||||
setPasswordCodeSent(false);
|
||||
setCurrentPassword("");
|
||||
setNewPassword("");
|
||||
setConfirmPassword("");
|
||||
setPasswordCode("");
|
||||
} catch (error) {
|
||||
const err = error as { response?: { data?: { error?: string } } };
|
||||
showMessage(err.response?.data?.error || 'Неверный код', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
// Username change handlers
|
||||
const handleRequestUsernameChange = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (newUsername.length < 3 || newUsername.length > 20) {
|
||||
showMessage('Имя должно быть от 3 до 20 символов', 'error');
|
||||
return;
|
||||
}
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(newUsername)) {
|
||||
showMessage('Имя может содержать только буквы, цифры, _ и -', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
await axios.post(`${API_URL}/api/account/username/request`, {
|
||||
newUsername
|
||||
}, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
setUsernameCodeSent(true);
|
||||
showMessage('Код отправлен на вашу почту', 'success');
|
||||
} catch (error) {
|
||||
const err = error as { response?: { data?: { error?: string } } };
|
||||
showMessage(err.response?.data?.error || 'Ошибка отправки кода', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const handleConfirmUsernameChange = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
await axios.post(`${API_URL}/api/account/username/confirm`, {
|
||||
code: usernameCode
|
||||
}, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
showMessage('Имя успешно изменено', 'success');
|
||||
setUsernameCodeSent(false);
|
||||
setNewUsername("");
|
||||
setUsernameCode("");
|
||||
await fetchAccountInfo();
|
||||
} catch (error) {
|
||||
const err = error as { response?: { data?: { error?: string } } };
|
||||
showMessage(err.response?.data?.error || 'Неверный код', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
// Delete account handlers
|
||||
const handleRequestAccountDeletion = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setShowDeleteConfirm(true);
|
||||
};
|
||||
|
||||
const confirmAccountDeletion = async () => {
|
||||
setShowDeleteConfirm(false);
|
||||
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
await axios.post(`${API_URL}/api/account/delete/request`, {}, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
setDeleteCodeSent(true);
|
||||
addToast('Код отправлен на вашу почту', 'success');
|
||||
} catch (error) {
|
||||
const err = error as { response?: { data?: { error?: string } } };
|
||||
addToast(err.response?.data?.error || 'Ошибка отправки кода', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const handleConfirmAccountDeletion = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
await axios.post(`${API_URL}/api/account/delete/confirm`, {
|
||||
code: deleteCode
|
||||
}, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
showMessage('Аккаунт удалён', 'success');
|
||||
localStorage.removeItem('access_token');
|
||||
setTimeout(() => {
|
||||
window.location.href = '/';
|
||||
}, 2000);
|
||||
} catch (error) {
|
||||
const err = error as { response?: { data?: { error?: string } } };
|
||||
showMessage(err.response?.data?.error || 'Неверный код', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="p-4 lg:p-8 bg-white rounded-3xl shadow-xl max-w-2xl mx-auto mt-6">
|
||||
<p className="text-center text-gray-500">Загрузка...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-4 lg:p-8 bg-white rounded-3xl shadow-xl max-w-2xl mx-auto mt-6">
|
||||
<h2 className="text-xl lg:text-2xl font-bold mb-4 lg:mb-6">Настройки аккаунта</h2>
|
||||
|
||||
{message && (
|
||||
<div className={`mb-4 p-3 rounded-lg ${message.type === 'success' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
|
||||
{message.text}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{accountInfo && (
|
||||
<div className="mb-6 p-4 bg-gray-50 rounded-lg">
|
||||
<p className="text-sm text-gray-600">Email: <span className="font-semibold text-gray-900">{accountInfo.email}</span></p>
|
||||
<p className="text-sm text-gray-600 mt-1">Имя: <span className="font-semibold text-gray-900">{accountInfo.username}</span></p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col sm:flex-row sm:space-x-2 space-y-2 sm:space-y-0 mb-6">
|
||||
<button
|
||||
type="button"
|
||||
className={`px-4 py-2 rounded-lg font-semibold text-sm lg:text-base ${tab === 'password' ? 'bg-ospab-primary text-white' : 'bg-gray-100 text-gray-700'}`}
|
||||
onClick={() => setTab('password')}
|
||||
>
|
||||
Смена пароля
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`px-4 py-2 rounded-lg font-semibold text-sm lg:text-base ${tab === 'username' ? 'bg-ospab-primary text-white' : 'bg-gray-100 text-gray-700'}`}
|
||||
onClick={() => setTab('username')}
|
||||
>
|
||||
Смена имени
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`px-4 py-2 rounded-lg font-semibold text-sm lg:text-base ${tab === 'delete' ? 'bg-red-600 text-white' : 'bg-gray-100 text-gray-700'}`}
|
||||
onClick={() => setTab('delete')}
|
||||
>
|
||||
Удалить аккаунт
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{tab === 'password' && (
|
||||
<div>
|
||||
{!passwordCodeSent ? (
|
||||
<form onSubmit={handleRequestPasswordChange} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-gray-700 mb-2 text-sm lg:text-base">Текущий пароль</label>
|
||||
<input
|
||||
type="password"
|
||||
value={currentPassword}
|
||||
onChange={e => setCurrentPassword(e.target.value)}
|
||||
className="w-full px-4 py-2 border rounded-lg text-sm lg:text-base"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-gray-700 mb-2 text-sm lg:text-base">Новый пароль (минимум 6 символов)</label>
|
||||
<input
|
||||
type="password"
|
||||
value={newPassword}
|
||||
onChange={e => setNewPassword(e.target.value)}
|
||||
className="w-full px-4 py-2 border rounded-lg text-sm lg:text-base"
|
||||
required
|
||||
minLength={6}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-gray-700 mb-2 text-sm lg:text-base">Подтвердите новый пароль</label>
|
||||
<input
|
||||
type="password"
|
||||
value={confirmPassword}
|
||||
onChange={e => setConfirmPassword(e.target.value)}
|
||||
className="w-full px-4 py-2 border rounded-lg text-sm lg:text-base"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<button type="submit" className="w-full lg:w-auto bg-ospab-primary text-white px-6 py-2 rounded-lg font-bold text-sm lg:text-base">
|
||||
Отправить код на почту
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<form onSubmit={handleConfirmPasswordChange} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-gray-700 mb-2 text-sm lg:text-base">Введите код из письма</label>
|
||||
<input
|
||||
type="text"
|
||||
value={passwordCode}
|
||||
onChange={e => setPasswordCode(e.target.value)}
|
||||
className="w-full px-4 py-2 border rounded-lg text-sm lg:text-base"
|
||||
placeholder="123456"
|
||||
required
|
||||
maxLength={6}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col sm:flex-row space-y-2 sm:space-y-0 sm:space-x-4">
|
||||
<button type="submit" className="w-full sm:w-auto bg-ospab-primary text-white px-6 py-2 rounded-lg font-bold text-sm lg:text-base">
|
||||
Подтвердить
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPasswordCodeSent(false)}
|
||||
className="w-full sm:w-auto bg-gray-300 text-gray-700 px-6 py-2 rounded-lg font-bold text-sm lg:text-base"
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tab === 'username' && (
|
||||
<div>
|
||||
{!usernameCodeSent ? (
|
||||
<form onSubmit={handleRequestUsernameChange} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-gray-700 mb-2 text-sm lg:text-base">Новое имя пользователя</label>
|
||||
<input
|
||||
type="text"
|
||||
value={newUsername}
|
||||
onChange={e => setNewUsername(e.target.value)}
|
||||
className="w-full px-4 py-2 border rounded-lg text-sm lg:text-base"
|
||||
placeholder={accountInfo?.username}
|
||||
required
|
||||
minLength={3}
|
||||
maxLength={20}
|
||||
pattern="[a-zA-Z0-9_-]+"
|
||||
/>
|
||||
<p className="text-xs text-gray-500 mt-1">От 3 до 20 символов, только буквы, цифры, _ и -</p>
|
||||
</div>
|
||||
<button type="submit" className="w-full lg:w-auto bg-ospab-primary text-white px-6 py-2 rounded-lg font-bold text-sm lg:text-base">
|
||||
Отправить код на почту
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<form onSubmit={handleConfirmUsernameChange} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-gray-700 mb-2 text-sm lg:text-base">Введите код из письма</label>
|
||||
<input
|
||||
type="text"
|
||||
value={usernameCode}
|
||||
onChange={e => setUsernameCode(e.target.value)}
|
||||
className="w-full px-4 py-2 border rounded-lg text-sm lg:text-base"
|
||||
placeholder="123456"
|
||||
required
|
||||
maxLength={6}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col sm:flex-row space-y-2 sm:space-y-0 sm:space-x-4">
|
||||
<button type="submit" className="w-full sm:w-auto bg-ospab-primary text-white px-6 py-2 rounded-lg font-bold text-sm lg:text-base">
|
||||
Подтвердить
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setUsernameCodeSent(false)}
|
||||
className="w-full sm:w-auto bg-gray-300 text-gray-700 px-6 py-2 rounded-lg font-bold text-sm lg:text-base"
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tab === 'delete' && (
|
||||
<div>
|
||||
{!deleteCodeSent ? (
|
||||
<form onSubmit={handleRequestAccountDeletion} className="space-y-4">
|
||||
<div className="p-4 bg-red-50 border border-red-200 rounded-lg">
|
||||
<p className="text-red-700 font-semibold mb-2">Внимание!</p>
|
||||
<p className="text-red-600 text-sm">Удаление аккаунта приведёт к безвозвратному удалению всех ваших данных: серверов, тикетов, чеков и уведомлений.</p>
|
||||
</div>
|
||||
<button type="submit" className="w-full lg:w-auto bg-red-600 text-white px-6 py-2 rounded-lg font-bold text-sm lg:text-base">
|
||||
Удалить аккаунт
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<form onSubmit={handleConfirmAccountDeletion} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-gray-700 mb-2 text-sm lg:text-base">Введите код из письма для подтверждения</label>
|
||||
<input
|
||||
type="text"
|
||||
value={deleteCode}
|
||||
onChange={e => setDeleteCode(e.target.value)}
|
||||
className="w-full px-4 py-2 border rounded-lg text-sm lg:text-base"
|
||||
placeholder="123456"
|
||||
required
|
||||
maxLength={6}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col sm:flex-row space-y-2 sm:space-y-0 sm:space-x-4">
|
||||
<button type="submit" className="w-full sm:w-auto bg-red-600 text-white px-6 py-2 rounded-lg font-bold text-sm lg:text-base">
|
||||
Подтвердить удаление
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDeleteCodeSent(false)}
|
||||
className="w-full sm:w-auto bg-gray-300 text-gray-700 px-6 py-2 rounded-lg font-bold text-sm lg:text-base"
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Модальное окно подтверждения удаления аккаунта */}
|
||||
<Modal
|
||||
isOpen={showDeleteConfirm}
|
||||
onClose={() => setShowDeleteConfirm(false)}
|
||||
title="Удаление аккаунта"
|
||||
type="danger"
|
||||
onConfirm={confirmAccountDeletion}
|
||||
confirmText="Да, удалить аккаунт"
|
||||
cancelText="Отмена"
|
||||
>
|
||||
<p className="font-bold text-red-600 mb-2">ВЫ УВЕРЕНЫ?</p>
|
||||
<p>Это действие необратимо!</p>
|
||||
<p className="mt-2 text-sm text-gray-600">
|
||||
После подтверждения на вашу почту будет отправлен код для финального подтверждения удаления.
|
||||
</p>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Settings;
|
||||
File diff suppressed because it is too large
Load Diff
281
ospabhost/frontend/src/pages/dashboard/settings/sessions.tsx
Normal file
281
ospabhost/frontend/src/pages/dashboard/settings/sessions.tsx
Normal file
@@ -0,0 +1,281 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import apiClient from '../../../utils/apiClient';
|
||||
|
||||
interface Session {
|
||||
id: number;
|
||||
device: string;
|
||||
browser: string;
|
||||
ipAddress: string;
|
||||
location: string;
|
||||
lastActivity: string;
|
||||
createdAt: string;
|
||||
isCurrent: boolean;
|
||||
}
|
||||
|
||||
interface LoginHistory {
|
||||
id: number;
|
||||
ipAddress: string;
|
||||
userAgent: string;
|
||||
success: boolean;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
const SessionsPage: React.FC = () => {
|
||||
const [sessions, setSessions] = useState<Session[]>([]);
|
||||
const [loginHistory, setLoginHistory] = useState<LoginHistory[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [showHistory, setShowHistory] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetchSessions();
|
||||
fetchLoginHistory();
|
||||
}, []);
|
||||
|
||||
const fetchSessions = async () => {
|
||||
try {
|
||||
const response = await apiClient.get('/api/sessions');
|
||||
const sessionsData = Array.isArray(response.data) ? response.data : response.data.sessions;
|
||||
setSessions(sessionsData || []);
|
||||
setLoading(false);
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки сессий:', error);
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const fetchLoginHistory = async () => {
|
||||
try {
|
||||
const response = await apiClient.get('/api/sessions/history', {
|
||||
params: { limit: 20 }
|
||||
});
|
||||
const historyData = Array.isArray(response.data) ? response.data : response.data.history;
|
||||
setLoginHistory(historyData || []);
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки истории входов:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const terminateSession = async (sessionId: number) => {
|
||||
if (!confirm('Вы уверены, что хотите завершить эту сессию?')) return;
|
||||
|
||||
try {
|
||||
await apiClient.delete(`/api/sessions/${sessionId}`);
|
||||
fetchSessions();
|
||||
} catch (error) {
|
||||
console.error('Ошибка завершения сессии:', error);
|
||||
alert('Не удалось завершить сессию');
|
||||
}
|
||||
};
|
||||
|
||||
const terminateAllOthers = async () => {
|
||||
if (!confirm('Вы уверены, что хотите завершить все остальные сессии?')) return;
|
||||
|
||||
try {
|
||||
await apiClient.delete('/api/sessions/others/all');
|
||||
fetchSessions();
|
||||
alert('Все остальные сессии завершены');
|
||||
} catch (error) {
|
||||
console.error('Ошибка завершения сессий:', error);
|
||||
alert('Не удалось завершить сессии');
|
||||
}
|
||||
};
|
||||
|
||||
const getDeviceIcon = (device: string) => {
|
||||
switch (device.toLowerCase()) {
|
||||
case 'mobile':
|
||||
return '📱';
|
||||
case 'tablet':
|
||||
return '📱';
|
||||
case 'desktop':
|
||||
default:
|
||||
return '💻';
|
||||
}
|
||||
};
|
||||
|
||||
const formatRelativeTime = (dateString: string) => {
|
||||
const date = new Date(dateString);
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - date.getTime();
|
||||
const diffMins = Math.floor(diffMs / 60000);
|
||||
const diffHours = Math.floor(diffMs / 3600000);
|
||||
const diffDays = Math.floor(diffMs / 86400000);
|
||||
|
||||
if (diffMins < 1) return 'только что';
|
||||
if (diffMins < 60) return `${diffMins} мин. назад`;
|
||||
if (diffHours < 24) return `${diffHours} ч. назад`;
|
||||
if (diffDays < 7) return `${diffDays} дн. назад`;
|
||||
return date.toLocaleDateString('ru-RU');
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto"></div>
|
||||
<p className="mt-4 text-gray-600">Загрузка сессий...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 py-8">
|
||||
<div className="max-w-6xl mx-auto px-4">
|
||||
{/* Header */}
|
||||
<div className="mb-8">
|
||||
<h1 className="text-3xl font-bold text-gray-900 mb-2">Активные сессии</h1>
|
||||
<p className="text-gray-600">Управляйте устройствами, с которых выполнен вход в ваш аккаунт</p>
|
||||
</div>
|
||||
|
||||
{/* Terminate All Button */}
|
||||
{sessions.filter(s => !s.isCurrent).length > 0 && (
|
||||
<div className="mb-6">
|
||||
<button
|
||||
onClick={terminateAllOthers}
|
||||
className="bg-orange-500 hover:bg-orange-600 text-white px-6 py-3 rounded-lg font-medium transition-colors duration-200 flex items-center gap-2"
|
||||
>
|
||||
Завершить все остальные сессии
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Sessions Grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-12">
|
||||
{sessions.map((session) => (
|
||||
<div
|
||||
key={session.id}
|
||||
className={`bg-white rounded-xl shadow-md overflow-hidden transition-all duration-200 hover:shadow-lg ${
|
||||
session.isCurrent ? 'ring-2 ring-green-500' : ''
|
||||
}`}
|
||||
>
|
||||
<div className="p-6">
|
||||
{/* Current Badge */}
|
||||
{session.isCurrent && (
|
||||
<div className="mb-3">
|
||||
<span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800">
|
||||
Текущая сессия
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Device Info */}
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="text-4xl">{getDeviceIcon(session.device)}</div>
|
||||
<div className="flex-1">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-1">
|
||||
{session.browser} · {session.device}
|
||||
</h3>
|
||||
<div className="space-y-1 text-sm text-gray-600">
|
||||
<p className="flex items-center gap-2">
|
||||
<span>{session.ipAddress}</span>
|
||||
</p>
|
||||
<p className="flex items-center gap-2">
|
||||
<span>{session.location}</span>
|
||||
</p>
|
||||
<p className="flex items-center gap-2">
|
||||
<span>Активность: {formatRelativeTime(session.lastActivity)}</span>
|
||||
</p>
|
||||
<p className="flex items-center gap-2 text-gray-500">
|
||||
<span>Вход: {new Date(session.createdAt).toLocaleString('ru-RU')}</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Terminate Button */}
|
||||
{!session.isCurrent && (
|
||||
<div className="mt-4 pt-4 border-t border-gray-200">
|
||||
<button
|
||||
onClick={() => terminateSession(session.id)}
|
||||
className="w-full bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg font-medium transition-colors duration-200"
|
||||
>
|
||||
Завершить сессию
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Login History Section */}
|
||||
<div className="bg-white rounded-xl shadow-md overflow-hidden">
|
||||
<div className="p-6 border-b border-gray-200">
|
||||
<button
|
||||
onClick={() => setShowHistory(!showHistory)}
|
||||
className="w-full flex items-center justify-between text-left"
|
||||
>
|
||||
<div>
|
||||
<h2 className="text-xl font-bold text-gray-900">История входов</h2>
|
||||
<p className="text-sm text-gray-600 mt-1">Последние 20 попыток входа в аккаунт</p>
|
||||
</div>
|
||||
<span className="text-2xl">{showHistory ? '▼' : '▶'}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showHistory && (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Статус
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
IP адрес
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Устройство
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Дата и время
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{loginHistory.map((entry) => (
|
||||
<tr key={entry.id} className={entry.success ? '' : 'bg-red-50'}>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<span
|
||||
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
|
||||
entry.success
|
||||
? 'bg-green-100 text-green-800'
|
||||
: 'bg-red-100 text-red-800'
|
||||
}`}
|
||||
>
|
||||
{entry.success ? 'Успешно' : 'Ошибка'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
|
||||
{entry.ipAddress}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-600">
|
||||
{entry.userAgent.substring(0, 60)}...
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-600">
|
||||
{new Date(entry.createdAt).toLocaleString('ru-RU')}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Security Tips */}
|
||||
<div className="mt-8 bg-blue-50 border border-blue-200 rounded-lg p-6">
|
||||
<h3 className="text-lg font-semibold text-blue-900 mb-3">💡 Советы по безопасности</h3>
|
||||
<ul className="space-y-2 text-sm text-blue-800">
|
||||
<li>• Регулярно проверяйте список активных сессий</li>
|
||||
<li>• Завершайте сессии на устройствах, которыми больше не пользуетесь</li>
|
||||
<li>• Если вы видите подозрительную активность, немедленно завершите все сессии и смените пароль</li>
|
||||
<li>• Используйте надёжные пароли и двухфакторную аутентификацию</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SessionsPage;
|
||||
215
ospabhost/frontend/src/pages/dashboard/storage.tsx
Normal file
215
ospabhost/frontend/src/pages/dashboard/storage.tsx
Normal file
@@ -0,0 +1,215 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { FiDatabase, FiPlus, FiInfo, FiTrash2, FiSettings, FiExternalLink } from 'react-icons/fi';
|
||||
import apiClient from '../../utils/apiClient';
|
||||
import { API_URL } from '../../config/api';
|
||||
|
||||
interface StorageBucket {
|
||||
id: number;
|
||||
name: string;
|
||||
plan: string;
|
||||
quotaGb: number;
|
||||
usedBytes: number;
|
||||
objectCount: number;
|
||||
storageClass: string;
|
||||
region: string;
|
||||
public: boolean;
|
||||
versioning: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
const StoragePage: React.FC = () => {
|
||||
const [buckets, setBuckets] = useState<StorageBucket[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
fetchBuckets();
|
||||
}, []);
|
||||
|
||||
const fetchBuckets = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const res = await apiClient.get(`${API_URL}/api/storage/buckets`);
|
||||
setBuckets(res.data.buckets || []);
|
||||
} catch (e) {
|
||||
console.error('Ошибка загрузки бакетов', e);
|
||||
setError('Не удалось загрузить список хранилищ');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const formatBytes = (bytes: number): string => {
|
||||
if (bytes === 0) return '0 B';
|
||||
const k = 1024;
|
||||
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
|
||||
};
|
||||
|
||||
const getUsagePercent = (usedBytes: number, quotaGb: number): number => {
|
||||
const quotaBytes = quotaGb * 1024 * 1024 * 1024;
|
||||
return quotaBytes > 0 ? Math.min((usedBytes / quotaBytes) * 100, 100) : 0;
|
||||
};
|
||||
|
||||
const getPlanColor = (plan: string): string => {
|
||||
const colors: Record<string, string> = {
|
||||
basic: 'text-blue-600 bg-blue-50',
|
||||
standard: 'text-green-600 bg-green-50',
|
||||
plus: 'text-purple-600 bg-purple-50',
|
||||
pro: 'text-orange-600 bg-orange-50',
|
||||
enterprise: 'text-red-600 bg-red-50'
|
||||
};
|
||||
return colors[plan] || 'text-gray-600 bg-gray-50';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-7xl mx-auto">
|
||||
{/* Header */}
|
||||
<div className="mb-6 flex items-center justify-between flex-wrap gap-4">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-800 flex items-center gap-2">
|
||||
<FiDatabase className="text-ospab-primary" />
|
||||
S3 Хранилище
|
||||
</h1>
|
||||
<p className="text-gray-600 mt-1">Управление вашими объектными хранилищами</p>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<button
|
||||
onClick={() => navigate('/tariffs')}
|
||||
className="px-5 py-2.5 bg-white border-2 border-ospab-primary text-ospab-primary rounded-lg font-semibold hover:bg-ospab-primary hover:text-white transition-all flex items-center gap-2"
|
||||
>
|
||||
<FiInfo />
|
||||
Тарифы
|
||||
</button>
|
||||
<button
|
||||
onClick={() => navigate('/tariffs')}
|
||||
className="px-5 py-2.5 bg-ospab-primary text-white rounded-lg font-semibold hover:bg-ospab-primary/90 shadow-lg transition-all flex items-center gap-2"
|
||||
>
|
||||
<FiPlus />
|
||||
Создать бакет
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-50 border border-red-200 rounded-xl p-4 mb-6 text-red-700">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<div className="flex justify-center items-center h-64">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-ospab-primary"></div>
|
||||
</div>
|
||||
) : buckets.length === 0 ? (
|
||||
<div className="bg-white rounded-xl shadow-md p-12 text-center">
|
||||
<FiDatabase className="text-6xl text-gray-300 mx-auto mb-4" />
|
||||
<h3 className="text-xl font-bold text-gray-800 mb-2">Нет активных хранилищ</h3>
|
||||
<p className="text-gray-600 mb-6">Создайте ваш первый S3 бакет для хранения файлов, резервных копий и медиа-контента</p>
|
||||
<button
|
||||
onClick={() => navigate('/tariffs')}
|
||||
className="px-6 py-3 bg-ospab-primary text-white rounded-lg font-semibold hover:bg-ospab-primary/90 shadow-lg transition-all inline-flex items-center gap-2"
|
||||
>
|
||||
<FiPlus />
|
||||
Выбрать тариф
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{buckets.map((bucket) => {
|
||||
const usagePercent = getUsagePercent(bucket.usedBytes, bucket.quotaGb);
|
||||
return (
|
||||
<div key={bucket.id} className="bg-white rounded-xl shadow-md hover:shadow-lg transition-shadow">
|
||||
<div className="p-6 border-b border-gray-100">
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="bg-ospab-primary/10 p-3 rounded-lg">
|
||||
<FiDatabase className="text-ospab-primary text-xl" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-bold text-gray-800">{bucket.name}</h3>
|
||||
<span className={`inline-block px-2 py-1 text-xs font-semibold rounded-full ${getPlanColor(bucket.plan)}`}>
|
||||
{bucket.plan}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<button className="p-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
|
||||
<FiSettings />
|
||||
</button>
|
||||
<button className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors">
|
||||
<FiTrash2 />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Usage bar */}
|
||||
<div className="mb-4">
|
||||
<div className="flex justify-between text-sm text-gray-600 mb-1">
|
||||
<span>Использовано: {formatBytes(bucket.usedBytes)}</span>
|
||||
<span>Квота: {bucket.quotaGb} GB</span>
|
||||
</div>
|
||||
<div className="w-full bg-gray-200 rounded-full h-2">
|
||||
<div
|
||||
className={`h-2 rounded-full transition-all ${
|
||||
usagePercent > 90 ? 'bg-red-500' : usagePercent > 70 ? 'bg-yellow-500' : 'bg-green-500'
|
||||
}`}
|
||||
style={{ width: `${usagePercent}%` }}
|
||||
></div>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-1">{usagePercent.toFixed(1)}% использовано</p>
|
||||
</div>
|
||||
|
||||
{/* Stats */}
|
||||
<div className="grid grid-cols-3 gap-4 mb-4">
|
||||
<div className="text-center">
|
||||
<p className="text-2xl font-bold text-ospab-primary">{bucket.objectCount}</p>
|
||||
<p className="text-xs text-gray-500">Объектов</p>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<p className="text-sm font-semibold text-gray-700">{bucket.region}</p>
|
||||
<p className="text-xs text-gray-500">Регион</p>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<p className="text-sm font-semibold text-gray-700">{bucket.storageClass}</p>
|
||||
<p className="text-xs text-gray-500">Класс</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Badges */}
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
{bucket.public && (
|
||||
<span className="inline-flex items-center px-2 py-1 bg-blue-100 text-blue-700 text-xs font-semibold rounded-full">
|
||||
Публичный
|
||||
</span>
|
||||
)}
|
||||
{bucket.versioning && (
|
||||
<span className="inline-flex items-center px-2 py-1 bg-purple-100 text-purple-700 text-xs font-semibold rounded-full">
|
||||
Версионирование
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="px-6 py-4 bg-gray-50 flex justify-between items-center">
|
||||
<p className="text-xs text-gray-500">
|
||||
Создан: {new Date(bucket.createdAt).toLocaleDateString('ru-RU')}
|
||||
</p>
|
||||
<button className="text-ospab-primary hover:text-ospab-primary/80 font-semibold text-sm flex items-center gap-1">
|
||||
Открыть <FiExternalLink />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default StoragePage;
|
||||
@@ -1,35 +1,27 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
import type { UserData, Ticket, Server } from './types';
|
||||
import type { UserData, Ticket } from './types';
|
||||
|
||||
interface SummaryProps {
|
||||
userData: UserData;
|
||||
}
|
||||
|
||||
const Summary = ({ userData }: SummaryProps) => {
|
||||
// Фильтрация открытых тикетов и активных серверов
|
||||
// Фильтрация открытых тикетов
|
||||
const openTickets = Array.isArray(userData.tickets)
|
||||
? userData.tickets.filter((t: Ticket) => t.status !== 'closed')
|
||||
: [];
|
||||
const activeServers = Array.isArray(userData.servers)
|
||||
? userData.servers.filter((s: Server) => s.status === 'active')
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="p-4 lg:p-8 bg-white rounded-2xl lg:rounded-3xl shadow-xl">
|
||||
<h2 className="text-2xl lg:text-3xl font-bold text-gray-800 mb-4 lg:mb-6">Сводка по аккаунту</h2>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 lg:gap-6 mb-6 lg:mb-8">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 lg:gap-6 mb-6 lg:mb-8">
|
||||
<div className="bg-gray-100 p-4 lg:p-6 rounded-xl lg:rounded-2xl flex flex-col items-start">
|
||||
<p className="text-lg lg:text-xl font-medium text-gray-700">Баланс:</p>
|
||||
<p className="text-3xl lg:text-4xl font-extrabold text-ospab-primary mt-2 break-words">₽ {userData.balance?.toFixed ? userData.balance.toFixed(2) : Number(userData.balance).toFixed(2)}</p>
|
||||
<Link to="/dashboard/billing" className="text-sm text-gray-500 hover:underline mt-2">Пополнить баланс →</Link>
|
||||
</div>
|
||||
<div className="bg-gray-100 p-4 lg:p-6 rounded-xl lg:rounded-2xl flex flex-col items-start">
|
||||
<p className="text-lg lg:text-xl font-medium text-gray-700">Активные серверы:</p>
|
||||
<p className="text-3xl lg:text-4xl font-extrabold text-gray-800 mt-2">{activeServers.length}</p>
|
||||
<Link to="/dashboard/servers" className="text-sm text-gray-500 hover:underline mt-2">Управлять →</Link>
|
||||
</div>
|
||||
<div className="bg-gray-100 p-4 lg:p-6 rounded-xl lg:rounded-2xl flex flex-col items-start md:col-span-2 lg:col-span-1">
|
||||
<p className="text-lg lg:text-xl font-medium text-gray-700">Открытые тикеты:</p>
|
||||
<p className="text-3xl lg:text-4xl font-extrabold text-gray-800 mt-2">{openTickets.length}</p>
|
||||
<Link to="/dashboard/tickets" className="text-sm text-gray-500 hover:underline mt-2">Служба поддержки →</Link>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import axios from 'axios';
|
||||
import apiClient from '../../utils/apiClient';
|
||||
|
||||
interface Response {
|
||||
id: number;
|
||||
@@ -31,16 +31,9 @@ const TicketResponse: React.FC = () => {
|
||||
const fetchTickets = async () => {
|
||||
setError('');
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const res = await axios.get('https://ospab.host:5000/api/ticket', {
|
||||
withCredentials: true,
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {}
|
||||
});
|
||||
if (Array.isArray(res.data)) {
|
||||
setTickets(res.data);
|
||||
} else {
|
||||
setTickets([]);
|
||||
}
|
||||
const res = await apiClient.get('/api/ticket');
|
||||
const data = Array.isArray(res.data) ? res.data : res.data?.tickets;
|
||||
setTickets(data || []);
|
||||
} catch {
|
||||
setError('Ошибка загрузки тикетов');
|
||||
setTickets([]);
|
||||
@@ -51,13 +44,9 @@ const TicketResponse: React.FC = () => {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
await axios.post('https://ospab.host:5000/api/ticket/respond', {
|
||||
await apiClient.post('/api/ticket/respond', {
|
||||
ticketId,
|
||||
message: responseMsg[ticketId]
|
||||
}, {
|
||||
withCredentials: true,
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {}
|
||||
});
|
||||
setResponseMsg(prev => ({ ...prev, [ticketId]: '' }));
|
||||
fetchTickets();
|
||||
@@ -73,11 +62,7 @@ const TicketResponse: React.FC = () => {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
await axios.post('https://ospab.host:5000/api/ticket/close', { ticketId }, {
|
||||
withCredentials: true,
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {}
|
||||
});
|
||||
await apiClient.post('/api/ticket/close', { ticketId });
|
||||
fetchTickets();
|
||||
} catch {
|
||||
setError('Ошибка закрытия тикета');
|
||||
|
||||
@@ -1,217 +1,282 @@
|
||||
import type { UserData, Ticket } from './types';
|
||||
import type { UserData } from './types';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import useAuth from '../../context/useAuth';
|
||||
import axios from 'axios';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import apiClient from '../../utils/apiClient';
|
||||
|
||||
// Глобальный логгер ошибок для axios
|
||||
axios.interceptors.response.use(
|
||||
response => response,
|
||||
error => {
|
||||
if (error.response) {
|
||||
console.error('Ошибка ответа:', error.response.data);
|
||||
} else if (error.request) {
|
||||
console.error('Нет ответа от сервера:', error.request);
|
||||
} else {
|
||||
console.error('Ошибка запроса:', error.message);
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
interface Ticket {
|
||||
id: number;
|
||||
title: string;
|
||||
message: string;
|
||||
status: string;
|
||||
priority: string;
|
||||
category: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
responses?: Response[];
|
||||
assignedTo?: number;
|
||||
closedAt?: string;
|
||||
}
|
||||
|
||||
interface Response {
|
||||
id: number;
|
||||
message: string;
|
||||
isInternal: boolean;
|
||||
createdAt: string;
|
||||
userId: number;
|
||||
user: {
|
||||
username: string;
|
||||
operator: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
type TicketsPageProps = {
|
||||
setUserData: (data: UserData) => void;
|
||||
};
|
||||
|
||||
const TicketsPage: React.FC<TicketsPageProps> = ({ setUserData }) => {
|
||||
const { user } = useAuth() as { user?: { username: string; operator?: number } };
|
||||
const TicketsPage: React.FC<TicketsPageProps> = () => {
|
||||
const navigate = useNavigate();
|
||||
const [tickets, setTickets] = useState<Ticket[]>([]);
|
||||
const [title, setTitle] = useState('');
|
||||
const [message, setMessage] = useState('');
|
||||
const [formError, setFormError] = useState('');
|
||||
const [formSuccess, setFormSuccess] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [responseMsg, setResponseMsg] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [filters, setFilters] = useState({
|
||||
status: 'all',
|
||||
category: 'all',
|
||||
priority: 'all'
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
fetchTickets();
|
||||
}, []);
|
||||
fetchTickets();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [filters]);
|
||||
|
||||
const fetchTickets = async () => {
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const res = await axios.get('https://ospab.host:5000/api/ticket', {
|
||||
withCredentials: true,
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {}
|
||||
});
|
||||
if (Array.isArray(res.data)) {
|
||||
setTickets(res.data);
|
||||
} else {
|
||||
setTickets([]);
|
||||
}
|
||||
} catch {
|
||||
const params: Record<string, string> = {};
|
||||
|
||||
if (filters.status !== 'all') params.status = filters.status;
|
||||
if (filters.category !== 'all') params.category = filters.category;
|
||||
if (filters.priority !== 'all') params.priority = filters.priority;
|
||||
|
||||
const response = await apiClient.get('/api/ticket', { params });
|
||||
|
||||
setTickets(response.data.tickets || response.data || []);
|
||||
setLoading(false);
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки тикетов:', error);
|
||||
setTickets([]);
|
||||
}
|
||||
};
|
||||
|
||||
const updateUserData = async () => {
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
if (!token) return;
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
const userRes = await axios.get('https://ospab.host:5000/api/auth/me', { headers });
|
||||
setUserData({
|
||||
user: userRes.data.user,
|
||||
balance: userRes.data.user.balance ?? 0,
|
||||
servers: userRes.data.user.servers ?? [],
|
||||
tickets: userRes.data.user.tickets ?? [],
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Ошибка обновления userData после тикета:', err);
|
||||
}
|
||||
};
|
||||
|
||||
const createTicket = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setFormError('');
|
||||
setFormSuccess('');
|
||||
if (!title.trim() || !message.trim()) {
|
||||
setFormError('Заполните тему и сообщение');
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
await axios.post('https://ospab.host:5000/api/ticket/create', { title, message }, {
|
||||
withCredentials: true,
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {}
|
||||
});
|
||||
setTitle('');
|
||||
setMessage('');
|
||||
setFormSuccess('Тикет успешно создан!');
|
||||
fetchTickets();
|
||||
await updateUserData();
|
||||
} catch {
|
||||
setFormError('Ошибка создания тикета');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const respondTicket = async (ticketId: number) => {
|
||||
const token = localStorage.getItem('access_token');
|
||||
await axios.post('https://ospab.host:5000/api/ticket/respond', { ticketId, message: responseMsg }, {
|
||||
withCredentials: true,
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {}
|
||||
});
|
||||
setResponseMsg('');
|
||||
fetchTickets();
|
||||
await updateUserData();
|
||||
const getStatusBadge = (status: string) => {
|
||||
const badges: Record<string, { color: string; text: string; emoji: string }> = {
|
||||
open: { color: 'bg-green-100 text-green-800', text: 'Открыт', emoji: '🟢' },
|
||||
in_progress: { color: 'bg-blue-100 text-blue-800', text: 'В работе', emoji: '🔵' },
|
||||
awaiting_reply: { color: 'bg-yellow-100 text-yellow-800', text: 'Ожидает ответа', emoji: '🟡' },
|
||||
resolved: { color: 'bg-purple-100 text-purple-800', text: 'Решён', emoji: '🟣' },
|
||||
closed: { color: 'bg-gray-100 text-gray-800', text: 'Закрыт', emoji: '⚪' }
|
||||
};
|
||||
|
||||
const badge = badges[status] || badges.open;
|
||||
|
||||
return (
|
||||
<span className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-medium ${badge.color}`}>
|
||||
<span>{badge.emoji}</span>
|
||||
<span>{badge.text}</span>
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
const closeTicket = async (ticketId: number) => {
|
||||
const token = localStorage.getItem('access_token');
|
||||
await axios.post('https://ospab.host:5000/api/ticket/close', { ticketId }, {
|
||||
withCredentials: true,
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {}
|
||||
});
|
||||
fetchTickets();
|
||||
await updateUserData();
|
||||
const getPriorityBadge = (priority: string) => {
|
||||
const badges: Record<string, { color: string; text: string; emoji: string }> = {
|
||||
urgent: { color: 'bg-red-100 text-red-800 border-red-300', text: 'Срочно', emoji: '🔴' },
|
||||
high: { color: 'bg-orange-100 text-orange-800 border-orange-300', text: 'Высокий', emoji: '🟠' },
|
||||
normal: { color: 'bg-gray-100 text-gray-800 border-gray-300', text: 'Обычный', emoji: '⚪' },
|
||||
low: { color: 'bg-green-100 text-green-800 border-green-300', text: 'Низкий', emoji: '🟢' }
|
||||
};
|
||||
|
||||
const badge = badges[priority] || badges.normal;
|
||||
|
||||
return (
|
||||
<span className={`inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium border ${badge.color}`}>
|
||||
<span>{badge.emoji}</span>
|
||||
<span>{badge.text}</span>
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
const getCategoryIcon = (category: string) => {
|
||||
const icons: Record<string, string> = {
|
||||
general: '💬',
|
||||
technical: '⚙️',
|
||||
billing: '💰',
|
||||
other: '📝'
|
||||
};
|
||||
|
||||
return icons[category] || icons.general;
|
||||
};
|
||||
|
||||
const formatRelativeTime = (dateString: string) => {
|
||||
const date = new Date(dateString);
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - date.getTime();
|
||||
const diffMins = Math.floor(diffMs / 60000);
|
||||
const diffHours = Math.floor(diffMs / 3600000);
|
||||
const diffDays = Math.floor(diffMs / 86400000);
|
||||
|
||||
if (diffMins < 1) return 'только что';
|
||||
if (diffMins < 60) return `${diffMins} мин. назад`;
|
||||
if (diffHours < 24) return `${diffHours} ч. назад`;
|
||||
if (diffDays < 7) return `${diffDays} дн. назад`;
|
||||
return date.toLocaleDateString('ru-RU');
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto"></div>
|
||||
<p className="mt-4 text-gray-600">Загрузка тикетов...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-8 bg-white rounded-3xl shadow-xl">
|
||||
<h2 className="text-3xl font-bold text-gray-800 mb-6">Мои тикеты</h2>
|
||||
<form onSubmit={createTicket} className="mb-8 max-w-xl bg-gray-50 rounded-2xl shadow p-6 flex flex-col gap-4">
|
||||
<label className="font-semibold text-lg">Тема тикета</label>
|
||||
<input
|
||||
value={title}
|
||||
onChange={e => setTitle(e.target.value)}
|
||||
placeholder="Введите тему..."
|
||||
className="border rounded-xl p-3 focus:outline-blue-400 text-base"
|
||||
/>
|
||||
<label className="font-semibold text-lg">Сообщение</label>
|
||||
<textarea
|
||||
value={message}
|
||||
onChange={e => setMessage(e.target.value)}
|
||||
placeholder="Опишите проблему или вопрос..."
|
||||
className="border rounded-xl p-3 min-h-[80px] resize-y focus:outline-blue-400 text-base"
|
||||
/>
|
||||
{formError && <div className="text-red-500 text-sm">{formError}</div>}
|
||||
{formSuccess && <div className="text-green-600 text-sm">{formSuccess}</div>}
|
||||
<button
|
||||
type="submit"
|
||||
className={`bg-blue-500 text-white px-6 py-3 rounded-xl hover:bg-blue-600 transition text-lg font-semibold ${loading ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? 'Отправка...' : 'Создать тикет'}
|
||||
</button>
|
||||
</form>
|
||||
<div className="space-y-8">
|
||||
{tickets.map(ticket => (
|
||||
<div key={ticket.id} className="border rounded-2xl p-6 shadow flex flex-col">
|
||||
<div className="flex flex-col md:flex-row md:items-center justify-between mb-2">
|
||||
<div className="font-bold text-xl text-blue-900">{ticket.title}</div>
|
||||
<div className="text-sm text-gray-500">Статус: <span className={ticket.status === 'closed' ? 'text-red-600 font-bold' : 'text-green-600 font-bold'}>{ticket.status === 'closed' ? 'Закрыт' : 'Открыт'}</span></div>
|
||||
<div className="min-h-screen bg-gray-50 py-8">
|
||||
<div className="max-w-7xl mx-auto px-4">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between mb-8">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900 mb-2">Тикеты поддержки</h1>
|
||||
<p className="text-gray-600">Управляйте вашими обращениями в службу поддержки</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => navigate('/dashboard/tickets/new')}
|
||||
className="bg-blue-500 hover:bg-blue-600 text-white px-6 py-3 rounded-lg font-medium transition-colors duration-200 flex items-center gap-2"
|
||||
>
|
||||
<span>➕</span>
|
||||
Создать тикет
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="bg-white rounded-xl shadow-md p-6 mb-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
{/* Status Filter */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">Статус</label>
|
||||
<select
|
||||
value={filters.status}
|
||||
onChange={(e) => setFilters({ ...filters, status: e.target.value })}
|
||||
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
>
|
||||
<option value="all">Все статусы</option>
|
||||
<option value="open">Открыт</option>
|
||||
<option value="in_progress">В работе</option>
|
||||
<option value="awaiting_reply">Ожидает ответа</option>
|
||||
<option value="resolved">Решён</option>
|
||||
<option value="closed">Закрыт</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="text-sm text-gray-400 mb-2">Автор: {ticket.user?.username} | {new Date(ticket.createdAt).toLocaleString()}</div>
|
||||
{/* Чат сообщений */}
|
||||
<div className="flex flex-col gap-2 mb-4">
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="bg-blue-100 text-blue-900 px-3 py-2 rounded-xl max-w-xl">
|
||||
<span className="font-semibold">{ticket.user?.username || 'Клиент'}:</span> {ticket.message}
|
||||
</div>
|
||||
</div>
|
||||
{((Array.isArray(ticket.responses) ? ticket.responses : []) as {
|
||||
id: number;
|
||||
operator?: { username?: string };
|
||||
message: string;
|
||||
createdAt: string;
|
||||
}[]).map((r) => (
|
||||
<div key={r.id} className="flex items-start gap-2">
|
||||
<div className="bg-green-100 text-green-900 px-3 py-2 rounded-xl max-w-xl ml-8">
|
||||
<span className="font-semibold">{r.operator?.username || 'Оператор'}:</span> {r.message}
|
||||
<span className="text-gray-400 ml-2 text-xs">{new Date(r.createdAt).toLocaleString()}</span>
|
||||
|
||||
{/* Category Filter */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">Категория</label>
|
||||
<select
|
||||
value={filters.category}
|
||||
onChange={(e) => setFilters({ ...filters, category: e.target.value })}
|
||||
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
>
|
||||
<option value="all">Все категории</option>
|
||||
<option value="general">Общие вопросы</option>
|
||||
<option value="technical">Технические</option>
|
||||
<option value="billing">Биллинг</option>
|
||||
<option value="other">Другое</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Priority Filter */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">Приоритет</label>
|
||||
<select
|
||||
value={filters.priority}
|
||||
onChange={(e) => setFilters({ ...filters, priority: e.target.value })}
|
||||
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
>
|
||||
<option value="all">Все приоритеты</option>
|
||||
<option value="urgent">Срочно</option>
|
||||
<option value="high">Высокий</option>
|
||||
<option value="normal">Обычный</option>
|
||||
<option value="low">Низкий</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tickets Grid */}
|
||||
{tickets.length === 0 ? (
|
||||
<div className="bg-white rounded-xl shadow-md p-12 text-center">
|
||||
<div className="text-6xl mb-4">📭</div>
|
||||
<h3 className="text-xl font-semibold text-gray-900 mb-2">Нет тикетов</h3>
|
||||
<p className="text-gray-600 mb-6">У вас пока нет открытых тикетов поддержки</p>
|
||||
<button
|
||||
onClick={() => navigate('/dashboard/tickets/new')}
|
||||
className="bg-blue-500 hover:bg-blue-600 text-white px-6 py-3 rounded-lg font-medium transition-colors duration-200"
|
||||
>
|
||||
Создать первый тикет
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 gap-6">
|
||||
{tickets.map((ticket) => (
|
||||
<Link
|
||||
key={ticket.id}
|
||||
to={`/dashboard/tickets/${ticket.id}`}
|
||||
className="bg-white rounded-xl shadow-md hover:shadow-lg transition-all duration-200 overflow-hidden"
|
||||
>
|
||||
<div className="p-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-start justify-between mb-4">
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-3 mb-2">
|
||||
<span className="text-2xl">{getCategoryIcon(ticket.category || 'general')}</span>
|
||||
<h3 className="text-xl font-semibold text-gray-900">{ticket.title}</h3>
|
||||
{getPriorityBadge(ticket.priority || 'normal')}
|
||||
</div>
|
||||
<p className="text-gray-600 line-clamp-2">{ticket.message.substring(0, 150)}...</p>
|
||||
</div>
|
||||
<div className="ml-4">
|
||||
{getStatusBadge(ticket.status)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="flex items-center justify-between pt-4 border-t border-gray-200">
|
||||
<div className="flex items-center gap-4 text-sm text-gray-600">
|
||||
<span className="flex items-center gap-1">
|
||||
<span>🕒</span>
|
||||
<span>{formatRelativeTime(ticket.updatedAt)}</span>
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<span>💬</span>
|
||||
<span>{ticket.responses?.length || 0} ответов</span>
|
||||
</span>
|
||||
{ticket.closedAt && (
|
||||
<span className="flex items-center gap-1">
|
||||
<span>🔒</span>
|
||||
<span>Закрыт</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-blue-500 hover:text-blue-600 font-medium">
|
||||
Открыть →
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{/* Форма ответа и кнопка закрытия */}
|
||||
{ticket.status !== 'closed' && (
|
||||
<div className="flex flex-col md:flex-row items-center gap-2 mt-2">
|
||||
{user?.operator === 1 && (
|
||||
<>
|
||||
<input
|
||||
value={responseMsg}
|
||||
onChange={e => setResponseMsg(e.target.value)}
|
||||
placeholder="Ваш ответ..."
|
||||
className="border rounded-xl p-2 flex-1"
|
||||
disabled={loading}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => respondTicket(ticket.id)}
|
||||
className="bg-green-500 text-white px-4 py-2 rounded-xl hover:bg-green-600 transition"
|
||||
disabled={loading || !(responseMsg && responseMsg.trim())}
|
||||
>
|
||||
{loading ? 'Отправка...' : 'Ответить'}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => closeTicket(ticket.id)}
|
||||
className="bg-red-500 text-white px-4 py-2 rounded-xl hover:bg-red-600 transition"
|
||||
disabled={loading}
|
||||
>
|
||||
Закрыть тикет
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{ticket.status === 'closed' && (
|
||||
<div className="text-red-600 font-bold mt-2">Тикет закрыт</div>
|
||||
)}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
278
ospabhost/frontend/src/pages/dashboard/tickets/detail.tsx
Normal file
278
ospabhost/frontend/src/pages/dashboard/tickets/detail.tsx
Normal file
@@ -0,0 +1,278 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useParams, Link } from 'react-router-dom';
|
||||
import apiClient from '../../../utils/apiClient';
|
||||
|
||||
interface Ticket {
|
||||
id: number;
|
||||
title: string;
|
||||
message: string;
|
||||
status: string;
|
||||
priority: string;
|
||||
category: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
closedAt?: string;
|
||||
assignedTo?: number;
|
||||
user: {
|
||||
id: number;
|
||||
username: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface Response {
|
||||
id: number;
|
||||
message: string;
|
||||
isInternal: boolean;
|
||||
createdAt: string;
|
||||
user: {
|
||||
id: number;
|
||||
username: string;
|
||||
operator: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
const TicketDetailPage: React.FC = () => {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const [ticket, setTicket] = useState<Ticket | null>(null);
|
||||
const [responses, setResponses] = useState<Response[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [newMessage, setNewMessage] = useState('');
|
||||
const [sending, setSending] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetchTicket();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [id]);
|
||||
|
||||
const fetchTicket = async () => {
|
||||
try {
|
||||
const response = await apiClient.get(`/api/ticket/${id}`);
|
||||
|
||||
setTicket(response.data.ticket);
|
||||
setResponses(response.data.ticket.responses || []);
|
||||
setLoading(false);
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки тикета:', error);
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const sendResponse = async () => {
|
||||
if (!newMessage.trim()) return;
|
||||
|
||||
setSending(true);
|
||||
try {
|
||||
await apiClient.post('/api/ticket/respond', {
|
||||
ticketId: id,
|
||||
message: newMessage
|
||||
});
|
||||
|
||||
setNewMessage('');
|
||||
fetchTicket();
|
||||
} catch (error) {
|
||||
console.error('Ошибка отправки ответа:', error);
|
||||
alert('Не удалось отправить ответ');
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
};
|
||||
|
||||
const closeTicket = async () => {
|
||||
if (!confirm('Вы уверены, что хотите закрыть этот тикет?')) return;
|
||||
|
||||
try {
|
||||
await apiClient.post('/api/ticket/close', { ticketId: id });
|
||||
|
||||
fetchTicket();
|
||||
alert('Тикет успешно закрыт');
|
||||
} catch (error) {
|
||||
console.error('Ошибка закрытия тикета:', error);
|
||||
alert('Не удалось закрыть тикет');
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusBadge = (status: string) => {
|
||||
const badges: Record<string, { color: string; text: string; emoji: string }> = {
|
||||
open: { color: 'bg-green-100 text-green-800', text: 'Открыт', emoji: '🟢' },
|
||||
in_progress: { color: 'bg-blue-100 text-blue-800', text: 'В работе', emoji: '🔵' },
|
||||
awaiting_reply: { color: 'bg-yellow-100 text-yellow-800', text: 'Ожидает ответа', emoji: '🟡' },
|
||||
resolved: { color: 'bg-purple-100 text-purple-800', text: 'Решён', emoji: '🟣' },
|
||||
closed: { color: 'bg-gray-100 text-gray-800', text: 'Закрыт', emoji: '⚪' }
|
||||
};
|
||||
|
||||
const badge = badges[status] || badges.open;
|
||||
|
||||
return (
|
||||
<span className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-sm font-medium ${badge.color}`}>
|
||||
<span>{badge.emoji}</span>
|
||||
<span>{badge.text}</span>
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
const getPriorityBadge = (priority: string) => {
|
||||
const badges: Record<string, { color: string; text: string }> = {
|
||||
urgent: { color: 'bg-red-100 text-red-800', text: 'Срочно 🔴' },
|
||||
high: { color: 'bg-orange-100 text-orange-800', text: 'Высокий 🟠' },
|
||||
normal: { color: 'bg-gray-100 text-gray-800', text: 'Обычный ⚪' },
|
||||
low: { color: 'bg-green-100 text-green-800', text: 'Низкий 🟢' }
|
||||
};
|
||||
|
||||
const badge = badges[priority] || badges.normal;
|
||||
|
||||
return (
|
||||
<span className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${badge.color}`}>
|
||||
{badge.text}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto"></div>
|
||||
<p className="mt-4 text-gray-600">Загрузка тикета...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!ticket) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<div className="text-center">
|
||||
<div className="text-6xl mb-4">❌</div>
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-2">Тикет не найден</h2>
|
||||
<Link
|
||||
to="/dashboard/tickets"
|
||||
className="text-blue-500 hover:text-blue-600 font-medium"
|
||||
>
|
||||
← Вернуться к списку тикетов
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 py-8">
|
||||
<div className="max-w-4xl mx-auto px-4">
|
||||
{/* Back Button */}
|
||||
<Link
|
||||
to="/dashboard/tickets"
|
||||
className="inline-flex items-center gap-2 text-gray-600 hover:text-gray-900 mb-6 transition-colors"
|
||||
>
|
||||
<span>←</span>
|
||||
<span>Назад к тикетам</span>
|
||||
</Link>
|
||||
|
||||
{/* Ticket Header */}
|
||||
<div className="bg-white rounded-xl shadow-md p-6 mb-6">
|
||||
<div className="flex items-start justify-between mb-4">
|
||||
<div className="flex-1">
|
||||
<h1 className="text-2xl font-bold text-gray-900 mb-2">{ticket.title}</h1>
|
||||
<div className="flex items-center gap-3">
|
||||
{getStatusBadge(ticket.status)}
|
||||
{getPriorityBadge(ticket.priority)}
|
||||
<span className="text-sm text-gray-600">
|
||||
Категория: {ticket.category}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{ticket.status !== 'closed' && (
|
||||
<button
|
||||
onClick={closeTicket}
|
||||
className="bg-gray-500 hover:bg-gray-600 text-white px-4 py-2 rounded-lg font-medium transition-colors duration-200"
|
||||
>
|
||||
Закрыть тикет
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="border-t border-gray-200 pt-4 mt-4">
|
||||
<p className="text-gray-700 whitespace-pre-wrap">{ticket.message}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4 mt-4 text-sm text-gray-600">
|
||||
<span>Создан: {new Date(ticket.createdAt).toLocaleString('ru-RU')}</span>
|
||||
{ticket.closedAt && (
|
||||
<span>Закрыт: {new Date(ticket.closedAt).toLocaleString('ru-RU')}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Responses */}
|
||||
<div className="space-y-4 mb-6">
|
||||
{responses.map((response) => (
|
||||
<div
|
||||
key={response.id}
|
||||
className={`bg-white rounded-xl shadow-md p-6 ${
|
||||
response.isInternal ? 'bg-yellow-50 border-2 border-yellow-200' : ''
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="w-10 h-10 bg-blue-500 rounded-full flex items-center justify-center text-white font-bold">
|
||||
{response.user.username.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<span className="font-semibold text-gray-900">
|
||||
{response.user.username}
|
||||
</span>
|
||||
{response.user.operator && (
|
||||
<span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800">
|
||||
⭐ Оператор
|
||||
</span>
|
||||
)}
|
||||
{response.isInternal && (
|
||||
<span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800">
|
||||
🔒 Внутренний комментарий
|
||||
</span>
|
||||
)}
|
||||
<span className="text-sm text-gray-600">
|
||||
{new Date(response.createdAt).toLocaleString('ru-RU')}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-gray-700 whitespace-pre-wrap">{response.message}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* New Response Form */}
|
||||
{ticket.status !== 'closed' && (
|
||||
<div className="bg-white rounded-xl shadow-md p-6">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-4">Добавить ответ</h3>
|
||||
<textarea
|
||||
value={newMessage}
|
||||
onChange={(e) => setNewMessage(e.target.value)}
|
||||
placeholder="Введите ваш ответ..."
|
||||
className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
|
||||
rows={5}
|
||||
/>
|
||||
<div className="flex items-center justify-end gap-3 mt-4">
|
||||
<button
|
||||
onClick={() => setNewMessage('')}
|
||||
className="px-6 py-2 text-gray-700 hover:text-gray-900 font-medium transition-colors"
|
||||
disabled={sending}
|
||||
>
|
||||
Очистить
|
||||
</button>
|
||||
<button
|
||||
onClick={sendResponse}
|
||||
disabled={sending || !newMessage.trim()}
|
||||
className="bg-blue-500 hover:bg-blue-600 text-white px-6 py-2 rounded-lg font-medium transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{sending ? 'Отправка...' : 'Отправить'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TicketDetailPage;
|
||||
278
ospabhost/frontend/src/pages/dashboard/tickets/index.tsx
Normal file
278
ospabhost/frontend/src/pages/dashboard/tickets/index.tsx
Normal file
@@ -0,0 +1,278 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import apiClient from '../../../utils/apiClient';
|
||||
|
||||
interface Ticket {
|
||||
id: number;
|
||||
title: string;
|
||||
message: string;
|
||||
status: string;
|
||||
priority: string;
|
||||
category: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
responses: Response[];
|
||||
assignedTo?: number;
|
||||
closedAt?: string;
|
||||
}
|
||||
|
||||
interface Response {
|
||||
id: number;
|
||||
message: string;
|
||||
isInternal: boolean;
|
||||
createdAt: string;
|
||||
userId: number;
|
||||
user: {
|
||||
username: string;
|
||||
operator: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
const TicketsPage: React.FC = () => {
|
||||
const [tickets, setTickets] = useState<Ticket[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [filters, setFilters] = useState({
|
||||
status: 'all',
|
||||
category: 'all',
|
||||
priority: 'all'
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
fetchTickets();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [filters]);
|
||||
|
||||
const fetchTickets = async () => {
|
||||
try {
|
||||
const params: Record<string, string> = {};
|
||||
|
||||
if (filters.status !== 'all') params.status = filters.status;
|
||||
if (filters.category !== 'all') params.category = filters.category;
|
||||
if (filters.priority !== 'all') params.priority = filters.priority;
|
||||
|
||||
const response = await apiClient.get('/api/ticket', { params });
|
||||
|
||||
setTickets(response.data.tickets || []);
|
||||
setLoading(false);
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки тикетов:', error);
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusBadge = (status: string) => {
|
||||
const badges: Record<string, { color: string; text: string; emoji: string }> = {
|
||||
open: { color: 'bg-green-100 text-green-800', text: 'Открыт', emoji: '🟢' },
|
||||
in_progress: { color: 'bg-blue-100 text-blue-800', text: 'В работе', emoji: '🔵' },
|
||||
awaiting_reply: { color: 'bg-yellow-100 text-yellow-800', text: 'Ожидает ответа', emoji: '🟡' },
|
||||
resolved: { color: 'bg-purple-100 text-purple-800', text: 'Решён', emoji: '🟣' },
|
||||
closed: { color: 'bg-gray-100 text-gray-800', text: 'Закрыт', emoji: '⚪' }
|
||||
};
|
||||
|
||||
const badge = badges[status] || badges.open;
|
||||
|
||||
return (
|
||||
<span className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-medium ${badge.color}`}>
|
||||
<span>{badge.emoji}</span>
|
||||
<span>{badge.text}</span>
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
const getPriorityBadge = (priority: string) => {
|
||||
const badges: Record<string, { color: string; text: string; emoji: string }> = {
|
||||
urgent: { color: 'bg-red-100 text-red-800 border-red-300', text: 'Срочно', emoji: '🔴' },
|
||||
high: { color: 'bg-orange-100 text-orange-800 border-orange-300', text: 'Высокий', emoji: '🟠' },
|
||||
normal: { color: 'bg-gray-100 text-gray-800 border-gray-300', text: 'Обычный', emoji: '⚪' },
|
||||
low: { color: 'bg-green-100 text-green-800 border-green-300', text: 'Низкий', emoji: '🟢' }
|
||||
};
|
||||
|
||||
const badge = badges[priority] || badges.normal;
|
||||
|
||||
return (
|
||||
<span className={`inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium border ${badge.color}`}>
|
||||
<span>{badge.emoji}</span>
|
||||
<span>{badge.text}</span>
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
const getCategoryIcon = (category: string) => {
|
||||
const icons: Record<string, string> = {
|
||||
general: '💬',
|
||||
technical: '⚙️',
|
||||
billing: '💰',
|
||||
other: '📝'
|
||||
};
|
||||
|
||||
return icons[category] || icons.general;
|
||||
};
|
||||
|
||||
const formatRelativeTime = (dateString: string) => {
|
||||
const date = new Date(dateString);
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - date.getTime();
|
||||
const diffMins = Math.floor(diffMs / 60000);
|
||||
const diffHours = Math.floor(diffMs / 3600000);
|
||||
const diffDays = Math.floor(diffMs / 86400000);
|
||||
|
||||
if (diffMins < 1) return 'только что';
|
||||
if (diffMins < 60) return `${diffMins} мин. назад`;
|
||||
if (diffHours < 24) return `${diffHours} ч. назад`;
|
||||
if (diffDays < 7) return `${diffDays} дн. назад`;
|
||||
return date.toLocaleDateString('ru-RU');
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto"></div>
|
||||
<p className="mt-4 text-gray-600">Загрузка тикетов...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 py-8">
|
||||
<div className="max-w-7xl mx-auto px-4">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between mb-8">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900 mb-2">Тикеты поддержки</h1>
|
||||
<p className="text-gray-600">Управляйте вашими обращениями в службу поддержки</p>
|
||||
</div>
|
||||
<Link
|
||||
to="/dashboard/tickets/new"
|
||||
className="bg-blue-500 hover:bg-blue-600 text-white px-6 py-3 rounded-lg font-medium transition-colors duration-200 flex items-center gap-2"
|
||||
>
|
||||
<span>➕</span>
|
||||
Создать тикет
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="bg-white rounded-xl shadow-md p-6 mb-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
{/* Status Filter */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">Статус</label>
|
||||
<select
|
||||
value={filters.status}
|
||||
onChange={(e) => setFilters({ ...filters, status: e.target.value })}
|
||||
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
>
|
||||
<option value="all">Все статусы</option>
|
||||
<option value="open">Открыт</option>
|
||||
<option value="in_progress">В работе</option>
|
||||
<option value="awaiting_reply">Ожидает ответа</option>
|
||||
<option value="resolved">Решён</option>
|
||||
<option value="closed">Закрыт</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Category Filter */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">Категория</label>
|
||||
<select
|
||||
value={filters.category}
|
||||
onChange={(e) => setFilters({ ...filters, category: e.target.value })}
|
||||
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
>
|
||||
<option value="all">Все категории</option>
|
||||
<option value="general">Общие вопросы</option>
|
||||
<option value="technical">Технические</option>
|
||||
<option value="billing">Биллинг</option>
|
||||
<option value="other">Другое</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Priority Filter */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">Приоритет</label>
|
||||
<select
|
||||
value={filters.priority}
|
||||
onChange={(e) => setFilters({ ...filters, priority: e.target.value })}
|
||||
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
>
|
||||
<option value="all">Все приоритеты</option>
|
||||
<option value="urgent">Срочно</option>
|
||||
<option value="high">Высокий</option>
|
||||
<option value="normal">Обычный</option>
|
||||
<option value="low">Низкий</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tickets Grid */}
|
||||
{tickets.length === 0 ? (
|
||||
<div className="bg-white rounded-xl shadow-md p-12 text-center">
|
||||
<div className="text-6xl mb-4">📭</div>
|
||||
<h3 className="text-xl font-semibold text-gray-900 mb-2">Нет тикетов</h3>
|
||||
<p className="text-gray-600 mb-6">У вас пока нет открытых тикетов поддержки</p>
|
||||
<Link
|
||||
to="/dashboard/tickets/new"
|
||||
className="inline-block bg-blue-500 hover:bg-blue-600 text-white px-6 py-3 rounded-lg font-medium transition-colors duration-200"
|
||||
>
|
||||
Создать первый тикет
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 gap-6">
|
||||
{tickets.map((ticket) => (
|
||||
<Link
|
||||
key={ticket.id}
|
||||
to={`/dashboard/tickets/${ticket.id}`}
|
||||
className="bg-white rounded-xl shadow-md hover:shadow-lg transition-all duration-200 overflow-hidden"
|
||||
>
|
||||
<div className="p-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-start justify-between mb-4">
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-3 mb-2">
|
||||
<span className="text-2xl">{getCategoryIcon(ticket.category)}</span>
|
||||
<h3 className="text-xl font-semibold text-gray-900">{ticket.title}</h3>
|
||||
{getPriorityBadge(ticket.priority)}
|
||||
</div>
|
||||
<p className="text-gray-600 line-clamp-2">{ticket.message.substring(0, 150)}...</p>
|
||||
</div>
|
||||
<div className="ml-4">
|
||||
{getStatusBadge(ticket.status)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="flex items-center justify-between pt-4 border-t border-gray-200">
|
||||
<div className="flex items-center gap-4 text-sm text-gray-600">
|
||||
<span className="flex items-center gap-1">
|
||||
<span>🕒</span>
|
||||
<span>{formatRelativeTime(ticket.updatedAt)}</span>
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<span>💬</span>
|
||||
<span>{ticket.responses?.length || 0} ответов</span>
|
||||
</span>
|
||||
{ticket.closedAt && (
|
||||
<span className="flex items-center gap-1">
|
||||
<span>🔒</span>
|
||||
<span>Закрыт</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-blue-500 hover:text-blue-600 font-medium">
|
||||
Открыть →
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TicketsPage;
|
||||
166
ospabhost/frontend/src/pages/dashboard/tickets/new.tsx
Normal file
166
ospabhost/frontend/src/pages/dashboard/tickets/new.tsx
Normal file
@@ -0,0 +1,166 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useNavigate, Link } from 'react-router-dom';
|
||||
import apiClient from '../../../utils/apiClient';
|
||||
|
||||
const NewTicketPage: React.FC = () => {
|
||||
const navigate = useNavigate();
|
||||
const [formData, setFormData] = useState({
|
||||
title: '',
|
||||
message: '',
|
||||
category: 'general',
|
||||
priority: 'normal'
|
||||
});
|
||||
const [sending, setSending] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!formData.title.trim() || !formData.message.trim()) {
|
||||
setError('Заполните все поля');
|
||||
return;
|
||||
}
|
||||
|
||||
setSending(true);
|
||||
setError('');
|
||||
|
||||
try {
|
||||
const response = await apiClient.post('/api/ticket/create', formData);
|
||||
|
||||
// Перенаправляем на созданный тикет
|
||||
navigate(`/dashboard/tickets/${response.data.ticket.id}`);
|
||||
} catch (err) {
|
||||
console.error('Ошибка создания тикета:', err);
|
||||
setError('Не удалось создать тикет. Попробуйте ещё раз.');
|
||||
setSending(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 py-8">
|
||||
<div className="max-w-3xl mx-auto px-4">
|
||||
{/* Back Button */}
|
||||
<Link
|
||||
to="/dashboard/tickets"
|
||||
className="inline-flex items-center gap-2 text-gray-600 hover:text-gray-900 mb-6 transition-colors"
|
||||
>
|
||||
<span>←</span>
|
||||
<span>Назад к тикетам</span>
|
||||
</Link>
|
||||
|
||||
{/* Form */}
|
||||
<div className="bg-white rounded-xl shadow-md p-8">
|
||||
<h1 className="text-2xl font-bold text-gray-900 mb-6">Создать новый тикет</h1>
|
||||
|
||||
{error && (
|
||||
<div className="mb-6 bg-red-50 border border-red-200 text-red-800 px-4 py-3 rounded-lg">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
{/* Title */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Тема <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.title}
|
||||
onChange={(e) => setFormData({ ...formData, title: e.target.value })}
|
||||
placeholder="Кратко опишите вашу проблему"
|
||||
className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Category and Priority */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
{/* Category */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Категория
|
||||
</label>
|
||||
<select
|
||||
value={formData.category}
|
||||
onChange={(e) => setFormData({ ...formData, category: e.target.value })}
|
||||
className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
>
|
||||
<option value="general">💬 Общие вопросы</option>
|
||||
<option value="technical">⚙️ Технические</option>
|
||||
<option value="billing">💰 Биллинг</option>
|
||||
<option value="other">📝 Другое</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Priority */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Приоритет
|
||||
</label>
|
||||
<select
|
||||
value={formData.priority}
|
||||
onChange={(e) => setFormData({ ...formData, priority: e.target.value })}
|
||||
className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
>
|
||||
<option value="low">🟢 Низкий</option>
|
||||
<option value="normal">⚪ Обычный</option>
|
||||
<option value="high">🟠 Высокий</option>
|
||||
<option value="urgent">🔴 Срочно</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Message */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Описание <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<textarea
|
||||
value={formData.message}
|
||||
onChange={(e) => setFormData({ ...formData, message: e.target.value })}
|
||||
placeholder="Подробно опишите вашу проблему или вопрос..."
|
||||
className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
|
||||
rows={8}
|
||||
required
|
||||
/>
|
||||
<p className="mt-2 text-sm text-gray-500">
|
||||
Минимум 10 символов. Чем подробнее вы опишете проблему, тем быстрее мы сможем помочь.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Info Box */}
|
||||
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
|
||||
<h3 className="text-sm font-semibold text-blue-900 mb-2">💡 Советы:</h3>
|
||||
<ul className="text-sm text-blue-800 space-y-1">
|
||||
<li>• Укажите все детали проблемы</li>
|
||||
<li>• Приложите скриншоты, если возможно</li>
|
||||
<li>• Опишите шаги для воспроизведения ошибки</li>
|
||||
<li>• Среднее время ответа: 2-4 часа</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex items-center justify-end gap-4">
|
||||
<Link
|
||||
to="/dashboard/tickets"
|
||||
className="px-6 py-3 text-gray-700 hover:text-gray-900 font-medium transition-colors"
|
||||
>
|
||||
Отмена
|
||||
</Link>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={sending}
|
||||
className="bg-blue-500 hover:bg-blue-600 text-white px-8 py-3 rounded-lg font-medium transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{sending ? 'Создание...' : 'Создать тикет'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default NewTicketPage;
|
||||
@@ -1,7 +1,12 @@
|
||||
export interface User {
|
||||
id?: number;
|
||||
username: string;
|
||||
email?: string;
|
||||
operator: number;
|
||||
isAdmin?: boolean;
|
||||
balance?: number;
|
||||
tickets?: Ticket[];
|
||||
buckets?: StorageBucket[];
|
||||
}
|
||||
|
||||
export interface Ticket {
|
||||
@@ -14,16 +19,23 @@ export interface Ticket {
|
||||
user?: { username: string };
|
||||
}
|
||||
|
||||
export interface Server {
|
||||
export interface StorageBucket {
|
||||
id: number;
|
||||
name: string;
|
||||
status: string;
|
||||
// можно добавить другие поля по необходимости
|
||||
plan: string;
|
||||
quotaGb: number;
|
||||
usedBytes: number;
|
||||
objectCount: number;
|
||||
storageClass: string;
|
||||
region: string;
|
||||
public: boolean;
|
||||
versioning: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface UserData {
|
||||
user: User;
|
||||
balance: number;
|
||||
servers: Server[];
|
||||
tickets: Ticket[];
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import { FaServer, FaCloud, FaShieldAlt } from 'react-icons/fa';
|
||||
import { FaCloud, FaShieldAlt, FaDatabase } from 'react-icons/fa';
|
||||
|
||||
const HomePage = () => {
|
||||
return (
|
||||
@@ -8,10 +8,10 @@ const HomePage = () => {
|
||||
<section className="relative bg-gradient-to-b from-blue-100 to-white pt-24 pb-32">
|
||||
<div className="container mx-auto text-center px-4">
|
||||
<h1 className="text-5xl md:text-6xl font-extrabold leading-tight tracking-tighter text-gray-900">
|
||||
Масштабируемый хостинг <br /> для ваших идей
|
||||
Облачное хранилище <br /> для ваших данных
|
||||
</h1>
|
||||
<p className="mt-6 text-lg md:text-xl max-w-2xl mx-auto text-gray-700">
|
||||
Запускайте, масштабируйте и управляйте своими проектами с надёжной и высокопроизводительной инфраструктурой.
|
||||
S3-совместимое хранилище с высокой доступностью и надежностью. Храните файлы, резервные копии и медиа-контент.
|
||||
</p>
|
||||
<div className="mt-10 flex flex-col sm:flex-row justify-center space-y-4 sm:space-y-0 sm:space-x-4">
|
||||
<Link
|
||||
@@ -37,11 +37,11 @@ const HomePage = () => {
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-8">
|
||||
<div className="bg-white p-8 rounded-2xl shadow-xl hover:shadow-2xl transition-shadow duration-300 transform hover:scale-105">
|
||||
<div className="flex justify-center mb-4">
|
||||
<FaServer className="text-5xl text-blue-500" />
|
||||
<FaDatabase className="text-5xl text-blue-500" />
|
||||
</div>
|
||||
<h3 className="text-2xl font-bold text-center text-gray-900">Высокая производительность</h3>
|
||||
<h3 className="text-2xl font-bold text-center text-gray-900">S3 API</h3>
|
||||
<p className="mt-2 text-center text-gray-700">
|
||||
Оптимизированные серверы для максимальной скорости загрузки вашего сайта.
|
||||
Полная совместимость с Amazon S3 API. Используйте привычные инструменты и SDK.
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-white p-8 rounded-2xl shadow-xl hover:shadow-2xl transition-shadow duration-300 transform hover:scale-105">
|
||||
@@ -50,7 +50,7 @@ const HomePage = () => {
|
||||
</div>
|
||||
<h3 className="text-2xl font-bold text-center text-gray-900">Масштабируемость</h3>
|
||||
<p className="mt-2 text-center text-gray-700">
|
||||
Легко увеличивайте или уменьшайте ресурсы по мере роста вашего проекта.
|
||||
Неограниченное хранилище. Платите только за используемое пространство.
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-white p-8 rounded-2xl shadow-xl hover:shadow-2xl transition-shadow duration-300 transform hover:scale-105">
|
||||
@@ -59,7 +59,7 @@ const HomePage = () => {
|
||||
</div>
|
||||
<h3 className="text-2xl font-bold text-center text-gray-900">Надежность и безопасность</h3>
|
||||
<p className="mt-2 text-center text-gray-700">
|
||||
Ваши данные и приложения всегда под надёжной защитой.
|
||||
Шифрование данных, резервное копирование и высокая доступность 99.9%.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -72,7 +72,7 @@ const HomePage = () => {
|
||||
Готовы начать?
|
||||
</h2>
|
||||
<p className="mt-4 text-lg md:text-xl max-w-2xl mx-auto text-gray-400">
|
||||
Присоединяйтесь к тысячам разработчиков, которые доверяют нам.
|
||||
Присоединяйтесь к разработчикам, которые доверяют нам свои данные.
|
||||
</p>
|
||||
<div className="mt-8">
|
||||
<Link
|
||||
|
||||
@@ -5,8 +5,10 @@ import useAuth from '../context/useAuth';
|
||||
import { Turnstile } from '@marsidev/react-turnstile';
|
||||
import type { TurnstileInstance } from '@marsidev/react-turnstile';
|
||||
import { API_URL } from '../config/api';
|
||||
import QRLogin from '../components/QRLogin';
|
||||
|
||||
const LoginPage = () => {
|
||||
const [loginMethod, setLoginMethod] = useState<'password' | 'qr'>('password');
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
@@ -87,52 +89,85 @@ const LoginPage = () => {
|
||||
<div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
|
||||
<div className="bg-white p-8 md:p-10 rounded-3xl shadow-2xl w-full max-w-md text-center">
|
||||
<h1 className="text-3xl font-bold text-gray-800 mb-6">Вход в аккаунт</h1>
|
||||
<form onSubmit={handleLogin}>
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="Электронная почта"
|
||||
className="w-full px-5 py-3 mb-4 border border-gray-300 rounded-full focus:outline-none focus:ring-2 focus:ring-ospab-primary"
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="Пароль"
|
||||
className="w-full px-5 py-3 mb-6 border border-gray-300 rounded-full focus:outline-none focus:ring-2 focus:ring-ospab-primary"
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
|
||||
{/* Cloudflare Turnstile Captcha */}
|
||||
<div className="mb-6 flex justify-center">
|
||||
<Turnstile
|
||||
ref={turnstileRef}
|
||||
siteKey={siteKey}
|
||||
onSuccess={(token: string) => setTurnstileToken(token)}
|
||||
onError={() => {
|
||||
setTurnstileToken(null);
|
||||
setError('Ошибка загрузки капчи. Попробуйте обновить страницу.');
|
||||
}}
|
||||
onExpire={() => setTurnstileToken(null)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
{/* Переключатель метода входа */}
|
||||
<div className="flex mb-6 bg-gray-100 rounded-full p-1">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading || !turnstileToken}
|
||||
className="w-full px-5 py-3 rounded-full text-white font-bold transition-colors transform hover:scale-105 bg-ospab-primary hover:bg-ospab-accent disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
type="button"
|
||||
onClick={() => setLoginMethod('password')}
|
||||
className={`flex-1 py-2 px-4 rounded-full text-sm font-medium transition-colors ${
|
||||
loginMethod === 'password'
|
||||
? 'bg-white text-gray-900 shadow'
|
||||
: 'text-gray-600 hover:text-gray-900'
|
||||
}`}
|
||||
>
|
||||
{isLoading ? 'Входим...' : 'Войти'}
|
||||
Пароль
|
||||
</button>
|
||||
</form>
|
||||
{error && (
|
||||
<div className="mt-4 p-3 bg-red-50 border border-red-200 rounded-lg">
|
||||
<p className="text-sm text-red-600">{error}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setLoginMethod('qr')}
|
||||
className={`flex-1 py-2 px-4 rounded-full text-sm font-medium transition-colors ${
|
||||
loginMethod === 'qr'
|
||||
? 'bg-white text-gray-900 shadow'
|
||||
: 'text-gray-600 hover:text-gray-900'
|
||||
}`}
|
||||
>
|
||||
QR-код
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{loginMethod === 'password' ? (
|
||||
<>
|
||||
<form onSubmit={handleLogin}>
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="Электронная почта"
|
||||
className="w-full px-5 py-3 mb-4 border border-gray-300 rounded-full focus:outline-none focus:ring-2 focus:ring-ospab-primary"
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="Пароль"
|
||||
className="w-full px-5 py-3 mb-6 border border-gray-300 rounded-full focus:outline-none focus:ring-2 focus:ring-ospab-primary"
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
|
||||
{/* Cloudflare Turnstile Captcha */}
|
||||
<div className="mb-6 flex justify-center">
|
||||
<Turnstile
|
||||
ref={turnstileRef}
|
||||
siteKey={siteKey}
|
||||
onSuccess={(token: string) => setTurnstileToken(token)}
|
||||
onError={() => {
|
||||
setTurnstileToken(null);
|
||||
setError('Ошибка загрузки капчи. Попробуйте обновить страницу.');
|
||||
}}
|
||||
onExpire={() => setTurnstileToken(null)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading || !turnstileToken}
|
||||
className="w-full px-5 py-3 rounded-full text-white font-bold transition-colors transform hover:scale-105 bg-ospab-primary hover:bg-ospab-accent disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{isLoading ? 'Входим...' : 'Войти'}
|
||||
</button>
|
||||
</form>
|
||||
{error && (
|
||||
<div className="mt-4 p-3 bg-red-50 border border-red-200 rounded-lg">
|
||||
<p className="text-sm text-red-600">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<QRLogin onSuccess={() => navigate('/dashboard')} />
|
||||
)}
|
||||
|
||||
{/* Социальные сети */}
|
||||
|
||||
@@ -59,7 +59,7 @@ const Privacy: React.FC = () => {
|
||||
<li>Информация о браузере и устройстве</li>
|
||||
<li>Данные cookies</li>
|
||||
<li>Логи доступа к услугам</li>
|
||||
<li>Информация о конфигурации серверов и используемых ресурсах</li>
|
||||
<li>Информация об используемых ресурсах хранилища</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
@@ -77,7 +77,7 @@ const Privacy: React.FC = () => {
|
||||
<h2 className="text-2xl font-semibold text-gray-900 mb-4">3. Цели обработки персональных данных</h2>
|
||||
<p className="text-gray-700 mb-4"><strong>3.1.</strong> Мы обрабатываем ваши персональные данные для следующих целей:</p>
|
||||
<ul className="list-disc pl-6 text-gray-700 space-y-1">
|
||||
<li>Предоставление услуг хостинга (VPS, выделенные серверы, colocation)</li>
|
||||
<li>Предоставление услуг облачного хранилища (S3 API)</li>
|
||||
<li>Регистрация и управление личным кабинетом</li>
|
||||
<li>Обработка платежей и ведение бухгалтерии</li>
|
||||
<li>Техническая поддержка клиентов</li>
|
||||
|
||||
216
ospabhost/frontend/src/pages/qr-login.tsx
Normal file
216
ospabhost/frontend/src/pages/qr-login.tsx
Normal file
@@ -0,0 +1,216 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { isAxiosError } from 'axios';
|
||||
import apiClient from '../utils/apiClient';
|
||||
|
||||
interface UserData {
|
||||
id: number;
|
||||
username: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
const QRLoginPage = () => {
|
||||
const [searchParams] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
const [status, setStatus] = useState<'loading' | 'confirm' | 'success' | 'error' | 'expired'>('loading');
|
||||
const [message, setMessage] = useState('Проверка QR-кода...');
|
||||
const [userData, setUserData] = useState<UserData | null>(null);
|
||||
const code = searchParams.get('code');
|
||||
|
||||
useEffect(() => {
|
||||
if (!code) {
|
||||
setStatus('error');
|
||||
setMessage('Неверный QR-код');
|
||||
return;
|
||||
}
|
||||
|
||||
const checkAuth = async () => {
|
||||
try {
|
||||
setStatus('loading');
|
||||
setMessage('Проверка авторизации...');
|
||||
|
||||
// Получаем токен из localStorage
|
||||
const token = localStorage.getItem('access_token');
|
||||
|
||||
if (!token) {
|
||||
setStatus('error');
|
||||
setMessage('Вы не авторизованы. Войдите в аккаунт на телефоне');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await apiClient.post('/api/qr-auth/scanning', { code });
|
||||
} catch (err) {
|
||||
console.log('Не удалось обновить статус на scanning:', err);
|
||||
}
|
||||
|
||||
// Получаем данные текущего пользователя
|
||||
const userResponse = await apiClient.get('/api/auth/me');
|
||||
|
||||
setUserData(userResponse.data.user);
|
||||
setStatus('confirm');
|
||||
setMessage('Подтвердите вход на новом устройстве');
|
||||
} catch (error) {
|
||||
console.error('Ошибка проверки авторизации:', error);
|
||||
|
||||
if (isAxiosError(error) && error.response?.status === 401) {
|
||||
setStatus('error');
|
||||
setMessage('Вы не авторизованы. Войдите в аккаунт на телефоне');
|
||||
} else {
|
||||
setStatus('error');
|
||||
setMessage('Ошибка проверки авторизации');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
checkAuth();
|
||||
}, [code]);
|
||||
|
||||
const handleConfirm = async () => {
|
||||
try {
|
||||
setStatus('loading');
|
||||
setMessage('Подтверждение входа...');
|
||||
|
||||
const response = await apiClient.post('/api/qr-auth/confirm', { code });
|
||||
|
||||
if (response.data.success) {
|
||||
setStatus('success');
|
||||
setMessage('Вход успешно подтверждён!');
|
||||
|
||||
// Перенаправление на главную через 2 секунды
|
||||
setTimeout(() => {
|
||||
window.close(); // Попытка закрыть вкладку если открыта из QR-сканера
|
||||
}, 2000);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка подтверждения:', error);
|
||||
|
||||
if (isAxiosError(error) && error.response?.status === 401) {
|
||||
setStatus('error');
|
||||
setMessage('Вы не авторизованы. Войдите в аккаунт на телефоне');
|
||||
} else if (isAxiosError(error) && (error.response?.status === 404 || error.response?.status === 410)) {
|
||||
setStatus('expired');
|
||||
setMessage('QR-код истёк или уже использован');
|
||||
} else if (isAxiosError(error) && error.response?.data && typeof error.response.data === 'object' && 'error' in error.response.data) {
|
||||
const data = error.response.data as { error?: string };
|
||||
setStatus('error');
|
||||
setMessage(data.error ?? 'Ошибка подтверждения входа');
|
||||
} else {
|
||||
setStatus('error');
|
||||
setMessage('Ошибка подтверждения входа');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
window.close();
|
||||
};
|
||||
|
||||
const getIcon = () => {
|
||||
switch (status) {
|
||||
case 'loading':
|
||||
return (
|
||||
<div className="animate-spin rounded-full h-16 w-16 border-b-4 border-blue-500 mx-auto"></div>
|
||||
);
|
||||
case 'confirm':
|
||||
return (
|
||||
<div className="w-20 h-20 bg-blue-100 rounded-full flex items-center justify-center mx-auto">
|
||||
<svg className="w-12 h-12 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
|
||||
</svg>
|
||||
</div>
|
||||
);
|
||||
case 'success':
|
||||
return <div className="text-6xl text-green-500">✓</div>;
|
||||
case 'expired':
|
||||
return <div className="text-6xl text-orange-500">⌛</div>;
|
||||
case 'error':
|
||||
return <div className="text-6xl text-red-500">✕</div>;
|
||||
}
|
||||
};
|
||||
|
||||
const getColor = () => {
|
||||
switch (status) {
|
||||
case 'loading':
|
||||
return 'text-blue-600';
|
||||
case 'confirm':
|
||||
return 'text-gray-800';
|
||||
case 'success':
|
||||
return 'text-green-600';
|
||||
case 'expired':
|
||||
return 'text-orange-600';
|
||||
case 'error':
|
||||
return 'text-red-600';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 flex items-center justify-center p-4">
|
||||
<div className="bg-white rounded-2xl shadow-xl p-8 w-full max-w-md text-center">
|
||||
<div className="mb-6">
|
||||
{getIcon()}
|
||||
</div>
|
||||
|
||||
<h1 className={`text-2xl font-bold mb-4 ${getColor()}`}>
|
||||
{status === 'loading' && 'Проверка'}
|
||||
{status === 'confirm' && 'Подтвердите вход'}
|
||||
{status === 'success' && 'Успешно!'}
|
||||
{status === 'expired' && 'QR-код истёк'}
|
||||
{status === 'error' && 'Ошибка'}
|
||||
</h1>
|
||||
|
||||
{status === 'confirm' && userData && (
|
||||
<div className="mb-6">
|
||||
<div className="bg-gray-50 rounded-xl p-6 mb-6">
|
||||
<p className="text-gray-600 mb-2">Войти на новом устройстве как:</p>
|
||||
<p className="text-xl font-bold text-gray-900">{userData.username}</p>
|
||||
<p className="text-sm text-gray-500">{userData.email}</p>
|
||||
</div>
|
||||
|
||||
<p className="text-gray-600 text-sm mb-6">
|
||||
Это вы пытаетесь войти? Подтвердите вход на компьютере
|
||||
</p>
|
||||
|
||||
<div className="flex gap-3">
|
||||
<button
|
||||
onClick={handleCancel}
|
||||
className="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-700 px-6 py-3 rounded-lg font-medium transition-colors duration-200"
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
<button
|
||||
onClick={handleConfirm}
|
||||
className="flex-1 bg-blue-500 hover:bg-blue-600 text-white px-6 py-3 rounded-lg font-medium transition-colors duration-200"
|
||||
>
|
||||
Подтвердить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{status !== 'confirm' && (
|
||||
<p className="text-gray-600 mb-6">
|
||||
{message}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{status === 'success' && (
|
||||
<p className="text-sm text-gray-500">
|
||||
Вы можете закрыть эту страницу
|
||||
</p>
|
||||
)}
|
||||
|
||||
{(status === 'error' || status === 'expired') && (
|
||||
<button
|
||||
onClick={() => navigate('/login')}
|
||||
className="bg-blue-500 hover:bg-blue-600 text-white px-6 py-3 rounded-lg font-medium transition-colors duration-200"
|
||||
>
|
||||
Вернуться к входу
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default QRLoginPage;
|
||||
@@ -5,7 +5,7 @@ import { Turnstile } from '@marsidev/react-turnstile';
|
||||
import type { TurnstileInstance } from '@marsidev/react-turnstile';
|
||||
import useAuth from '../context/useAuth';
|
||||
import { API_URL } from '../config/api';
|
||||
import { useToast } from '../components/Toast';
|
||||
import { useToast } from '../hooks/useToast';
|
||||
|
||||
const RegisterPage = () => {
|
||||
const { addToast } = useToast();
|
||||
|
||||
328
ospabhost/frontend/src/pages/s3plans.tsx
Normal file
328
ospabhost/frontend/src/pages/s3plans.tsx
Normal file
@@ -0,0 +1,328 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import { FaDatabase, FaCheck, FaArrowRight, FaShieldAlt, FaBolt, FaInfinity } from 'react-icons/fa';
|
||||
|
||||
const S3PlansPage = () => {
|
||||
const plans = [
|
||||
{
|
||||
name: 'Starter',
|
||||
price: 99,
|
||||
storage: '10 GB',
|
||||
bandwidth: '50 GB',
|
||||
requests: '10,000',
|
||||
features: [
|
||||
'S3-совместимый API',
|
||||
'Публичные и приватные бакеты',
|
||||
'SSL/TLS шифрование',
|
||||
'Версионирование файлов',
|
||||
'CDN интеграция',
|
||||
'Web-интерфейс управления'
|
||||
],
|
||||
popular: false
|
||||
},
|
||||
{
|
||||
name: 'Professional',
|
||||
price: 299,
|
||||
storage: '50 GB',
|
||||
bandwidth: '250 GB',
|
||||
requests: '100,000',
|
||||
features: [
|
||||
'Всё из Starter',
|
||||
'Lifecycle политики',
|
||||
'Cross-region репликация',
|
||||
'Object Lock (WORM)',
|
||||
'Расширенная статистика',
|
||||
'Priority поддержка',
|
||||
'SLA 99.9%'
|
||||
],
|
||||
popular: true
|
||||
},
|
||||
{
|
||||
name: 'Business',
|
||||
price: 799,
|
||||
storage: '200 GB',
|
||||
bandwidth: '1 TB',
|
||||
requests: '500,000',
|
||||
features: [
|
||||
'Всё из Professional',
|
||||
'Приватная сеть',
|
||||
'Кастомные домены',
|
||||
'Webhook уведомления',
|
||||
'Audit логи',
|
||||
'Deduplicate storage',
|
||||
'SLA 99.95%'
|
||||
],
|
||||
popular: false
|
||||
},
|
||||
{
|
||||
name: 'Enterprise',
|
||||
price: 1999,
|
||||
storage: '1 TB',
|
||||
bandwidth: '5 TB',
|
||||
requests: 'Unlimited',
|
||||
features: [
|
||||
'Всё из Business',
|
||||
'Выделенные ресурсы',
|
||||
'Geo-распределение',
|
||||
'Custom retention policies',
|
||||
'Персональный менеджер',
|
||||
'White-label опции',
|
||||
'SLA 99.99%'
|
||||
],
|
||||
popular: false
|
||||
}
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-b from-gray-50 to-white">
|
||||
{/* Hero Section */}
|
||||
<section className="pt-32 pb-20 px-8">
|
||||
<div className="container mx-auto max-w-6xl text-center">
|
||||
<div className="inline-flex items-center gap-2 px-4 py-2 bg-blue-50 text-blue-600 rounded-full text-sm font-medium mb-6">
|
||||
<FaDatabase />
|
||||
<span>S3 Object Storage</span>
|
||||
</div>
|
||||
<h1 className="text-5xl md:text-6xl font-bold mb-6 text-gray-900">
|
||||
Тарифы S3 Хранилища
|
||||
</h1>
|
||||
<p className="text-xl text-gray-600 max-w-3xl mx-auto mb-8">
|
||||
Масштабируемое объектное хранилище с S3-совместимым API.
|
||||
Храните любые данные: от бэкапов до медиа-контента.
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Features Grid */}
|
||||
<section className="py-16 px-8 bg-white">
|
||||
<div className="container mx-auto max-w-6xl">
|
||||
<div className="grid md:grid-cols-3 gap-8 mb-16">
|
||||
<div className="text-center p-6">
|
||||
<div className="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
|
||||
<FaBolt className="text-3xl text-blue-600" />
|
||||
</div>
|
||||
<h3 className="text-lg font-semibold mb-2">Высокая скорость</h3>
|
||||
<p className="text-gray-600 text-sm">
|
||||
NVMe SSD и 10Gb/s сеть для быстрого доступа к данным
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-center p-6">
|
||||
<div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
|
||||
<FaShieldAlt className="text-3xl text-green-600" />
|
||||
</div>
|
||||
<h3 className="text-lg font-semibold mb-2">Безопасность</h3>
|
||||
<p className="text-gray-600 text-sm">
|
||||
Шифрование at-rest и in-transit, IAM политики доступа
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-center p-6">
|
||||
<div className="w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-4">
|
||||
<FaInfinity className="text-3xl text-purple-600" />
|
||||
</div>
|
||||
<h3 className="text-lg font-semibold mb-2">Совместимость</h3>
|
||||
<p className="text-gray-600 text-sm">
|
||||
S3 API - работает с AWS SDK, boto3, s3cmd и другими
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Pricing Plans */}
|
||||
<section className="py-20 px-8 bg-gradient-to-b from-white to-gray-50">
|
||||
<div className="container mx-auto max-w-7xl">
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-4 gap-8">
|
||||
{plans.map((plan, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className={`relative bg-white rounded-2xl shadow-lg hover:shadow-xl transition-all ${
|
||||
plan.popular ? 'ring-2 ring-blue-500 scale-105' : ''
|
||||
}`}
|
||||
>
|
||||
{plan.popular && (
|
||||
<div className="absolute -top-4 left-0 right-0 flex justify-center">
|
||||
<span className="bg-blue-500 text-white px-4 py-1 rounded-full text-sm font-medium">
|
||||
Популярный
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="p-8">
|
||||
<h3 className="text-2xl font-bold mb-2 text-gray-900">{plan.name}</h3>
|
||||
<div className="mb-6">
|
||||
<span className="text-4xl font-bold text-gray-900">{plan.price}</span>
|
||||
<span className="text-gray-600 ml-2">₽/мес</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 mb-6 text-sm">
|
||||
<div className="flex justify-between py-2 border-b border-gray-100">
|
||||
<span className="text-gray-600">Хранилище:</span>
|
||||
<span className="font-semibold text-gray-900">{plan.storage}</span>
|
||||
</div>
|
||||
<div className="flex justify-between py-2 border-b border-gray-100">
|
||||
<span className="text-gray-600">Трафик:</span>
|
||||
<span className="font-semibold text-gray-900">{plan.bandwidth}</span>
|
||||
</div>
|
||||
<div className="flex justify-between py-2 border-b border-gray-100">
|
||||
<span className="text-gray-600">Запросы:</span>
|
||||
<span className="font-semibold text-gray-900">{plan.requests}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ul className="space-y-3 mb-8">
|
||||
{plan.features.map((feature, i) => (
|
||||
<li key={i} className="flex items-start gap-2 text-sm">
|
||||
<FaCheck className="text-green-500 mt-1 flex-shrink-0" />
|
||||
<span className="text-gray-700">{feature}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
<Link
|
||||
to={`/dashboard/checkout?plan=${plan.name.toLowerCase()}&price=${plan.price}&type=s3`}
|
||||
className={`block w-full py-3 text-center rounded-lg font-medium transition-all ${
|
||||
plan.popular
|
||||
? 'bg-blue-500 text-white hover:bg-blue-600 shadow-md hover:shadow-lg'
|
||||
: 'bg-gray-100 text-gray-900 hover:bg-gray-200'
|
||||
}`}
|
||||
>
|
||||
Выбрать план
|
||||
<FaArrowRight className="inline ml-2" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="mt-16 text-center">
|
||||
<p className="text-gray-600 mb-4">
|
||||
Нужен индивидуальный план с большими объёмами?
|
||||
</p>
|
||||
<Link
|
||||
to="/dashboard/tickets"
|
||||
className="inline-flex items-center gap-2 text-blue-600 hover:text-blue-700 font-medium"
|
||||
>
|
||||
Связаться с нами
|
||||
<FaArrowRight />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Use Cases */}
|
||||
<section className="py-20 px-8 bg-white">
|
||||
<div className="container mx-auto max-w-6xl">
|
||||
<h2 className="text-3xl font-bold text-center mb-12 text-gray-900">
|
||||
Сценарии использования
|
||||
</h2>
|
||||
<div className="grid md:grid-cols-3 gap-8">
|
||||
<div className="p-6 bg-gray-50 rounded-xl">
|
||||
<h3 className="text-lg font-semibold mb-3">Бэкапы и Архивы</h3>
|
||||
<p className="text-gray-600 text-sm mb-4">
|
||||
Храните резервные копии баз данных, конфигураций и важных файлов.
|
||||
Версионирование защитит от случайного удаления.
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<span className="text-xs px-2 py-1 bg-blue-100 text-blue-700 rounded">Databases</span>
|
||||
<span className="text-xs px-2 py-1 bg-blue-100 text-blue-700 rounded">Configs</span>
|
||||
<span className="text-xs px-2 py-1 bg-blue-100 text-blue-700 rounded">Archives</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-6 bg-gray-50 rounded-xl">
|
||||
<h3 className="text-lg font-semibold mb-3">Медиа Контент</h3>
|
||||
<p className="text-gray-600 text-sm mb-4">
|
||||
Храните и раздавайте изображения, видео, аудио через CDN.
|
||||
Идеально для сайтов, приложений и стриминга.
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<span className="text-xs px-2 py-1 bg-green-100 text-green-700 rounded">Images</span>
|
||||
<span className="text-xs px-2 py-1 bg-green-100 text-green-700 rounded">Videos</span>
|
||||
<span className="text-xs px-2 py-1 bg-green-100 text-green-700 rounded">Audio</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-6 bg-gray-50 rounded-xl">
|
||||
<h3 className="text-lg font-semibold mb-3">Статические Сайты</h3>
|
||||
<p className="text-gray-600 text-sm mb-4">
|
||||
Хостинг статических сайтов (HTML/CSS/JS) напрямую из бакета.
|
||||
Кастомные домены и SSL из коробки.
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<span className="text-xs px-2 py-1 bg-purple-100 text-purple-700 rounded">React</span>
|
||||
<span className="text-xs px-2 py-1 bg-purple-100 text-purple-700 rounded">Vue</span>
|
||||
<span className="text-xs px-2 py-1 bg-purple-100 text-purple-700 rounded">Next.js</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* FAQ */}
|
||||
<section className="py-20 px-8 bg-gray-50">
|
||||
<div className="container mx-auto max-w-4xl">
|
||||
<h2 className="text-3xl font-bold text-center mb-12 text-gray-900">
|
||||
Частые вопросы
|
||||
</h2>
|
||||
<div className="space-y-6">
|
||||
<div className="bg-white p-6 rounded-xl shadow-sm">
|
||||
<h3 className="font-semibold mb-2">Что такое S3-совместимое хранилище?</h3>
|
||||
<p className="text-gray-600 text-sm">
|
||||
Это объектное хранилище с API, совместимым с Amazon S3. Вы можете использовать
|
||||
любые инструменты и библиотеки для S3 (AWS SDK, boto3, s3cmd, Cyberduck и т.д.)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-6 rounded-xl shadow-sm">
|
||||
<h3 className="font-semibold mb-2">Что будет при превышении лимитов?</h3>
|
||||
<p className="text-gray-600 text-sm">
|
||||
При превышении хранилища или трафика мы уведомим вас. Можно перейти на старший тариф
|
||||
или докупить дополнительные ресурсы. Сервис не отключается мгновенно.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-6 rounded-xl shadow-sm">
|
||||
<h3 className="font-semibold mb-2">Как получить доступ к хранилищу?</h3>
|
||||
<p className="text-gray-600 text-sm">
|
||||
После оплаты тарифа вы получите Access Key и Secret Key. Используйте их для подключения
|
||||
через S3 API. Endpoint: s3.ospab.host
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-6 rounded-xl shadow-sm">
|
||||
<h3 className="font-semibold mb-2">Есть ли гарантия сохранности данных?</h3>
|
||||
<p className="text-gray-600 text-sm">
|
||||
Данные хранятся с репликацией на 3 узлах (3x копии). Durability 99.999999999% (11 девяток).
|
||||
Версионирование и snapshot защищают от случайного удаления.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* CTA */}
|
||||
<section className="py-20 px-8 bg-gradient-to-br from-blue-500 to-blue-600 text-white">
|
||||
<div className="container mx-auto max-w-4xl text-center">
|
||||
<h2 className="text-4xl font-bold mb-6">Готовы начать?</h2>
|
||||
<p className="text-xl mb-8 opacity-90">
|
||||
Создайте аккаунт и получите доступ к S3 хранилищу за 2 минуты
|
||||
</p>
|
||||
<div className="flex gap-4 justify-center">
|
||||
<Link
|
||||
to="/register"
|
||||
className="px-8 py-4 bg-white text-blue-600 rounded-lg font-semibold hover:bg-gray-100 transition-all"
|
||||
>
|
||||
Зарегистрироваться
|
||||
</Link>
|
||||
<Link
|
||||
to="/login"
|
||||
className="px-8 py-4 bg-blue-400 text-white rounded-lg font-semibold hover:bg-blue-300 transition-all"
|
||||
>
|
||||
Войти
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default S3PlansPage;
|
||||
@@ -1,83 +0,0 @@
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import axios from 'axios';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
const TariffsPage = () => {
|
||||
const [tariffs, setTariffs] = useState<Array<{id:number;name:string;price:number;description?:string}>>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const navigate = useNavigate();
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
const fetchTariffs = async () => {
|
||||
try {
|
||||
const res = await axios.get('https://ospab.host:5000/api/tariff');
|
||||
console.log('Ответ API тарифов:', res.data);
|
||||
if (Array.isArray(res.data)) {
|
||||
setTariffs(res.data);
|
||||
} else {
|
||||
setError('Некорректный формат данных тарифов');
|
||||
setTariffs([]);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Ошибка загрузки тарифов:', err);
|
||||
setError('Ошибка загрузки тарифов');
|
||||
setTariffs([]);
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
fetchTariffs();
|
||||
}, []);
|
||||
|
||||
const handleBuy = (tariffId: number) => {
|
||||
navigate(`/dashboard/checkout?tariff=${tariffId}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 py-12 lg:py-20">
|
||||
<div className="container mx-auto px-4">
|
||||
<h1 className="text-3xl md:text-4xl lg:text-5xl font-bold text-center mb-4 lg:mb-6 text-gray-900">Тарифы</h1>
|
||||
<p className="text-base lg:text-lg text-gray-600 text-center mb-8 lg:mb-10 max-w-2xl mx-auto">
|
||||
Выберите тариф для размещения сайта или сервера. ospab.host — надёжно и удобно!
|
||||
</p>
|
||||
{loading ? (
|
||||
<p className="text-lg text-gray-500 text-center">Загрузка...</p>
|
||||
) : error ? (
|
||||
<p className="text-lg text-red-500 text-center">{error}</p>
|
||||
) : tariffs.length === 0 ? (
|
||||
<p className="text-lg text-gray-500 text-center">Нет доступных тарифов.</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 lg:gap-8 mb-12 lg:mb-20">
|
||||
{tariffs.map(tariff => (
|
||||
<div key={tariff.id} className="bg-white p-6 lg:p-12 rounded-2xl lg:rounded-3xl shadow-xl lg:shadow-2xl text-left flex flex-col justify-between transition-transform hover:scale-105 duration-300 min-h-[280px] lg:min-h-[340px]">
|
||||
<div>
|
||||
<h2 className="text-2xl lg:text-4xl font-bold text-gray-800 mb-3 lg:mb-4">{tariff.name}</h2>
|
||||
<p className="mb-3 lg:mb-4 text-3xl lg:text-5xl font-extrabold text-ospab-primary break-words">₽{tariff.price}<span className="text-base lg:text-xl font-normal text-gray-500">/мес</span></p>
|
||||
{tariff.description && (
|
||||
<ul className="text-sm lg:text-lg text-gray-700 mb-4 lg:mb-6 list-disc list-inside space-y-1">
|
||||
{tariff.description.split(',').map((desc, i) => (
|
||||
<li key={i} className="break-words">{desc.trim()}</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
className="mt-4 px-6 lg:px-8 py-3 lg:py-4 rounded-full text-white font-bold text-base lg:text-xl transition-colors transform hover:scale-105 bg-ospab-primary hover:bg-ospab-accent w-full"
|
||||
onClick={() => handleBuy(tariff.id)}
|
||||
>
|
||||
Купить
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TariffsPage;
|
||||
|
||||
|
||||
@@ -40,11 +40,10 @@ const Terms: React.FC = () => {
|
||||
<div className="text-gray-700">
|
||||
<p className="mb-4">Для целей настоящего Соглашения используются следующие термины:</p>
|
||||
<ul className="list-disc pl-6 space-y-2">
|
||||
<li><strong>VPS (Virtual Private Server)</strong> — виртуальный выделенный сервер</li>
|
||||
<li><strong>Выделенный сервер (Dedicated Server)</strong> — физический сервер, предоставляемый в единоличное пользование</li>
|
||||
<li><strong>Colocation (Колокация)</strong> — услуга размещения оборудования Клиента в дата-центре Исполнителя</li>
|
||||
<li><strong>S3 хранилище</strong> — облачное объектное хранилище, совместимое с Amazon S3 API</li>
|
||||
<li><strong>Bucket</strong> — контейнер для хранения объектов в S3</li>
|
||||
<li><strong>Личный кабинет</strong> — защищённый раздел на сайте ospab.host для управления услугами</li>
|
||||
<li><strong>Панель управления</strong> — интерфейс для администрирования серверов</li>
|
||||
<li><strong>Панель управления</strong> — интерфейс для администрирования хранилища</li>
|
||||
<li><strong>Баланс счёта</strong> — сумма денежных средств на счету Клиента в системе</li>
|
||||
<li><strong>Uptime</strong> — время доступности услуг</li>
|
||||
</ul>
|
||||
@@ -57,9 +56,8 @@ const Terms: React.FC = () => {
|
||||
<div>
|
||||
<p><strong>3.1.</strong> Исполнитель обязуется предоставить Клиенту следующие услуги хостинга:</p>
|
||||
<ul className="list-disc pl-6 mt-2">
|
||||
<li>VPS (виртуальные выделенные серверы)</li>
|
||||
<li>Выделенные серверы (Dedicated Servers)</li>
|
||||
<li>Colocation (размещение оборудования Клиента)</li>
|
||||
<li>S3-совместимое облачное хранилище</li>
|
||||
<li>Хостинг статических сайтов (в разработке)</li>
|
||||
<li>Дополнительные услуги (по мере развития компании)</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
222
ospabhost/frontend/src/services/notificationService.ts
Normal file
222
ospabhost/frontend/src/services/notificationService.ts
Normal file
@@ -0,0 +1,222 @@
|
||||
import apiClient from '../utils/apiClient';
|
||||
|
||||
const API_URL = '/api/notifications';
|
||||
|
||||
// Тип для уведомления
|
||||
export interface Notification {
|
||||
id: number;
|
||||
userId: number;
|
||||
type: string;
|
||||
title: string;
|
||||
message: string;
|
||||
serverId?: number;
|
||||
ticketId?: number;
|
||||
checkId?: number;
|
||||
actionUrl?: string;
|
||||
icon?: string;
|
||||
color?: string;
|
||||
isRead: boolean;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
// Тип для PushSubscription
|
||||
export interface PushSubscriptionData {
|
||||
endpoint: string;
|
||||
keys: {
|
||||
p256dh: string;
|
||||
auth: string;
|
||||
};
|
||||
}
|
||||
|
||||
// Получить токен из localStorage
|
||||
const getAuthHeader = () => {
|
||||
const token = localStorage.getItem('access_token');
|
||||
return token ? { Authorization: `Bearer ${token}` } : {};
|
||||
};
|
||||
|
||||
// Получить список уведомлений
|
||||
export const getNotifications = async (params?: {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
unreadOnly?: boolean;
|
||||
type?: string;
|
||||
}): Promise<{ notifications: Notification[]; total: number; unreadCount: number }> => {
|
||||
try {
|
||||
const response = await apiClient.get(API_URL, {
|
||||
headers: getAuthHeader(),
|
||||
params
|
||||
});
|
||||
|
||||
// Проверяем структуру ответа
|
||||
if (response.data && response.data.success !== false) {
|
||||
// Адаптируем формат ответа от сервера
|
||||
const data = response.data;
|
||||
return {
|
||||
notifications: data.data || [],
|
||||
total: data.pagination?.total || 0,
|
||||
unreadCount: data.unreadCount || 0
|
||||
};
|
||||
} else {
|
||||
console.error('Ошибка ответа:', response.data);
|
||||
throw new Error(response.data?.message || 'Ошибка сервера');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки уведомлений:', error);
|
||||
// Возвращаем пустой объект вместо выброса ошибки
|
||||
return { notifications: [], total: 0, unreadCount: 0 };
|
||||
}
|
||||
};
|
||||
|
||||
// Получить количество непрочитанных
|
||||
export const getUnreadCount = async (): Promise<number> => {
|
||||
try {
|
||||
const response = await apiClient.get(`${API_URL}/unread-count`, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
return response.data.count || 0;
|
||||
} catch (error) {
|
||||
console.error('Ошибка получения счетчика:', error);
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
// Пометить уведомление как прочитанное
|
||||
export const markAsRead = async (id: number): Promise<void> => {
|
||||
await apiClient.post(`${API_URL}/${id}/read`, {}, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
};
|
||||
|
||||
// Пометить все как прочитанные
|
||||
export const markAllAsRead = async (): Promise<void> => {
|
||||
await apiClient.post(`${API_URL}/read-all`, {}, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
};
|
||||
|
||||
// Удалить уведомление
|
||||
export const deleteNotification = async (id: number): Promise<void> => {
|
||||
await apiClient.delete(`${API_URL}/${id}`, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
};
|
||||
|
||||
// Удалить все прочитанные
|
||||
export const deleteAllRead = async (): Promise<void> => {
|
||||
await apiClient.delete(`${API_URL}/read/all`, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
};
|
||||
|
||||
// Получить публичный VAPID ключ
|
||||
export const getVapidKey = async (): Promise<string> => {
|
||||
const response = await apiClient.get(`${API_URL}/vapid-key`, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
return response.data.publicKey;
|
||||
};
|
||||
|
||||
// Подписаться на Push-уведомления
|
||||
export const subscribePush = async (subscription: PushSubscriptionData): Promise<void> => {
|
||||
await apiClient.post(`${API_URL}/subscribe-push`, { subscription }, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
};
|
||||
|
||||
// Отписаться от Push-уведомлений
|
||||
export const unsubscribePush = async (endpoint: string): Promise<void> => {
|
||||
await apiClient.delete(`${API_URL}/unsubscribe-push`, {
|
||||
headers: getAuthHeader(),
|
||||
data: { endpoint }
|
||||
});
|
||||
};
|
||||
|
||||
// Запросить разрешение на Push-уведомления и зарегистрировать Service Worker
|
||||
export const requestPushPermission = async (): Promise<boolean> => {
|
||||
if (!('Notification' in window)) {
|
||||
console.error('❌ Браузер не поддерживает уведомления');
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!('serviceWorker' in navigator)) {
|
||||
console.error('❌ Браузер не поддерживает Service Worker');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Запрос разрешения
|
||||
console.log('📝 Запрашиваем разрешение на уведомления...');
|
||||
const permission = await Notification.requestPermission();
|
||||
console.log('📝 Результат запроса разрешения:', permission);
|
||||
|
||||
if (permission !== 'granted') {
|
||||
console.log('❌ Пользователь отклонил разрешение на уведомления');
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
// Регистрация Service Worker
|
||||
console.log('📝 Регистрируем Service Worker...');
|
||||
const registration = await navigator.serviceWorker.register('/service-worker.js');
|
||||
console.log('✅ Service Worker зарегистрирован:', registration);
|
||||
|
||||
console.log('📝 Ожидаем готовности Service Worker...');
|
||||
await navigator.serviceWorker.ready;
|
||||
console.log('✅ Service Worker готов');
|
||||
|
||||
// Получаем публичный VAPID ключ
|
||||
console.log('📝 Получаем VAPID ключ...');
|
||||
const vapidPublicKey = await getVapidKey();
|
||||
console.log('✅ VAPID ключ получен:', vapidPublicKey.substring(0, 20) + '...');
|
||||
|
||||
// Создаём подписку
|
||||
console.log('📝 Создаём Push подписку...');
|
||||
const subscription = await registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: urlBase64ToUint8Array(vapidPublicKey) as BufferSource
|
||||
});
|
||||
console.log('✅ Push подписка создана:', subscription.endpoint);
|
||||
|
||||
// Отправляем подписку на сервер
|
||||
console.log('📝 Отправляем подписку на сервер...');
|
||||
const subscriptionData: PushSubscriptionData = {
|
||||
endpoint: subscription.endpoint,
|
||||
keys: {
|
||||
p256dh: arrayBufferToBase64(subscription.getKey('p256dh')!),
|
||||
auth: arrayBufferToBase64(subscription.getKey('auth')!)
|
||||
}
|
||||
};
|
||||
|
||||
await subscribePush(subscriptionData);
|
||||
console.log('✅ Push-уведомления успешно подключены');
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('❌ Ошибка подключения Push-уведомлений:', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Утилита: конвертация base64 VAPID ключа в Uint8Array
|
||||
function urlBase64ToUint8Array(base64String: string): Uint8Array {
|
||||
const padding = '='.repeat((4 - base64String.length % 4) % 4);
|
||||
const base64 = (base64String + padding)
|
||||
.replace(/-/g, '+')
|
||||
.replace(/_/g, '/');
|
||||
|
||||
const rawData = window.atob(base64);
|
||||
const outputArray = new Uint8Array(rawData.length);
|
||||
|
||||
for (let i = 0; i < rawData.length; ++i) {
|
||||
outputArray[i] = rawData.charCodeAt(i);
|
||||
}
|
||||
return outputArray;
|
||||
}
|
||||
|
||||
// Утилита: конвертация ArrayBuffer в base64
|
||||
function arrayBufferToBase64(buffer: ArrayBuffer): string {
|
||||
const bytes = new Uint8Array(buffer);
|
||||
let binary = '';
|
||||
for (let i = 0; i < bytes.byteLength; i++) {
|
||||
binary += String.fromCharCode(bytes[i]);
|
||||
}
|
||||
return window.btoa(binary);
|
||||
}
|
||||
248
ospabhost/frontend/src/services/userService.ts
Normal file
248
ospabhost/frontend/src/services/userService.ts
Normal file
@@ -0,0 +1,248 @@
|
||||
import apiClient from '../utils/apiClient';
|
||||
|
||||
const API_URL = '/api/user';
|
||||
const SESSIONS_API = '/api/sessions'; // Отдельный эндпоинт для сессий
|
||||
|
||||
// Типы
|
||||
export interface UserProfile {
|
||||
id: number;
|
||||
username: string;
|
||||
email: string;
|
||||
balance: number;
|
||||
createdAt: string;
|
||||
profile?: {
|
||||
avatarUrl?: string;
|
||||
phoneNumber?: string;
|
||||
timezone?: string;
|
||||
language?: string;
|
||||
profilePublic: boolean;
|
||||
showEmail: boolean;
|
||||
twoFactorEnabled: boolean;
|
||||
};
|
||||
notificationSettings?: NotificationSettings;
|
||||
_count?: {
|
||||
servers: number;
|
||||
tickets: number;
|
||||
sessions: number;
|
||||
sshKeys: number;
|
||||
apiKeys: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface Session {
|
||||
id: number;
|
||||
token: string;
|
||||
ipAddress?: string;
|
||||
userAgent?: string;
|
||||
device?: string;
|
||||
browser?: string;
|
||||
location?: string;
|
||||
lastActivity: string;
|
||||
createdAt: string;
|
||||
expiresAt: string;
|
||||
isCurrent?: boolean;
|
||||
}
|
||||
|
||||
export interface LoginHistoryEntry {
|
||||
id: number;
|
||||
ipAddress: string;
|
||||
userAgent?: string;
|
||||
device?: string;
|
||||
browser?: string;
|
||||
location?: string;
|
||||
success: boolean;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface SSHKey {
|
||||
id: number;
|
||||
name: string;
|
||||
publicKey: string;
|
||||
fingerprint: string;
|
||||
createdAt: string;
|
||||
lastUsed?: string;
|
||||
}
|
||||
|
||||
export interface APIKey {
|
||||
id: number;
|
||||
name: string;
|
||||
prefix: string;
|
||||
permissions?: string;
|
||||
lastUsed?: string;
|
||||
createdAt: string;
|
||||
expiresAt?: string;
|
||||
}
|
||||
|
||||
export interface NotificationSettings {
|
||||
id: number;
|
||||
userId: number;
|
||||
emailServerCreated: boolean;
|
||||
emailServerStopped: boolean;
|
||||
emailBalanceLow: boolean;
|
||||
emailPaymentCharged: boolean;
|
||||
emailTicketReply: boolean;
|
||||
emailNewsletter: boolean;
|
||||
pushServerCreated: boolean;
|
||||
pushServerStopped: boolean;
|
||||
pushBalanceLow: boolean;
|
||||
pushPaymentCharged: boolean;
|
||||
pushTicketReply: boolean;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
// Получить токен из localStorage
|
||||
const getAuthHeader = () => {
|
||||
const token = localStorage.getItem('access_token');
|
||||
return token ? { Authorization: `Bearer ${token}` } : {};
|
||||
};
|
||||
|
||||
// ============ ПРОФИЛЬ ============
|
||||
|
||||
export const getProfile = async (): Promise<UserProfile> => {
|
||||
const response = await apiClient.get(`${API_URL}/profile`, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
return response.data.data;
|
||||
};
|
||||
|
||||
export const updateProfile = async (data: {
|
||||
username?: string;
|
||||
email?: string;
|
||||
phoneNumber?: string;
|
||||
timezone?: string;
|
||||
language?: string;
|
||||
}): Promise<void> => {
|
||||
await apiClient.put(`${API_URL}/profile`, data, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
};
|
||||
|
||||
// ============ БЕЗОПАСНОСТЬ ============
|
||||
|
||||
export const changePassword = async (data: {
|
||||
currentPassword: string;
|
||||
newPassword: string;
|
||||
}): Promise<void> => {
|
||||
await apiClient.post(`${API_URL}/change-password`, data, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
};
|
||||
|
||||
export const getSessions = async (): Promise<Session[]> => {
|
||||
const response = await apiClient.get(`${SESSIONS_API}`, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
return response.data; // Backend возвращает массив напрямую
|
||||
};
|
||||
|
||||
export const terminateSession = async (sessionId: number): Promise<void> => {
|
||||
await apiClient.delete(`${SESSIONS_API}/${sessionId}`, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
};
|
||||
|
||||
export const getLoginHistory = async (limit = 20): Promise<LoginHistoryEntry[]> => {
|
||||
const response = await apiClient.get(`${SESSIONS_API}/history`, {
|
||||
headers: getAuthHeader(),
|
||||
params: { limit }
|
||||
});
|
||||
return response.data; // Backend возвращает массив напрямую
|
||||
};
|
||||
|
||||
// ============ АВАТАР ============
|
||||
|
||||
export const uploadAvatar = async (file: File): Promise<{ avatarUrl: string }> => {
|
||||
const formData = new FormData();
|
||||
formData.append('avatar', file);
|
||||
|
||||
const response = await apiClient.post(`${API_URL}/avatar`, formData, {
|
||||
headers: {
|
||||
...getAuthHeader(),
|
||||
'Content-Type': 'multipart/form-data'
|
||||
}
|
||||
});
|
||||
return response.data.data;
|
||||
};
|
||||
|
||||
export const deleteAvatar = async (): Promise<void> => {
|
||||
await apiClient.delete(`${API_URL}/avatar`, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
};
|
||||
|
||||
// ============ SSH КЛЮЧИ ============
|
||||
|
||||
export const getSSHKeys = async (): Promise<SSHKey[]> => {
|
||||
const response = await apiClient.get(`${API_URL}/ssh-keys`, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
return response.data.data;
|
||||
};
|
||||
|
||||
export const addSSHKey = async (data: {
|
||||
name: string;
|
||||
publicKey: string;
|
||||
}): Promise<SSHKey> => {
|
||||
const response = await apiClient.post(`${API_URL}/ssh-keys`, data, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
return response.data.data;
|
||||
};
|
||||
|
||||
export const deleteSSHKey = async (keyId: number): Promise<void> => {
|
||||
await apiClient.delete(`${API_URL}/ssh-keys/${keyId}`, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
};
|
||||
|
||||
// ============ API КЛЮЧИ ============
|
||||
|
||||
export const getAPIKeys = async (): Promise<APIKey[]> => {
|
||||
const response = await apiClient.get(`${API_URL}/api-keys`, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
return response.data.data;
|
||||
};
|
||||
|
||||
export const createAPIKey = async (data: {
|
||||
name: string;
|
||||
permissions?: string[];
|
||||
expiresAt?: string;
|
||||
}): Promise<APIKey & { fullKey: string }> => {
|
||||
const response = await apiClient.post(`${API_URL}/api-keys`, data, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
return response.data.data;
|
||||
};
|
||||
|
||||
export const deleteAPIKey = async (keyId: number): Promise<void> => {
|
||||
await apiClient.delete(`${API_URL}/api-keys/${keyId}`, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
};
|
||||
|
||||
// ============ НАСТРОЙКИ УВЕДОМЛЕНИЙ ============
|
||||
|
||||
export const getNotificationSettings = async (): Promise<NotificationSettings> => {
|
||||
const response = await apiClient.get(`${API_URL}/notification-settings`, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
return response.data.data;
|
||||
};
|
||||
|
||||
export const updateNotificationSettings = async (
|
||||
settings: Partial<NotificationSettings>
|
||||
): Promise<void> => {
|
||||
await apiClient.put(`${API_URL}/notification-settings`, settings, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
};
|
||||
|
||||
// ============ ЭКСПОРТ ДАННЫХ ============
|
||||
|
||||
export const exportUserData = async (): Promise<Record<string, unknown>> => {
|
||||
const response = await apiClient.get(`${API_URL}/export`, {
|
||||
headers: getAuthHeader()
|
||||
});
|
||||
return response.data;
|
||||
};
|
||||
71
ospabhost/frontend/src/utils/apiClient.ts
Normal file
71
ospabhost/frontend/src/utils/apiClient.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import axios, { AxiosError } from 'axios';
|
||||
import type { InternalAxiosRequestConfig } from 'axios';
|
||||
import { API_URL } from '../config/api';
|
||||
|
||||
// Создаём экземпляр axios с базовым URL
|
||||
export const apiClient = axios.create({
|
||||
baseURL: API_URL,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
// Добавляем токен к каждому запросу
|
||||
apiClient.interceptors.request.use(
|
||||
(config: InternalAxiosRequestConfig) => {
|
||||
const token = localStorage.getItem('access_token');
|
||||
if (token && config.headers) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return config;
|
||||
},
|
||||
(error) => {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
// Обработка ответов и ошибок
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => {
|
||||
return response;
|
||||
},
|
||||
(error: AxiosError) => {
|
||||
if (error.response) {
|
||||
const status = error.response.status;
|
||||
|
||||
// Обрабатываем ошибки без автоматического перенаправления
|
||||
// Компоненты сами решают, как обрабатывать ошибки
|
||||
switch (status) {
|
||||
case 401:
|
||||
// Unauthorized - очищаем токен
|
||||
localStorage.removeItem('access_token');
|
||||
sessionStorage.clear();
|
||||
// Вызываем событие для реакции на изменение авторизации
|
||||
window.dispatchEvent(new Event('unauthorized'));
|
||||
break;
|
||||
case 403:
|
||||
// Forbidden - нет прав доступа
|
||||
console.warn('Access denied (403)');
|
||||
break;
|
||||
case 404:
|
||||
// Not Found - ресурс не найден
|
||||
console.warn('Resource not found (404)');
|
||||
break;
|
||||
case 500:
|
||||
case 502:
|
||||
case 503:
|
||||
case 504:
|
||||
// Server errors
|
||||
console.error(`Server error (${status})`);
|
||||
break;
|
||||
}
|
||||
} else if (error.request) {
|
||||
// Ошибка сети - сервер недоступен
|
||||
console.error('Network error:', error.message);
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
export default apiClient;
|
||||
49
ospabhost/frontend/src/utils/logger.ts
Normal file
49
ospabhost/frontend/src/utils/logger.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Logger utility для frontend - логирование только в development режиме
|
||||
*/
|
||||
|
||||
const isDebug = import.meta.env.MODE === 'development';
|
||||
|
||||
export const logger = {
|
||||
log: (...args: unknown[]) => {
|
||||
if (isDebug) {
|
||||
console.log(...args);
|
||||
}
|
||||
},
|
||||
|
||||
error: (...args: unknown[]) => {
|
||||
// Ошибки логируем всегда
|
||||
console.error(...args);
|
||||
},
|
||||
|
||||
warn: (...args: unknown[]) => {
|
||||
if (isDebug) {
|
||||
console.warn(...args);
|
||||
}
|
||||
},
|
||||
|
||||
info: (...args: unknown[]) => {
|
||||
if (isDebug) {
|
||||
console.info(...args);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// WebSocket специфичные логи
|
||||
export const wsLogger = {
|
||||
log: (message: string, ...args: unknown[]) => {
|
||||
if (isDebug) {
|
||||
console.log(`[WS] ${message}`, ...args);
|
||||
}
|
||||
},
|
||||
|
||||
error: (message: string, ...args: unknown[]) => {
|
||||
console.error(`[WS] ${message}`, ...args);
|
||||
},
|
||||
|
||||
warn: (message: string, ...args: unknown[]) => {
|
||||
if (isDebug) {
|
||||
console.warn(`[WS] ${message}`, ...args);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -7,8 +7,8 @@ export default {
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
'ospab-primary': '#3B82F6', // Голубой
|
||||
'ospab-accent': '#FF13F0', // Розовый
|
||||
'ospab-primary': '#2563EB', // Более тёмный синий (blue-600) для лучшего контраста
|
||||
'ospab-accent': '#DB2777', // Более тёмный розовый (pink-600) для лучшего контраста
|
||||
},
|
||||
fontFamily: {
|
||||
mono: ['Share Tech Mono', 'monospace'],
|
||||
|
||||
@@ -1,7 +1,52 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import { copyFileSync } from 'fs'
|
||||
import { resolve } from 'path'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
plugins: [
|
||||
react(),
|
||||
{
|
||||
name: 'copy-service-worker',
|
||||
writeBundle() {
|
||||
// Копируем service worker в dist при сборке
|
||||
try {
|
||||
copyFileSync(
|
||||
resolve(__dirname, 'public/service-worker.js'),
|
||||
resolve(__dirname, 'dist/service-worker.js')
|
||||
)
|
||||
console.log('✅ Service worker скопирован в dist/')
|
||||
} catch (error) {
|
||||
console.error('❌ Ошибка копирования service worker:', error)
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
build: {
|
||||
target: 'es2015', // Современные браузеры, уменьшаем полифилы
|
||||
cssCodeSplit: true,
|
||||
rollupOptions: {
|
||||
output: {
|
||||
manualChunks: {
|
||||
// Разделяем большие зависимости
|
||||
'react-vendor': ['react', 'react-dom', 'react-router-dom'],
|
||||
'ui-vendor': ['react-qr-code'],
|
||||
}
|
||||
}
|
||||
},
|
||||
minify: 'terser',
|
||||
terserOptions: {
|
||||
compress: {
|
||||
drop_console: true, // Убираем console.log в production
|
||||
drop_debugger: true,
|
||||
pure_funcs: ['console.log', 'console.info'] // Удаляем конкретные функции
|
||||
}
|
||||
},
|
||||
chunkSizeWarningLimit: 600 // Увеличим лимит предупреждения
|
||||
},
|
||||
server: {
|
||||
// Для dev сервера public файлы доступны из корня автоматически
|
||||
port: 3000
|
||||
}
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user