sitemap и тд
This commit is contained in:
7
ospabhost/frontend/.htaccess
Normal file
7
ospabhost/frontend/.htaccess
Normal file
@@ -0,0 +1,7 @@
|
||||
RewriteEngine On
|
||||
RewriteBase /
|
||||
# Если файл или папка существует — отдать как есть
|
||||
RewriteCond %{REQUEST_FILENAME} !-f
|
||||
RewriteCond %{REQUEST_FILENAME} !-d
|
||||
# Иначе — отдать index.html
|
||||
RewriteRule ^ index.html [L]
|
||||
7
ospabhost/frontend/.prettierrc
Normal file
7
ospabhost/frontend/.prettierrc
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"printWidth": 100,
|
||||
"tabWidth": 2,
|
||||
"trailingComma": "es5"
|
||||
}
|
||||
@@ -2,14 +2,96 @@
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
|
||||
|
||||
<!-- Favicons -->
|
||||
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
|
||||
<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" />
|
||||
|
||||
<!-- Viewport и основные мета теги -->
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Share+Tech+Mono&display=swap" rel="stylesheet">
|
||||
<title>ospab.host - первый хостинг в Великом Новгороде</title>
|
||||
<meta name="theme-color" content="#2563eb" />
|
||||
|
||||
<!-- SEO мета теги -->
|
||||
<meta name="description" content="ospab.host - облачные решения с надёжной инфраструктурой в Великом Новгороде." />
|
||||
<meta name="keywords" content="хостинг, облачный хостинг, VPS, VDS, виртуальные машины, ВМ, дата-центр, ЦОД, Великий Новгород, ospab, облако, серверы" />
|
||||
<meta name="author" content="ospab.team" />
|
||||
<meta name="robots" content="index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1" />
|
||||
<meta name="language" content="Russian" />
|
||||
<meta name="revisit-after" content="7 days" />
|
||||
<meta name="distribution" content="global" />
|
||||
|
||||
<!-- Open Graph (для социальных сетей) -->
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://ospab.host/" />
|
||||
<meta property="og:title" content="ospab.host - Облачный хостинг и виртуальные машины" />
|
||||
<meta property="og:description" content="Облачные решения в Великом Новгороде." />
|
||||
<meta property="og:image" content="https://ospab.host/og-image.jpg" />
|
||||
<meta property="og:site_name" content="ospab.host" />
|
||||
<meta property="og:locale" content="ru_RU" />
|
||||
|
||||
<!-- Twitter Card -->
|
||||
<meta name="twitter:card" content="summary_large_image" />
|
||||
<meta name="twitter:url" content="https://ospab.host/" />
|
||||
<meta name="twitter:title" content="ospab.host - Облачный хостинг" />
|
||||
<meta name="twitter:description" content="Надёжный облачный хостинг для ваших проектов в Великом Новгороде" />
|
||||
<meta name="twitter:image" content="https://ospab.host/og-image.jpg" />
|
||||
|
||||
<!-- Canonical URL -->
|
||||
<link rel="canonical" href="https://ospab.host/" />
|
||||
|
||||
<!-- Preconnect для производительности -->
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<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" />
|
||||
|
||||
<!-- Structured Data (JSON-LD) -->
|
||||
<script type="application/ld+json">
|
||||
{
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Organization",
|
||||
"name": "ospab.host",
|
||||
"url": "https://ospab.host",
|
||||
"logo": "https://ospab.host/logo.jpg",
|
||||
"description": "Облачные решения в Великом Новгороде.",
|
||||
"sameAs": [
|
||||
"https://github.com/Ospab"
|
||||
],
|
||||
"address": {
|
||||
"@type": "PostalAddress",
|
||||
"addressLocality": "Великий Новгород",
|
||||
"addressRegion": "Новгородская область",
|
||||
"addressCountry": "RU"
|
||||
},
|
||||
"contactPoint": {
|
||||
"@type": "ContactPoint",
|
||||
"contactType": "Customer Support",
|
||||
"areaServed": "RU",
|
||||
"availableLanguage": ["ru"]
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- WebSite Schema для поиска -->
|
||||
<script type="application/ld+json">
|
||||
{
|
||||
"@context": "https://schema.org",
|
||||
"@type": "WebSite",
|
||||
"name": "ospab.host",
|
||||
"url": "https://ospab.host",
|
||||
"potentialAction": {
|
||||
"@type": "SearchAction",
|
||||
"target": "https://ospab.host/search?q={search_term_string}",
|
||||
"query-input": "required name=search_term_string"
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<title>ospab.host - облачные решения в Великом Новгороде</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
47
ospabhost/frontend/package-lock.json
generated
47
ospabhost/frontend/package-lock.json
generated
@@ -8,9 +8,11 @@
|
||||
"name": "frontend",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@marsidev/react-turnstile": "^1.3.1",
|
||||
"axios": "^1.12.2",
|
||||
"react": "^19.1.1",
|
||||
"react-dom": "^19.1.1",
|
||||
"react-helmet-async": "^2.0.5",
|
||||
"react-icons": "^5.5.0",
|
||||
"react-qr-code": "^2.0.18",
|
||||
"xterm": "^5.3.0"
|
||||
@@ -1044,6 +1046,16 @@
|
||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||
}
|
||||
},
|
||||
"node_modules/@marsidev/react-turnstile": {
|
||||
"version": "1.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@marsidev/react-turnstile/-/react-turnstile-1.3.1.tgz",
|
||||
"integrity": "sha512-h2THG/75k4Y049hgjSGPIcajxXnh+IZAiXVbryQyVmagkboN7pJtBgR16g8akjwUBSfRrg6jw6KvPDjscQflog==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"react": "^17.0.2 || ^18.0.0 || ^19.0",
|
||||
"react-dom": "^17.0.2 || ^18.0.0 || ^19.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@nodelib/fs.scandir": {
|
||||
"version": "2.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
|
||||
@@ -3034,6 +3046,15 @@
|
||||
"node": ">=0.8.19"
|
||||
}
|
||||
},
|
||||
"node_modules/invariant": {
|
||||
"version": "2.2.4",
|
||||
"resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.4.tgz",
|
||||
"integrity": "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/is-binary-path": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz",
|
||||
@@ -3864,6 +3885,26 @@
|
||||
"react": "^19.1.1"
|
||||
}
|
||||
},
|
||||
"node_modules/react-fast-compare": {
|
||||
"version": "3.2.2",
|
||||
"resolved": "https://registry.npmjs.org/react-fast-compare/-/react-fast-compare-3.2.2.tgz",
|
||||
"integrity": "sha512-nsO+KSNgo1SbJqJEYRE9ERzo7YtYbou/OqjSQKxV7jcKox7+usiUVZOAC+XnDOABXggQTno0Y1CpVnuWEc1boQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/react-helmet-async": {
|
||||
"version": "2.0.5",
|
||||
"resolved": "https://registry.npmjs.org/react-helmet-async/-/react-helmet-async-2.0.5.tgz",
|
||||
"integrity": "sha512-rYUYHeus+i27MvFE+Jaa4WsyBKGkL6qVgbJvSBoX8mbsWoABJXdEO0bZyi0F6i+4f0NuIb8AvqPMj3iXFHkMwg==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"invariant": "^2.2.4",
|
||||
"react-fast-compare": "^3.2.2",
|
||||
"shallowequal": "^1.1.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^16.6.0 || ^17.0.0 || ^18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-icons": {
|
||||
"version": "5.5.0",
|
||||
"resolved": "https://registry.npmjs.org/react-icons/-/react-icons-5.5.0.tgz",
|
||||
@@ -4095,6 +4136,12 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/shallowequal": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/shallowequal/-/shallowequal-1.1.0.tgz",
|
||||
"integrity": "sha512-y0m1JoUZSlPAjXVtPPW70aZWfIL/dSP7AFkRnniLCrK/8MDKog3TySTBmckD+RObVxH0v4Tox67+F14PdED2oQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/shebang-command": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
|
||||
|
||||
@@ -10,9 +10,11 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@marsidev/react-turnstile": "^1.3.1",
|
||||
"axios": "^1.12.2",
|
||||
"react": "^19.1.1",
|
||||
"react-dom": "^19.1.1",
|
||||
"react-helmet-async": "^2.0.5",
|
||||
"react-icons": "^5.5.0",
|
||||
"react-qr-code": "^2.0.18",
|
||||
"xterm": "^5.3.0"
|
||||
|
||||
7
ospabhost/frontend/public/.htaccess
Normal file
7
ospabhost/frontend/public/.htaccess
Normal file
@@ -0,0 +1,7 @@
|
||||
RewriteEngine On
|
||||
RewriteBase /
|
||||
# Если файл или папка существует — отдать как есть
|
||||
RewriteCond %{REQUEST_FILENAME} !-f
|
||||
RewriteCond %{REQUEST_FILENAME} !-d
|
||||
# Иначе — отдать index.html
|
||||
RewriteRule ^ index.html [L]
|
||||
24
ospabhost/frontend/public/robots.txt
Normal file
24
ospabhost/frontend/public/robots.txt
Normal file
@@ -0,0 +1,24 @@
|
||||
User-agent: *
|
||||
Allow: /
|
||||
Allow: /about
|
||||
Allow: /tariffs
|
||||
Allow: /login
|
||||
Allow: /register
|
||||
Allow: /terms
|
||||
|
||||
Disallow: /dashboard
|
||||
Disallow: /api/
|
||||
Disallow: /admin
|
||||
Disallow: /private
|
||||
|
||||
Sitemap: https://ospab.host/sitemap.xml
|
||||
|
||||
# Yandex
|
||||
User-agent: Yandexbot
|
||||
Allow: /
|
||||
Crawl-delay: 0
|
||||
|
||||
# Google
|
||||
User-agent: Googlebot
|
||||
Allow: /
|
||||
Crawl-delay: 0
|
||||
@@ -1,4 +1,5 @@
|
||||
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
|
||||
import { useEffect } from 'react';
|
||||
import { BrowserRouter as Router, Route, Routes, useLocation } from 'react-router-dom';
|
||||
import Pagetempl from './components/pagetempl';
|
||||
import DashboardTempl from './components/dashboardtempl';
|
||||
import Homepage from './pages/index';
|
||||
@@ -9,35 +10,212 @@ import TariffsPage from './pages/tariffs';
|
||||
import Aboutpage from './pages/about';
|
||||
import Privacy from './pages/privacy';
|
||||
import Terms from './pages/terms';
|
||||
import NotFound from './pages/404';
|
||||
import ServerError from './pages/500';
|
||||
import Privateroute from './components/privateroute';
|
||||
import { AuthProvider } from './context/authcontext';
|
||||
import ErrorBoundary from './components/ErrorBoundary';
|
||||
import { ToastProvider } from './components/Toast';
|
||||
|
||||
// SEO конфиг для всех маршрутов
|
||||
const SEO_CONFIG: Record<string, {
|
||||
title: string;
|
||||
description: string;
|
||||
keywords: string;
|
||||
og?: {
|
||||
title: string;
|
||||
description: string;
|
||||
image: string;
|
||||
url: string;
|
||||
};
|
||||
}> = {
|
||||
'/': {
|
||||
title: 'Облачный хостинг и виртуальные машины',
|
||||
description: 'Ospab.host - надёжный облачный хостинг и виртуальные машины (VPS/VDS) в Великом Новгороде. Запускайте и масштабируйте проекты с высокой производительностью, 24/7 поддержкой и доступными ценами.',
|
||||
keywords: 'хостинг, облачный хостинг, VPS, VDS, виртуальные машины, дата-центр, Великий Новгород',
|
||||
og: {
|
||||
title: 'Ospab.host - Облачный хостинг',
|
||||
description: 'Запускайте и масштабируйте проекты с надёжной инфраструктурой',
|
||||
image: 'https://ospab.host/og-image.jpg',
|
||||
url: 'https://ospab.host/',
|
||||
},
|
||||
},
|
||||
'/about': {
|
||||
title: 'О компании',
|
||||
description: 'Узнайте о Ospab.host - первом облачном хостинге в Великом Новгороде. История создания, миссия и видение компании. Основатель Георгий Сыралёв.',
|
||||
keywords: 'об ospab, история хостинга, облачные решения, Великий Новгород',
|
||||
og: {
|
||||
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, вход в хостинг',
|
||||
og: {
|
||||
title: 'Вход в Ospab.host',
|
||||
description: 'Логин в личный кабинет',
|
||||
image: 'https://ospab.host/og-image.jpg',
|
||||
url: 'https://ospab.host/login',
|
||||
},
|
||||
},
|
||||
'/register': {
|
||||
title: 'Регистрация',
|
||||
description: 'Зарегистрируйтесь в Ospab.host и начните пользоваться облачным хостингом. Создайте аккаунт бесплатно за 2 минуты и получите бонус.',
|
||||
keywords: 'регистрация, создать аккаунт, ospab регистрация, регистрация хостинга',
|
||||
og: {
|
||||
title: 'Регистрация в Ospab.host',
|
||||
description: 'Создайте аккаунт и начните пользоваться хостингом',
|
||||
image: 'https://ospab.host/og-image.jpg',
|
||||
url: 'https://ospab.host/register',
|
||||
},
|
||||
},
|
||||
'/terms': {
|
||||
title: 'Условия использования',
|
||||
description: 'Условия использования сервиса Ospab.host. Ознакомьтесь с полными правилами и требованиями для пользователей хостинга.',
|
||||
keywords: 'условия использования, пользовательское соглашение, правила использования',
|
||||
og: {
|
||||
title: 'Условия использования Ospab.host',
|
||||
description: 'Полные условия использования сервиса',
|
||||
image: 'https://ospab.host/og-image.jpg',
|
||||
url: 'https://ospab.host/terms',
|
||||
},
|
||||
},
|
||||
'/privacy': {
|
||||
title: 'Политика конфиденциальности',
|
||||
description: 'Политика конфиденциальности Ospab.host. Узнайте как мы защищаем ваши персональные данные и информацию о приватности.',
|
||||
keywords: 'политика конфиденциальности, приватность, защита данных, GDPR',
|
||||
og: {
|
||||
title: 'Политика конфиденциальности Ospab.host',
|
||||
description: 'Узнайте о защите ваших данных',
|
||||
image: 'https://ospab.host/og-image.jpg',
|
||||
url: 'https://ospab.host/privacy',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// Компонент для обновления SEO при изменении маршрута
|
||||
function SEOUpdater() {
|
||||
const location = useLocation();
|
||||
|
||||
useEffect(() => {
|
||||
const pathname = location.pathname;
|
||||
|
||||
// Получаем SEO данные для текущего маршрута, иначе используем дефолтные
|
||||
const seoData = SEO_CONFIG[pathname] || {
|
||||
title: 'Ospab.host - Облачный хостинг',
|
||||
description: 'Ospab.host - надёжный облачный хостинг и виртуальные машины в Великом Новгороде.',
|
||||
keywords: 'хостинг, облачный хостинг, VPS, VDS',
|
||||
};
|
||||
|
||||
// Устанавливаем title
|
||||
document.title = `${seoData.title} - Ospab.host`;
|
||||
|
||||
// Функция для установки или обновления meta тега
|
||||
const setMeta = (name: string, content: string, isProperty = false) => {
|
||||
let tag = document.querySelector(
|
||||
isProperty ? `meta[property="${name}"]` : `meta[name="${name}"]`
|
||||
) as HTMLMetaElement | null;
|
||||
|
||||
if (!tag) {
|
||||
tag = document.createElement('meta');
|
||||
if (isProperty) {
|
||||
tag.setAttribute('property', name);
|
||||
} else {
|
||||
tag.setAttribute('name', name);
|
||||
}
|
||||
document.head.appendChild(tag);
|
||||
}
|
||||
|
||||
tag.setAttribute('content', content);
|
||||
};
|
||||
|
||||
// Основные SEO теги
|
||||
setMeta('description', seoData.description);
|
||||
setMeta('keywords', seoData.keywords);
|
||||
|
||||
// Canonical URL
|
||||
let canonicalTag = document.querySelector('link[rel="canonical"]') as HTMLLinkElement | null;
|
||||
if (!canonicalTag) {
|
||||
canonicalTag = document.createElement('link');
|
||||
canonicalTag.setAttribute('rel', 'canonical');
|
||||
document.head.appendChild(canonicalTag);
|
||||
}
|
||||
canonicalTag.setAttribute('href', `https://ospab.host${pathname}`);
|
||||
|
||||
// Open Graph теги
|
||||
if (seoData.og) {
|
||||
setMeta('og:type', 'website', true);
|
||||
setMeta('og:title', seoData.og.title, true);
|
||||
setMeta('og:description', seoData.og.description, true);
|
||||
setMeta('og:image', seoData.og.image, true);
|
||||
setMeta('og:url', seoData.og.url, true);
|
||||
setMeta('og:site_name', 'Ospab.host', true);
|
||||
setMeta('og:locale', 'ru_RU', true);
|
||||
|
||||
// Twitter Card
|
||||
setMeta('twitter:card', 'summary_large_image');
|
||||
setMeta('twitter:title', seoData.og.title);
|
||||
setMeta('twitter:description', seoData.og.description);
|
||||
setMeta('twitter:image', seoData.og.image);
|
||||
}
|
||||
|
||||
// Скроллим вверх при навигации
|
||||
window.scrollTo(0, 0);
|
||||
}, [location.pathname]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<Router>
|
||||
<SEOUpdater />
|
||||
<AuthProvider>
|
||||
<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={<Pagetempl><Privacy /></Pagetempl>} />
|
||||
<Route path="/terms" element={<Pagetempl><Terms /></Pagetempl>} />
|
||||
<Route path="/login" element={<Pagetempl><Loginpage /></Pagetempl>} />
|
||||
<Route path="/register" element={<Pagetempl><Registerpage /></Pagetempl>} />
|
||||
|
||||
{/* Дашборд без footer */}
|
||||
<Route path="/dashboard/*" element={
|
||||
<DashboardTempl>
|
||||
<Privateroute>
|
||||
<Dashboard />
|
||||
</Privateroute>
|
||||
</DashboardTempl>
|
||||
} />
|
||||
</Routes>
|
||||
<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>
|
||||
} />
|
||||
|
||||
{/* Страницы ошибок */}
|
||||
<Route path="/500" element={<ServerError />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</ErrorBoundary>
|
||||
</ToastProvider>
|
||||
</AuthProvider>
|
||||
</Router>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
export default App;
|
||||
49
ospabhost/frontend/src/components/ErrorBoundary.tsx
Normal file
49
ospabhost/frontend/src/components/ErrorBoundary.tsx
Normal file
@@ -0,0 +1,49 @@
|
||||
import React from 'react';
|
||||
|
||||
interface ErrorBoundaryState {
|
||||
hasError: boolean;
|
||||
error: Error | null;
|
||||
}
|
||||
|
||||
export class ErrorBoundary extends React.Component<{ children: React.ReactNode }, ErrorBoundaryState> {
|
||||
constructor(props: { children: React.ReactNode }) {
|
||||
super(props);
|
||||
this.state = { hasError: false, error: null };
|
||||
}
|
||||
|
||||
static getDerivedStateFromError(error: Error) {
|
||||
return { hasError: true, error };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
|
||||
// Отправка ошибки в сервис мониторинга
|
||||
console.error('ErrorBoundary caught:', error, errorInfo);
|
||||
|
||||
// Перенаправление на страницу 500 через 2 секунды
|
||||
setTimeout(() => {
|
||||
window.location.href = '/500';
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.hasError) {
|
||||
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-md w-full mx-auto px-6 py-12 text-center">
|
||||
<div className="animate-spin rounded-full h-16 w-16 border-b-4 border-red-600 mx-auto mb-6"></div>
|
||||
<h2 className="text-2xl font-bold text-gray-800 mb-4">
|
||||
Произошла ошибка
|
||||
</h2>
|
||||
<p className="text-gray-600 mb-2">{this.state.error?.message}</p>
|
||||
<p className="text-sm text-gray-500">
|
||||
Перенаправление на страницу ошибки...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
export default ErrorBoundary;
|
||||
220
ospabhost/frontend/src/components/Modal.tsx
Normal file
220
ospabhost/frontend/src/components/Modal.tsx
Normal file
@@ -0,0 +1,220 @@
|
||||
import React, { useEffect } from 'react';
|
||||
|
||||
interface ModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
title: string;
|
||||
children: React.ReactNode;
|
||||
onConfirm?: () => void;
|
||||
confirmText?: string;
|
||||
cancelText?: string;
|
||||
type?: 'info' | 'warning' | 'danger';
|
||||
}
|
||||
|
||||
export const Modal: React.FC<ModalProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
title,
|
||||
children,
|
||||
onConfirm,
|
||||
confirmText = 'Подтвердить',
|
||||
cancelText = 'Отмена',
|
||||
type = 'info'
|
||||
}) => {
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
document.body.style.overflow = 'hidden';
|
||||
} else {
|
||||
document.body.style.overflow = 'unset';
|
||||
}
|
||||
return () => {
|
||||
document.body.style.overflow = 'unset';
|
||||
};
|
||||
}, [isOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleEscape = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && isOpen) {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', handleEscape);
|
||||
return () => document.removeEventListener('keydown', handleEscape);
|
||||
}, [isOpen, onClose]);
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
const getTypeStyles = () => {
|
||||
switch (type) {
|
||||
case 'warning':
|
||||
return {
|
||||
icon: '⚠️',
|
||||
iconBg: 'bg-yellow-100',
|
||||
iconColor: 'text-yellow-600',
|
||||
buttonBg: 'bg-yellow-600 hover:bg-yellow-700'
|
||||
};
|
||||
case 'danger':
|
||||
return {
|
||||
icon: '🗑️',
|
||||
iconBg: 'bg-red-100',
|
||||
iconColor: 'text-red-600',
|
||||
buttonBg: 'bg-red-600 hover:bg-red-700'
|
||||
};
|
||||
default:
|
||||
return {
|
||||
icon: 'ℹ️',
|
||||
iconBg: 'bg-blue-100',
|
||||
iconColor: 'text-blue-600',
|
||||
buttonBg: 'bg-blue-600 hover:bg-blue-700'
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const styles = getTypeStyles();
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center">
|
||||
{/* Backdrop */}
|
||||
<div
|
||||
className="absolute inset-0 bg-black bg-opacity-50 backdrop-blur-sm transition-opacity"
|
||||
onClick={onClose}
|
||||
/>
|
||||
|
||||
{/* Modal */}
|
||||
<div className="relative bg-white dark:bg-gray-800 rounded-lg shadow-2xl max-w-md w-full mx-4 transform transition-all animate-modal-enter">
|
||||
{/* Header */}
|
||||
<div className="flex items-start p-6 border-b border-gray-200 dark:border-gray-700">
|
||||
<div className={`flex-shrink-0 ${styles.iconBg} rounded-full p-3 mr-4`}>
|
||||
<span className={`text-2xl ${styles.iconColor}`}>{styles.icon}</span>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h3 className="text-xl font-semibold text-gray-900 dark:text-white">
|
||||
{title}
|
||||
</h3>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="ml-4 text-gray-400 hover:text-gray-500 dark:hover:text-gray-300 transition-colors"
|
||||
>
|
||||
<svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="p-6 text-gray-700 dark:text-gray-300">
|
||||
{children}
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="flex items-center justify-end gap-3 p-6 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900 rounded-b-lg">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors"
|
||||
>
|
||||
{cancelText}
|
||||
</button>
|
||||
{onConfirm && (
|
||||
<button
|
||||
onClick={() => {
|
||||
onConfirm();
|
||||
onClose();
|
||||
}}
|
||||
className={`px-4 py-2 text-sm font-medium text-white rounded-lg transition-colors ${styles.buttonBg}`}
|
||||
>
|
||||
{confirmText}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Компонент для модального окна с вводом текста
|
||||
interface PromptModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
title: string;
|
||||
message: string;
|
||||
onConfirm: (value: string) => void;
|
||||
placeholder?: string;
|
||||
defaultValue?: string;
|
||||
}
|
||||
|
||||
export const PromptModal: React.FC<PromptModalProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
title,
|
||||
message,
|
||||
onConfirm,
|
||||
placeholder = '',
|
||||
defaultValue = ''
|
||||
}) => {
|
||||
const [value, setValue] = React.useState(defaultValue);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setValue(defaultValue);
|
||||
}
|
||||
}, [isOpen, defaultValue]);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
onConfirm(value);
|
||||
onClose();
|
||||
};
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center">
|
||||
<div
|
||||
className="absolute inset-0 bg-black bg-opacity-50 backdrop-blur-sm"
|
||||
onClick={onClose}
|
||||
/>
|
||||
<div className="relative bg-white dark:bg-gray-800 rounded-lg shadow-2xl max-w-md w-full mx-4">
|
||||
<div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
|
||||
<h3 className="text-xl font-semibold text-gray-900 dark:text-white">{title}</h3>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-gray-400 hover:text-gray-500 dark:hover:text-gray-300"
|
||||
>
|
||||
<svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="p-6">
|
||||
<p className="text-gray-700 dark:text-gray-300 mb-4">{message}</p>
|
||||
<input
|
||||
type="text"
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
placeholder={placeholder}
|
||||
className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-end gap-3 p-6 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900 rounded-b-lg">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600"
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700"
|
||||
>
|
||||
Подтвердить
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
43
ospabhost/frontend/src/components/SEO.tsx
Normal file
43
ospabhost/frontend/src/components/SEO.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
import { Helmet } from 'react-helmet-async';
|
||||
|
||||
interface SEOProps {
|
||||
title: string;
|
||||
description: string;
|
||||
keywords?: string;
|
||||
canonical?: string;
|
||||
ogTitle?: string;
|
||||
ogDescription?: string;
|
||||
ogImage?: string;
|
||||
ogUrl?: string;
|
||||
}
|
||||
|
||||
export const SEO: React.FC<SEOProps> = ({
|
||||
title,
|
||||
description,
|
||||
keywords,
|
||||
canonical,
|
||||
ogTitle,
|
||||
ogDescription,
|
||||
ogImage,
|
||||
ogUrl,
|
||||
}) => {
|
||||
return (
|
||||
<Helmet>
|
||||
<title>{title} - Ospab.host</title>
|
||||
<meta name="description" content={description} />
|
||||
{keywords && <meta name="keywords" content={keywords} />}
|
||||
{canonical && <link rel="canonical" href={canonical} />}
|
||||
|
||||
{/* Open Graph */}
|
||||
<meta property="og:title" content={ogTitle || title} />
|
||||
<meta property="og:description" content={ogDescription || description} />
|
||||
{ogImage && <meta property="og:image" content={ogImage} />}
|
||||
{ogUrl && <meta property="og:url" content={ogUrl} />}
|
||||
|
||||
{/* Twitter Card */}
|
||||
<meta name="twitter:title" content={ogTitle || title} />
|
||||
<meta name="twitter:description" content={ogDescription || description} />
|
||||
{ogImage && <meta name="twitter:image" content={ogImage} />}
|
||||
</Helmet>
|
||||
);
|
||||
};
|
||||
@@ -1,120 +0,0 @@
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { Terminal } from 'xterm';
|
||||
import 'xterm/css/xterm.css';
|
||||
|
||||
const ServerConsole: React.FC = () => {
|
||||
const { id } = useParams();
|
||||
const termRef = useRef<HTMLDivElement>(null);
|
||||
const wsRef = useRef<WebSocket | null>(null);
|
||||
const xtermRef = useRef<Terminal | null>(null);
|
||||
const reconnectAttempts = useRef(0);
|
||||
|
||||
// Логгер ошибок
|
||||
const logError = (msg: string, err?: unknown) => {
|
||||
console.error('[Console]', msg, err);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
let disposed = false;
|
||||
if (!termRef.current) return;
|
||||
let term: Terminal | null = null;
|
||||
try {
|
||||
term = new Terminal({
|
||||
rows: 24,
|
||||
cols: 80,
|
||||
fontSize: 16,
|
||||
theme: {
|
||||
background: '#18181b',
|
||||
foreground: '#e5e7eb',
|
||||
},
|
||||
cursorBlink: true,
|
||||
});
|
||||
term.open(termRef.current);
|
||||
xtermRef.current = term;
|
||||
} catch (err) {
|
||||
logError('Ошибка инициализации xterm', err);
|
||||
return;
|
||||
}
|
||||
|
||||
// Resize обработка
|
||||
const handleResize = () => {
|
||||
try {
|
||||
term?.resize(
|
||||
Math.floor(termRef.current?.offsetWidth ? termRef.current.offsetWidth / 9 : 80),
|
||||
Math.floor(termRef.current?.offsetHeight ? termRef.current.offsetHeight / 20 : 24)
|
||||
);
|
||||
} catch (err) {
|
||||
logError('Ошибка resize терминала', err);
|
||||
}
|
||||
};
|
||||
window.addEventListener('resize', handleResize);
|
||||
setTimeout(handleResize, 100);
|
||||
|
||||
// WebSocket с авто-подключением
|
||||
const connectWS = () => {
|
||||
if (disposed) return;
|
||||
const ws = new WebSocket(`wss://ospab.host:5000/api/server/${id}/console`);
|
||||
wsRef.current = ws;
|
||||
|
||||
ws.onopen = () => {
|
||||
reconnectAttempts.current = 0;
|
||||
term?.write('\x1b[32mПодключено к серверу\x1b[0m\r\n');
|
||||
};
|
||||
ws.onmessage = (event) => {
|
||||
try {
|
||||
term?.write(event.data);
|
||||
} catch (err) {
|
||||
logError('Ошибка вывода данных в терминал', err);
|
||||
}
|
||||
};
|
||||
ws.onclose = (event) => {
|
||||
logError('WebSocket закрыт', event);
|
||||
term?.write('\r\n\x1b[31mОтключено от сервера\x1b[0m\r\n');
|
||||
// Авто-подключение (до 5 попыток)
|
||||
if (!disposed && reconnectAttempts.current < 5) {
|
||||
reconnectAttempts.current++;
|
||||
setTimeout(connectWS, 1000 * reconnectAttempts.current);
|
||||
}
|
||||
};
|
||||
ws.onerror = (event) => {
|
||||
logError('WebSocket ошибка', event);
|
||||
term?.write('\r\n\x1b[31mОшибка соединения\x1b[0m\r\n');
|
||||
};
|
||||
|
||||
term?.onData((data: string) => {
|
||||
try {
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(data);
|
||||
}
|
||||
} catch (err) {
|
||||
logError('Ошибка отправки данных по WebSocket', err);
|
||||
}
|
||||
});
|
||||
};
|
||||
connectWS();
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
try {
|
||||
wsRef.current?.close();
|
||||
} catch (err) {
|
||||
logError('Ошибка закрытия WebSocket', err);
|
||||
}
|
||||
try {
|
||||
term?.dispose();
|
||||
} catch (err) {
|
||||
logError('Ошибка dispose терминала', err);
|
||||
}
|
||||
window.removeEventListener('resize', handleResize);
|
||||
};
|
||||
}, [id]);
|
||||
|
||||
return (
|
||||
<div className="bg-black rounded-xl p-2 w-full h-[500px]">
|
||||
<div ref={termRef} style={{ width: '100%', height: '100%' }} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ServerConsole;
|
||||
30
ospabhost/frontend/src/components/StructuredData.tsx
Normal file
30
ospabhost/frontend/src/components/StructuredData.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
export const StructuredData = () => {
|
||||
const schema = {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Organization",
|
||||
"name": "Ospab.host",
|
||||
"url": "https://ospab.host",
|
||||
"logo": "https://ospab.host/logo.jpg",
|
||||
"description": "Облачный хостинг и виртуальные машины с высокопроизводительной инфраструктурой",
|
||||
"sameAs": [
|
||||
"https://github.com/Ospab"
|
||||
],
|
||||
"address": {
|
||||
"@type": "PostalAddress",
|
||||
"addressLocality": "Великий Новгород",
|
||||
"addressCountry": "RU"
|
||||
},
|
||||
"contactPoint": {
|
||||
"@type": "ContactPoint",
|
||||
"contactType": "Support",
|
||||
"areaServed": "RU"
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<script
|
||||
type="application/ld+json"
|
||||
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
|
||||
/>
|
||||
);
|
||||
};
|
||||
149
ospabhost/frontend/src/components/Toast.tsx
Normal file
149
ospabhost/frontend/src/components/Toast.tsx
Normal file
@@ -0,0 +1,149 @@
|
||||
import React, { createContext, useContext, useState, useCallback } from 'react';
|
||||
|
||||
export type ToastType = 'success' | 'error' | 'warning' | 'info';
|
||||
|
||||
export interface Toast {
|
||||
id: string;
|
||||
message: string;
|
||||
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[]>([]);
|
||||
|
||||
const removeToast = useCallback((id: string) => {
|
||||
setToasts((prev) => prev.filter((toast) => toast.id !== id));
|
||||
}, []);
|
||||
|
||||
const addToast = useCallback((message: string, type: ToastType = 'info') => {
|
||||
const id = Math.random().toString(36).substring(2, 9);
|
||||
const newToast: Toast = { id, message, type };
|
||||
|
||||
setToasts((prev) => [...prev, newToast]);
|
||||
|
||||
// Автоматическое удаление через 5 секунд
|
||||
setTimeout(() => {
|
||||
removeToast(id);
|
||||
}, 5000);
|
||||
}, [removeToast]);
|
||||
|
||||
return (
|
||||
<ToastContext.Provider value={{ toasts, addToast, removeToast }}>
|
||||
{children}
|
||||
<ToastContainer toasts={toasts} removeToast={removeToast} />
|
||||
</ToastContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
interface ToastContainerProps {
|
||||
toasts: Toast[];
|
||||
removeToast: (id: string) => void;
|
||||
}
|
||||
|
||||
const ToastContainer: React.FC<ToastContainerProps> = ({ toasts, removeToast }) => {
|
||||
return (
|
||||
<div className="fixed bottom-4 right-4 z-50 flex flex-col gap-2 max-w-sm w-full pointer-events-none">
|
||||
{toasts.map((toast, index) => (
|
||||
<ToastItem
|
||||
key={toast.id}
|
||||
toast={toast}
|
||||
onClose={() => removeToast(toast.id)}
|
||||
index={index}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
interface ToastItemProps {
|
||||
toast: Toast;
|
||||
onClose: () => void;
|
||||
index: number;
|
||||
}
|
||||
|
||||
const ToastItem: React.FC<ToastItemProps> = ({ toast, onClose, index }) => {
|
||||
const getToastStyles = () => {
|
||||
switch (toast.type) {
|
||||
case 'success':
|
||||
return {
|
||||
bg: 'bg-green-500',
|
||||
icon: (
|
||||
<svg className="w-5 h-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
)
|
||||
};
|
||||
case 'error':
|
||||
return {
|
||||
bg: 'bg-red-500',
|
||||
icon: (
|
||||
<svg className="w-5 h-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
)
|
||||
};
|
||||
case 'warning':
|
||||
return {
|
||||
bg: 'bg-yellow-500',
|
||||
icon: (
|
||||
<svg className="w-5 h-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<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>
|
||||
)
|
||||
};
|
||||
default:
|
||||
return {
|
||||
bg: 'bg-blue-500',
|
||||
icon: (
|
||||
<svg className="w-5 h-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
)
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const styles = getToastStyles();
|
||||
|
||||
return (
|
||||
<div
|
||||
className="pointer-events-auto transform transition-all duration-300 ease-out animate-toast-enter"
|
||||
style={{
|
||||
animation: `toast-enter 0.3s ease-out ${index * 0.1}s both`
|
||||
}}
|
||||
>
|
||||
<div className={`${styles.bg} text-white px-4 py-3 rounded-lg shadow-lg flex items-center gap-3 min-w-[300px]`}>
|
||||
<div className="flex-shrink-0">
|
||||
{styles.icon}
|
||||
</div>
|
||||
<div className="flex-1 text-sm font-medium">
|
||||
{toast.message}
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="flex-shrink-0 text-white hover:text-gray-200 transition-colors"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,48 +1,123 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useState } from 'react';
|
||||
import useAuth from '../context/useAuth';
|
||||
import logo from '../assets/logo.svg';
|
||||
|
||||
const Header = () => {
|
||||
const { isLoggedIn, logout } = useAuth();
|
||||
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
|
||||
|
||||
const handleLogout = () => {
|
||||
logout();
|
||||
setIsMobileMenuOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<header className="static bg-white shadow-md">
|
||||
<div className="container mx-auto px-4 py-4 flex justify-between items-center">
|
||||
<div className="flex items-center gap-1">
|
||||
<Link to="/" className="flex items-center">
|
||||
<img src={logo} alt="Логотип" className="h-14 w-auto mr-2" />
|
||||
<span className="font-mono text-2xl text-gray-800 font-bold">ospab.host</span>
|
||||
</Link>
|
||||
</div>
|
||||
<div className="flex items-center space-x-4">
|
||||
<Link to="/tariffs" 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>
|
||||
<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"
|
||||
>
|
||||
Выйти
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Link to="/login" className="text-gray-600 hover:text-ospab-primary transition-colors">Войти</Link>
|
||||
<Link
|
||||
to="/register"
|
||||
className="px-4 py-2 rounded-full text-white font-bold transition-colors transform hover:scale-105 bg-ospab-primary hover:bg-ospab-accent"
|
||||
>
|
||||
Зарегистрироваться
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
<div className="container mx-auto px-4 py-4">
|
||||
<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" />
|
||||
<span className="font-mono text-xl lg:text-2xl text-gray-800 font-bold">ospab.host</span>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* 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="/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>
|
||||
<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"
|
||||
>
|
||||
Выйти
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Link to="/login" className="text-gray-600 hover:text-ospab-primary transition-colors">Войти</Link>
|
||||
<Link
|
||||
to="/register"
|
||||
className="px-4 py-2 rounded-full text-white font-bold transition-colors transform hover:scale-105 bg-ospab-primary hover:bg-ospab-accent"
|
||||
>
|
||||
Зарегистрироваться
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Mobile Menu Button */}
|
||||
<button
|
||||
onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
|
||||
className="md:hidden p-2 text-gray-800"
|
||||
>
|
||||
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
{isMobileMenuOpen ? (
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
) : (
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
|
||||
)}
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Mobile Menu */}
|
||||
{isMobileMenuOpen && (
|
||||
<div className="md:hidden mt-4 pb-4 space-y-2 border-t border-gray-200 pt-4">
|
||||
<Link
|
||||
to="/tariffs"
|
||||
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"
|
||||
onClick={() => setIsMobileMenuOpen(false)}
|
||||
>
|
||||
О нас
|
||||
</Link>
|
||||
{isLoggedIn ? (
|
||||
<>
|
||||
<Link
|
||||
to="/dashboard"
|
||||
className="block py-2 text-gray-600 hover:text-ospab-primary transition-colors"
|
||||
onClick={() => setIsMobileMenuOpen(false)}
|
||||
>
|
||||
Личный кабинет
|
||||
</Link>
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="w-full text-left py-2 text-gray-600 hover:text-red-500 transition-colors"
|
||||
>
|
||||
Выйти
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Link
|
||||
to="/login"
|
||||
className="block py-2 text-gray-600 hover:text-ospab-primary transition-colors"
|
||||
onClick={() => setIsMobileMenuOpen(false)}
|
||||
>
|
||||
Войти
|
||||
</Link>
|
||||
<Link
|
||||
to="/register"
|
||||
className="block w-full text-center mt-2 px-4 py-2 rounded-full text-white font-bold bg-ospab-primary hover:bg-ospab-accent"
|
||||
onClick={() => setIsMobileMenuOpen(false)}
|
||||
>
|
||||
Зарегистрироваться
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
|
||||
95
ospabhost/frontend/src/components/modalHelpers.tsx
Normal file
95
ospabhost/frontend/src/components/modalHelpers.tsx
Normal file
@@ -0,0 +1,95 @@
|
||||
// Утилиты для совместимости со старым кодом, использующим alert/confirm/prompt
|
||||
// Этот файл позволяет заменить window.alert/confirm/prompt на наши компоненты
|
||||
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { Modal, PromptModal } from './Modal';
|
||||
|
||||
// Улучшенный alert через toast (если доступен) или через модальное окно
|
||||
export const showAlert = (message: string, type: 'success' | 'error' | 'info' | 'warning' = 'info'): Promise<void> => {
|
||||
return new Promise((resolve) => {
|
||||
const container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
|
||||
const handleClose = () => {
|
||||
root.unmount();
|
||||
document.body.removeChild(container);
|
||||
resolve();
|
||||
};
|
||||
|
||||
const iconMap = {
|
||||
success: '✅',
|
||||
error: '❌',
|
||||
info: 'ℹ️',
|
||||
warning: '⚠️'
|
||||
};
|
||||
|
||||
root.render(
|
||||
<Modal
|
||||
isOpen={true}
|
||||
onClose={handleClose}
|
||||
title={iconMap[type] + ' Уведомление'}
|
||||
type={type === 'success' ? 'info' : type === 'error' ? 'danger' : type}
|
||||
confirmText="OK"
|
||||
>
|
||||
<p>{message}</p>
|
||||
</Modal>
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
// Улучшенный confirm через модальное окно
|
||||
export const showConfirm = (message: string, title: string = 'Подтвердите действие'): Promise<boolean> => {
|
||||
return new Promise((resolve) => {
|
||||
const container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
|
||||
const handleClose = (result: boolean) => {
|
||||
root.unmount();
|
||||
document.body.removeChild(container);
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
root.render(
|
||||
<Modal
|
||||
isOpen={true}
|
||||
onClose={() => handleClose(false)}
|
||||
title={title}
|
||||
type="warning"
|
||||
onConfirm={() => handleClose(true)}
|
||||
confirmText="Да"
|
||||
cancelText="Отмена"
|
||||
>
|
||||
<p>{message}</p>
|
||||
</Modal>
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
// Улучшенный prompt через модальное окно
|
||||
export const showPrompt = (message: string, title: string = 'Введите значение', defaultValue: string = ''): Promise<string | null> => {
|
||||
return new Promise((resolve) => {
|
||||
const container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
|
||||
const handleClose = (value: string | null) => {
|
||||
root.unmount();
|
||||
document.body.removeChild(container);
|
||||
resolve(value);
|
||||
};
|
||||
|
||||
root.render(
|
||||
<PromptModal
|
||||
isOpen={true}
|
||||
onClose={() => handleClose(null)}
|
||||
title={title}
|
||||
message={message}
|
||||
onConfirm={(value) => handleClose(value)}
|
||||
defaultValue={defaultValue}
|
||||
placeholder="Введите значение..."
|
||||
/>
|
||||
);
|
||||
});
|
||||
};
|
||||
9
ospabhost/frontend/src/config/api.ts
Normal file
9
ospabhost/frontend/src/config/api.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Централизованная конфигурация API
|
||||
*/
|
||||
|
||||
// API URL - напрямую на порт 5000
|
||||
export const API_URL = import.meta.env.VITE_API_URL || 'https://ospab.host:5000';
|
||||
|
||||
// WebSocket URL - напрямую на порт 5000
|
||||
export const SOCKET_URL = import.meta.env.VITE_SOCKET_URL || 'wss://ospab.host:5000';
|
||||
26
ospabhost/frontend/src/constants/statuses.ts
Normal file
26
ospabhost/frontend/src/constants/statuses.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
// Статусы для серверов, чеков, тикетов и т.д.
|
||||
export const SERVER_STATUSES = [
|
||||
'creating',
|
||||
'running',
|
||||
'stopped',
|
||||
'blocked',
|
||||
'deleted',
|
||||
];
|
||||
|
||||
export const CHECK_STATUSES = [
|
||||
'pending',
|
||||
'approved',
|
||||
'rejected',
|
||||
];
|
||||
|
||||
export const TICKET_STATUSES = [
|
||||
'open',
|
||||
'closed',
|
||||
'waiting',
|
||||
];
|
||||
|
||||
export const USER_ROLES = [
|
||||
'user',
|
||||
'operator',
|
||||
'admin',
|
||||
];
|
||||
@@ -1,10 +1,9 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import io from 'socket.io-client';
|
||||
import { SOCKET_URL } from '../config/api';
|
||||
|
||||
type Socket = SocketIOClient.Socket;
|
||||
|
||||
const SOCKET_URL = 'http://localhost:5000';
|
||||
|
||||
export function useSocket() {
|
||||
const [socket, setSocket] = useState<Socket | null>(null);
|
||||
const [connected, setConnected] = useState(false);
|
||||
|
||||
@@ -1,3 +1,34 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
@tailwind utilities;
|
||||
|
||||
/* Анимации для модальных окон и уведомлений */
|
||||
@keyframes modal-enter {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: scale(0.95) translateY(-10px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: scale(1) translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes toast-enter {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateX(100%);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
}
|
||||
}
|
||||
|
||||
.animate-modal-enter {
|
||||
animation: modal-enter 0.2s ease-out;
|
||||
}
|
||||
|
||||
.animate-toast-enter {
|
||||
animation: toast-enter 0.3s ease-out;
|
||||
}
|
||||
120
ospabhost/frontend/src/pages/404.tsx
Normal file
120
ospabhost/frontend/src/pages/404.tsx
Normal file
@@ -0,0 +1,120 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
233
ospabhost/frontend/src/pages/500.tsx
Normal file
233
ospabhost/frontend/src/pages/500.tsx
Normal file
@@ -0,0 +1,233 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
410
ospabhost/frontend/src/pages/dashboard/admin.tsx
Normal file
410
ospabhost/frontend/src/pages/dashboard/admin.tsx
Normal file
@@ -0,0 +1,410 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import axios from 'axios';
|
||||
import { API_URL } from '../../config/api';
|
||||
import { useToast } from '../../components/Toast';
|
||||
import { showConfirm, showPrompt } from '../../components/modalHelpers';
|
||||
|
||||
interface User {
|
||||
id: number;
|
||||
username: string;
|
||||
email: string;
|
||||
balance: number;
|
||||
isAdmin: boolean;
|
||||
operator: number;
|
||||
createdAt: string;
|
||||
_count: {
|
||||
servers: number;
|
||||
tickets: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface Statistics {
|
||||
users: { total: number };
|
||||
servers: { total: number; active: number; suspended: number };
|
||||
balance: { total: number };
|
||||
checks: { pending: number };
|
||||
tickets: { open: number };
|
||||
recentTransactions: any[];
|
||||
}
|
||||
|
||||
const AdminPanel = () => {
|
||||
const { addToast } = useToast();
|
||||
const [users, setUsers] = useState<User[]>([]);
|
||||
const [statistics, setStatistics] = useState<Statistics | null>(null);
|
||||
const [selectedUser, setSelectedUser] = useState<any>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [activeTab, setActiveTab] = useState<'users' | 'stats'>('stats');
|
||||
|
||||
// Модальные окна
|
||||
const [showBalanceModal, setShowBalanceModal] = useState(false);
|
||||
const [balanceAction, setBalanceAction] = useState<'add' | 'withdraw'>('add');
|
||||
const [balanceAmount, setBalanceAmount] = useState('');
|
||||
const [balanceDescription, setBalanceDescription] = useState('');
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
|
||||
const [usersRes, statsRes] = await Promise.all([
|
||||
axios.get(`${API_URL}/api/admin/users`, { headers }),
|
||||
axios.get(`${API_URL}/api/admin/statistics`, { headers })
|
||||
]);
|
||||
|
||||
setUsers(usersRes.data.data);
|
||||
setStatistics(statsRes.data.data);
|
||||
} catch (error: any) {
|
||||
console.error('Ошибка загрузки данных админки:', error);
|
||||
if (error.response?.status === 403) {
|
||||
addToast('У вас нет прав администратора', 'error');
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [addToast]);
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
|
||||
const loadUserDetails = async (userId: number) => {
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
const res = await axios.get(`${API_URL}/api/admin/users/${userId}`, { headers });
|
||||
setSelectedUser(res.data.data);
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки пользователя:', error);
|
||||
addToast('Ошибка загрузки данных пользователя', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const handleBalanceChange = async () => {
|
||||
if (!selectedUser || !balanceAmount) return;
|
||||
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
const url = `${API_URL}/api/admin/users/${selectedUser.id}/balance/${balanceAction}`;
|
||||
|
||||
await axios.post(url, {
|
||||
amount: parseFloat(balanceAmount),
|
||||
description: balanceDescription
|
||||
}, { headers });
|
||||
|
||||
addToast(`Баланс успешно ${balanceAction === 'add' ? 'пополнен' : 'списан'}`, 'success');
|
||||
setShowBalanceModal(false);
|
||||
setBalanceAmount('');
|
||||
setBalanceDescription('');
|
||||
loadUserDetails(selectedUser.id);
|
||||
loadData();
|
||||
} catch (error) {
|
||||
console.error('Ошибка изменения баланса:', error);
|
||||
addToast('Ошибка изменения баланса', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteServer = async (serverId: number) => {
|
||||
const confirmed = await showConfirm('Вы уверены, что хотите удалить этот сервер?', 'Удаление сервера');
|
||||
if (!confirmed) return;
|
||||
|
||||
const reason = await showPrompt('Укажите причину удаления (необязательно):', 'Причина удаления');
|
||||
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
|
||||
await axios.delete(`${API_URL}/api/admin/servers/${serverId}`, {
|
||||
headers,
|
||||
data: { reason }
|
||||
});
|
||||
|
||||
addToast('Сервер успешно удалён', 'success');
|
||||
if (selectedUser) {
|
||||
loadUserDetails(selectedUser.id);
|
||||
}
|
||||
loadData();
|
||||
} catch (error) {
|
||||
console.error('Ошибка удаления сервера:', error);
|
||||
addToast('Ошибка удаления сервера', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const toggleAdmin = async (userId: number, currentStatus: boolean) => {
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
|
||||
await axios.patch(`${API_URL}/api/admin/users/${userId}/role`, {
|
||||
isAdmin: !currentStatus
|
||||
}, { headers });
|
||||
|
||||
addToast('Права обновлены', 'success');
|
||||
loadData();
|
||||
} catch (error) {
|
||||
console.error('Ошибка обновления прав:', error);
|
||||
addToast('Ошибка обновления прав', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
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-3xl font-bold mb-8">Админ-панель</h1>
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="flex gap-4 mb-6 border-b">
|
||||
<button
|
||||
className={`px-4 py-2 ${activeTab === 'stats' ? 'border-b-2 border-blue-500 font-bold' : ''}`}
|
||||
onClick={() => setActiveTab('stats')}
|
||||
>
|
||||
Статистика
|
||||
</button>
|
||||
<button
|
||||
className={`px-4 py-2 ${activeTab === 'users' ? 'border-b-2 border-blue-500 font-bold' : ''}`}
|
||||
onClick={() => setActiveTab('users')}
|
||||
>
|
||||
Пользователи
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Statistics Tab */}
|
||||
{activeTab === 'stats' && statistics && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
|
||||
<div className="bg-white p-6 rounded-lg shadow">
|
||||
<h3 className="text-gray-500 text-sm">Всего пользователей</h3>
|
||||
<p className="text-3xl font-bold">{statistics.users.total}</p>
|
||||
</div>
|
||||
<div className="bg-white p-6 rounded-lg shadow">
|
||||
<h3 className="text-gray-500 text-sm">Серверы</h3>
|
||||
<p className="text-3xl font-bold">{statistics.servers.total}</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
Активных: {statistics.servers.active} | Приостановлено: {statistics.servers.suspended}
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-white p-6 rounded-lg shadow">
|
||||
<h3 className="text-gray-500 text-sm">Общий баланс</h3>
|
||||
<p className="text-3xl font-bold">{statistics.balance.total.toFixed(2)} ₽</p>
|
||||
</div>
|
||||
<div className="bg-white p-6 rounded-lg shadow">
|
||||
<h3 className="text-gray-500 text-sm">Ожидающие чеки</h3>
|
||||
<p className="text-3xl font-bold">{statistics.checks.pending}</p>
|
||||
</div>
|
||||
<div className="bg-white p-6 rounded-lg shadow">
|
||||
<h3 className="text-gray-500 text-sm">Открытые тикеты</h3>
|
||||
<p className="text-3xl font-bold">{statistics.tickets.open}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Users Tab */}
|
||||
{activeTab === 'users' && (
|
||||
<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">ID</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">Email</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">
|
||||
{users.map((user) => (
|
||||
<tr key={user.id} className="hover:bg-gray-50">
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm">{user.id}</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm">{user.username}</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm">{user.email}</td>
|
||||
<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 ? '✅' : '❌'}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm space-x-2">
|
||||
<button
|
||||
onClick={() => { loadUserDetails(user.id); }}
|
||||
className="text-blue-600 hover:text-blue-800"
|
||||
>
|
||||
Детали
|
||||
</button>
|
||||
<button
|
||||
onClick={() => toggleAdmin(user.id, user.isAdmin)}
|
||||
className="text-purple-600 hover:text-purple-800"
|
||||
>
|
||||
{user.isAdmin ? 'Убрать админа' : 'Сделать админом'}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* User Details Modal */}
|
||||
{selectedUser && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 overflow-y-auto">
|
||||
<div className="bg-white rounded-lg p-8 max-w-4xl w-full mx-4 my-8 max-h-[90vh] overflow-y-auto">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h2 className="text-2xl font-bold">
|
||||
{selectedUser.username} (ID: {selectedUser.id})
|
||||
</h2>
|
||||
<button
|
||||
onClick={() => setSelectedUser(null)}
|
||||
className="text-gray-500 hover:text-gray-700 text-2xl"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4 mb-6">
|
||||
<div>
|
||||
<p className="text-gray-600">Email:</p>
|
||||
<p className="font-medium">{selectedUser.email}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-gray-600">Баланс:</p>
|
||||
<p className="font-medium text-2xl">{selectedUser.balance.toFixed(2)} ₽</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-4 mb-6">
|
||||
<button
|
||||
onClick={() => { setBalanceAction('add'); setShowBalanceModal(true); }}
|
||||
className="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600"
|
||||
>
|
||||
Пополнить баланс
|
||||
</button>
|
||||
<button
|
||||
onClick={() => { setBalanceAction('withdraw'); setShowBalanceModal(true); }}
|
||||
className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600"
|
||||
>
|
||||
Списать с баланса
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 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) => (
|
||||
<div key={server.id} className="border p-4 rounded">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<p className="font-medium">Сервер #{server.id}</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
{server.tariff.name} | {server.os.name} | {server.status}
|
||||
</p>
|
||||
<p className="text-sm text-gray-600">IP: {server.ipAddress || 'N/A'}</p>
|
||||
{server.nextPaymentDate && (
|
||||
<p className="text-sm text-gray-600">
|
||||
След. платёж: {new Date(server.nextPaymentDate).toLocaleDateString('ru-RU')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={() => handleDeleteServer(server.id)}
|
||||
className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600"
|
||||
>
|
||||
Удалить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Transactions */}
|
||||
<h3 className="text-xl font-bold mb-4">Последние транзакции</h3>
|
||||
<div className="space-y-2">
|
||||
{selectedUser.transactions?.slice(0, 10).map((tx: any) => (
|
||||
<div key={tx.id} className="flex justify-between border-b pb-2">
|
||||
<div>
|
||||
<p className="font-medium">{tx.description}</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
{new Date(tx.createdAt).toLocaleString('ru-RU')}
|
||||
</p>
|
||||
</div>
|
||||
<p className={`font-bold ${tx.amount > 0 ? 'text-green-600' : 'text-red-600'}`}>
|
||||
{tx.amount > 0 ? '+' : ''}{tx.amount.toFixed(2)} ₽
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Balance Change Modal */}
|
||||
{showBalanceModal && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
|
||||
<div className="bg-white rounded-lg p-8 max-w-md w-full mx-4">
|
||||
<h2 className="text-2xl font-bold mb-4">
|
||||
{balanceAction === 'add' ? 'Пополнить баланс' : 'Списать с баланса'}
|
||||
</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-2">Сумма (₽)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={balanceAmount}
|
||||
onChange={(e) => setBalanceAmount(e.target.value)}
|
||||
className="w-full px-4 py-2 border rounded"
|
||||
placeholder="0.00"
|
||||
min="0"
|
||||
step="0.01"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-2">Описание</label>
|
||||
<textarea
|
||||
value={balanceDescription}
|
||||
onChange={(e) => setBalanceDescription(e.target.value)}
|
||||
className="w-full px-4 py-2 border rounded"
|
||||
placeholder="Причина пополнения/списания"
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-4 mt-6">
|
||||
<button
|
||||
onClick={handleBalanceChange}
|
||||
className={`px-4 py-2 text-white rounded flex-1 ${
|
||||
balanceAction === 'add'
|
||||
? 'bg-green-500 hover:bg-green-600'
|
||||
: 'bg-red-500 hover:bg-red-600'
|
||||
}`}
|
||||
>
|
||||
Подтвердить
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
setShowBalanceModal(false);
|
||||
setBalanceAmount('');
|
||||
setBalanceDescription('');
|
||||
}}
|
||||
className="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600"
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AdminPanel;
|
||||
@@ -54,12 +54,12 @@ const Billing = () => {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-8 bg-white rounded-3xl shadow-xl max-w-2xl mx-auto">
|
||||
<h2 className="text-3xl font-bold text-gray-800 mb-6">Пополнение баланса</h2>
|
||||
<div className="p-4 lg:p-8 bg-white rounded-2xl lg:rounded-3xl shadow-xl max-w-2xl mx-auto">
|
||||
<h2 className="text-2xl lg:text-3xl font-bold text-gray-800 mb-4 lg:mb-6">Пополнение баланса</h2>
|
||||
{/* Только QR-код и карта, без реквизитов */}
|
||||
{!isPaymentGenerated ? (
|
||||
<div>
|
||||
<p className="text-lg text-gray-500 mb-4">
|
||||
<p className="text-base lg:text-lg text-gray-500 mb-4">
|
||||
Пополните свой баланс, чтобы оплачивать услуги. Минимальная сумма пополнения: 1 руб.
|
||||
</p>
|
||||
<div className="mb-4">
|
||||
@@ -83,7 +83,7 @@ const Billing = () => {
|
||||
) : (
|
||||
<div className="text-center">
|
||||
<div>
|
||||
<p className="text-lg text-gray-700 mb-4">
|
||||
<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">
|
||||
@@ -91,43 +91,43 @@ const Billing = () => {
|
||||
</p>
|
||||
</div>
|
||||
{/* QR-код для оплаты по СБП */}
|
||||
<div className="bg-gray-100 p-6 rounded-2xl inline-block mb-6">
|
||||
<h3 className="text-xl font-bold text-gray-800 mb-2">Оплата по СБП</h3>
|
||||
<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={256} />
|
||||
<QRCode value={sbpUrl || 'https://qr.nspk.ru/FAKE-QR-LINK'} size={Math.min(window.innerWidth - 100, 256)} />
|
||||
</div>
|
||||
<p className="mt-4 text-sm text-gray-600">
|
||||
<p className="mt-4 text-xs lg:text-sm text-gray-600">
|
||||
Отсканируйте QR-код через мобильное приложение вашего банка.
|
||||
</p>
|
||||
</div>
|
||||
{/* Номер карты с кнопкой копирования */}
|
||||
<div className="bg-gray-100 p-6 rounded-2xl mb-6">
|
||||
<h3 className="text-xl font-bold text-gray-800 mb-2">Оплата по номеру карты</h3>
|
||||
<p className="text-2xl font-bold text-gray-800 select-all">{cardNumber || '0000 0000 0000 0000'}</p>
|
||||
<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"
|
||||
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>
|
||||
{/* Форма загрузки чека и инструкции */}
|
||||
<div className="bg-blue-50 p-6 rounded-2xl border-l-4 border-blue-500 text-left mb-6">
|
||||
<p className="font-bold text-blue-800">Загрузите чек для проверки:</p>
|
||||
<input type="file" accept="image/*,application/pdf" onChange={e => setCheckFile(e.target.files?.[0] || null)} className="mt-2" />
|
||||
<button onClick={handleCheckUpload} disabled={!checkFile || uploadLoading} className="mt-2 bg-blue-500 text-white px-4 py-2 rounded">
|
||||
<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">{checkStatus}</div>}
|
||||
{checkStatus && <div className="mt-2 text-green-600 text-sm">{checkStatus}</div>}
|
||||
</div>
|
||||
<div className="bg-red-50 p-6 rounded-2xl border-l-4 border-red-500 text-left mb-6">
|
||||
<p className="font-bold text-red-800">Важно:</p>
|
||||
<p className="text-sm text-red-700">
|
||||
<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">
|
||||
<p className="mt-4 text-gray-600 text-sm lg:text-base">
|
||||
После подтверждения ваш баланс будет пополнен. Ожидайте проверки чека оператором.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -36,8 +36,8 @@ const Checkout: React.FC<CheckoutProps> = ({ onSuccess }) => {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
const [tariffRes, osRes] = await Promise.all([
|
||||
axios.get('https://ospab.host:5000/api/tariff', { headers }),
|
||||
axios.get('https://ospab.host:5000/api/os', { headers }),
|
||||
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);
|
||||
@@ -64,7 +64,7 @@ const Checkout: React.FC<CheckoutProps> = ({ onSuccess }) => {
|
||||
try {
|
||||
const token = localStorage.getItem('access_token') || localStorage.getItem('token');
|
||||
console.log('Покупка сервера:', { tariffId: selectedTariff, osId: selectedOs });
|
||||
const res = await axios.post('https://ospab.host:5000/api/server/create', {
|
||||
const res = await axios.post(`${process.env.VITE_API_URL || 'https://ospab.host:5000'}/api/server/create`, {
|
||||
tariffId: selectedTariff,
|
||||
osId: selectedOs,
|
||||
}, {
|
||||
@@ -78,7 +78,7 @@ const Checkout: React.FC<CheckoutProps> = ({ onSuccess }) => {
|
||||
}
|
||||
// После успешной покупки обновляем userData
|
||||
try {
|
||||
const userRes = await axios.get('https://ospab.host:5000/api/auth/me', { headers: token ? { Authorization: `Bearer ${token}` } : {} });
|
||||
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,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import axios from 'axios';
|
||||
import { API_URL } from '../../config/api';
|
||||
|
||||
interface IUser {
|
||||
id: number;
|
||||
@@ -18,8 +19,6 @@ interface ICheck {
|
||||
user?: IUser;
|
||||
}
|
||||
|
||||
const API_URL = 'https://ospab.host:5000/api/check';
|
||||
|
||||
const CheckVerification: React.FC = () => {
|
||||
const [checks, setChecks] = useState<ICheck[]>([]);
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
@@ -32,7 +31,7 @@ const CheckVerification: React.FC = () => {
|
||||
setError('');
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const res = await axios.get<ICheck[]>(API_URL, {
|
||||
const res = await axios.get<ICheck[]>(`${API_URL}/api/check`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
withCredentials: true,
|
||||
});
|
||||
@@ -51,7 +50,7 @@ const CheckVerification: React.FC = () => {
|
||||
setError('');
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
await axios.post(`${API_URL}/${action}`, { checkId }, {
|
||||
await axios.post(`${API_URL}/api/check/${action}`, { checkId }, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
withCredentials: true,
|
||||
});
|
||||
@@ -61,7 +60,7 @@ const CheckVerification: React.FC = () => {
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
const userRes = await axios.get('https://ospab.host:5000/api/auth/me', { headers });
|
||||
const userRes = await axios.get(`${API_URL}/api/auth/me`, { headers });
|
||||
// Глобально обновить userData через типизированное событие (для Dashboard)
|
||||
window.dispatchEvent(new CustomEvent<import('./types').UserData>('userDataUpdate', {
|
||||
detail: {
|
||||
@@ -109,8 +108,8 @@ const CheckVerification: React.FC = () => {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col items-center gap-2 md:ml-8">
|
||||
<a href={`https://ospab.host:5000${check.fileUrl}`} target="_blank" rel="noopener noreferrer" className="block mb-2">
|
||||
<img src={`https://ospab.host:5000${check.fileUrl}`} alt="Чек" className="w-32 h-32 object-contain rounded-xl border" />
|
||||
<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>
|
||||
{check.status === 'pending' && (
|
||||
<>
|
||||
|
||||
@@ -17,26 +17,24 @@ import CheckVerification from './checkverification';
|
||||
import TicketResponse from './ticketresponse';
|
||||
import Checkout from './checkout';
|
||||
import TariffsPage from '../tariffs';
|
||||
import AdminPanel from './admin';
|
||||
|
||||
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);
|
||||
|
||||
// Определяем активную вкладку из URL
|
||||
const getActiveTab = () => {
|
||||
const path = location.pathname.split('/dashboard/')[1] || '';
|
||||
return path === '' ? 'summary' : path;
|
||||
};
|
||||
|
||||
const [activeTab, setActiveTab] = useState(getActiveTab());
|
||||
const [activeTab, setActiveTab] = useState('summary');
|
||||
|
||||
// Обновляем активную вкладку при изменении URL
|
||||
useEffect(() => {
|
||||
setActiveTab(getActiveTab());
|
||||
}, [location]);
|
||||
const path = location.pathname.split('/dashboard/')[1] || '';
|
||||
const tab = path === '' ? 'summary' : path.split('/')[0];
|
||||
setActiveTab(tab);
|
||||
}, [location.pathname]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
@@ -102,6 +100,7 @@ const Dashboard = () => {
|
||||
}, []);
|
||||
|
||||
const isOperator = userData?.user?.operator === 1;
|
||||
const isAdmin = userData?.user?.isAdmin === true;
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
@@ -124,30 +123,61 @@ const Dashboard = () => {
|
||||
{ key: 'checkverification', label: 'Проверка чеков', to: '/dashboard/checkverification' },
|
||||
{ key: 'ticketresponse', label: 'Ответы на тикеты', to: '/dashboard/ticketresponse' },
|
||||
];
|
||||
|
||||
const superAdminTabs = [
|
||||
{ key: 'admin', label: '👑 Админ-панель', to: '/dashboard/admin' },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen bg-gray-50">
|
||||
{/* Sidebar */}
|
||||
<div className="w-64 bg-white shadow-xl flex flex-col">
|
||||
{/* Mobile Menu Button */}
|
||||
<button
|
||||
onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
|
||||
className="lg:hidden fixed top-4 left-4 z-50 p-2 bg-white rounded-lg shadow-lg"
|
||||
>
|
||||
<svg className="w-6 h-6 text-gray-800" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
{isMobileMenuOpen ? (
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
) : (
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
|
||||
)}
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{/* Sidebar - теперь адаптивный */}
|
||||
<div className={`
|
||||
fixed lg:static inset-y-0 left-0 z-40
|
||||
w-64 bg-white shadow-xl flex flex-col
|
||||
transform transition-transform duration-300 ease-in-out
|
||||
${isMobileMenuOpen ? 'translate-x-0' : '-translate-x-full lg:translate-x-0'}
|
||||
`}>
|
||||
<div className="p-6 border-b border-gray-200">
|
||||
<h2 className="text-xl font-bold text-gray-800">
|
||||
<h2 className="text-xl font-bold text-gray-800 break-words">
|
||||
Привет, {userData?.user?.username || 'Гость'}!
|
||||
</h2>
|
||||
{isOperator && (
|
||||
<span className="inline-block px-2 py-1 bg-red-100 text-red-800 text-xs font-semibold rounded-full mt-1">
|
||||
Оператор
|
||||
</span>
|
||||
)}
|
||||
<div className="flex gap-2 mt-2">
|
||||
{isOperator && (
|
||||
<span className="inline-block px-2 py-1 bg-blue-100 text-blue-800 text-xs font-semibold rounded-full">
|
||||
Оператор
|
||||
</span>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<span className="inline-block px-2 py-1 bg-red-100 text-red-800 text-xs font-semibold rounded-full">
|
||||
👑 Супер Админ
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-2 text-sm text-gray-600">
|
||||
Баланс: <span className="font-semibold text-ospab-primary">₽{userData?.balance ?? 0}</span>
|
||||
</div>
|
||||
</div>
|
||||
<nav className="flex-1 p-6">
|
||||
<nav className="flex-1 p-6 overflow-y-auto">
|
||||
<div className="space-y-1">
|
||||
{tabs.map(tab => (
|
||||
<Link
|
||||
key={tab.key}
|
||||
to={tab.to}
|
||||
onClick={() => setIsMobileMenuOpen(false)}
|
||||
className={`flex items-center py-3 px-4 rounded-xl font-semibold transition-colors duration-200 ${
|
||||
activeTab === tab.key ? 'bg-ospab-primary text-white shadow-lg' : 'text-gray-600 hover:bg-gray-100'
|
||||
}`}
|
||||
@@ -166,6 +196,7 @@ const Dashboard = () => {
|
||||
<Link
|
||||
key={tab.key}
|
||||
to={tab.to}
|
||||
onClick={() => setIsMobileMenuOpen(false)}
|
||||
className={`flex items-center py-3 px-4 rounded-xl font-semibold transition-colors duration-200 ${
|
||||
activeTab === tab.key ? 'bg-ospab-primary text-white shadow-lg' : 'text-gray-600 hover:bg-gray-100'
|
||||
}`}
|
||||
@@ -176,6 +207,27 @@ const Dashboard = () => {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<div className="mt-8 pt-6 border-t border-gray-200">
|
||||
<p className="text-xs font-semibold text-red-500 uppercase tracking-wider mb-3 px-4">
|
||||
Супер Админ
|
||||
</p>
|
||||
<div className="space-y-1">
|
||||
{superAdminTabs.map(tab => (
|
||||
<Link
|
||||
key={tab.key}
|
||||
to={tab.to}
|
||||
onClick={() => setIsMobileMenuOpen(false)}
|
||||
className={`flex items-center py-3 px-4 rounded-xl font-semibold transition-colors duration-200 ${
|
||||
activeTab === tab.key ? 'bg-red-600 text-white shadow-lg' : 'text-red-600 hover:bg-red-50'
|
||||
}`}
|
||||
>
|
||||
{tab.label}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</nav>
|
||||
<div className="p-6 border-t border-gray-200 text-xs text-gray-500 text-center">
|
||||
<p>© 2025 ospab.host</p>
|
||||
@@ -183,13 +235,21 @@ const Dashboard = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Overlay для мобильного меню */}
|
||||
{isMobileMenuOpen && (
|
||||
<div
|
||||
className="fixed inset-0 bg-black bg-opacity-50 z-30 lg:hidden"
|
||||
onClick={() => setIsMobileMenuOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Main Content */}
|
||||
<div className="flex-1 flex flex-col">
|
||||
<div className="bg-white border-b border-gray-200 px-8 py-4">
|
||||
<h1 className="text-2xl font-bold text-gray-900 capitalize">
|
||||
<div className="flex-1 flex flex-col w-full lg:w-auto">
|
||||
<div className="bg-white border-b border-gray-200 px-4 lg:px-8 py-4 pt-16 lg:pt-4">
|
||||
<h1 className="text-xl lg:text-2xl font-bold text-gray-900 capitalize break-words">
|
||||
{tabs.concat(adminTabs).find(t => t.key === activeTab)?.label || 'Панель управления'}
|
||||
</h1>
|
||||
<p className="text-sm text-gray-600 mt-1">
|
||||
<p className="text-xs lg:text-sm text-gray-600 mt-1">
|
||||
{new Date().toLocaleDateString('ru-RU', {
|
||||
weekday: 'long',
|
||||
year: 'numeric',
|
||||
@@ -198,17 +258,12 @@ const Dashboard = () => {
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex-1 p-8 pt-12">
|
||||
{activeTab === 'summary' && (
|
||||
<div className="border-4 border-red-500 bg-red-100 text-red-900 font-bold text-lg rounded-2xl shadow-lg p-6 mb-8 text-center animate-pulse">
|
||||
⚠️ Управление серверами временно невозможно — сайт ещё в разработке!
|
||||
</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/servers')} />} />
|
||||
<Route path="checkout" element={<Checkout onSuccess={() => navigate('/dashboard')} />} />
|
||||
<Route path="tariffs" element={<TariffsPage />} />
|
||||
{userData && (
|
||||
<Route path="tickets" element={<TicketsPage setUserData={setUserData} />} />
|
||||
@@ -224,6 +279,9 @@ const Dashboard = () => {
|
||||
<Route path="ticketresponse" element={<TicketResponse />} />
|
||||
</>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<Route path="admin" element={<AdminPanel />} />
|
||||
)}
|
||||
</Routes>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,344 +1,376 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
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 React, { useEffect, useState } from 'react';
|
||||
import ServerConsole from '../../components/ServerConsole';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import axios, { AxiosError } from 'axios';
|
||||
|
||||
// Типы
|
||||
interface Server {
|
||||
interface ServerData {
|
||||
id: number;
|
||||
status: string;
|
||||
ipAddress: string | null;
|
||||
rootPassword: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
os: { name: string; type: string };
|
||||
tariff: { name: string; price: number };
|
||||
ip?: string;
|
||||
rootPassword?: string;
|
||||
}
|
||||
|
||||
interface ServerStats {
|
||||
data?: {
|
||||
cpu?: number;
|
||||
memory?: { usage?: number };
|
||||
tariff: {
|
||||
name: string;
|
||||
price: number;
|
||||
description: string;
|
||||
};
|
||||
os: {
|
||||
name: string;
|
||||
type: string;
|
||||
};
|
||||
nextPaymentDate: string | null;
|
||||
autoRenew: boolean;
|
||||
stats?: {
|
||||
data?: {
|
||||
cpu: number;
|
||||
memory: {
|
||||
usage: number;
|
||||
};
|
||||
disk: {
|
||||
usage: number;
|
||||
};
|
||||
status: string;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
// ...existing code...
|
||||
|
||||
// ConsoleSection больше не нужен
|
||||
|
||||
const TABS = [
|
||||
{ key: 'overview', label: 'Обзор' },
|
||||
{ key: 'console', label: 'Консоль' },
|
||||
{ key: 'stats', label: 'Статистика' },
|
||||
{ key: 'manage', label: 'Управление' },
|
||||
{ key: 'security', label: 'Безопасность' },
|
||||
{ key: 'network', label: 'Сеть' },
|
||||
{ key: 'backups', label: 'Бэкапы' },
|
||||
{ key: 'monitoring', label: 'Мониторинг' },
|
||||
{ key: 'logs', label: 'Логи' },
|
||||
];
|
||||
|
||||
const ServerPanel: React.FC = () => {
|
||||
const { id } = useParams();
|
||||
const [server, setServer] = useState<Server | null>(null);
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const { addToast } = useToast();
|
||||
const [server, setServer] = useState<ServerData | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [success, setSuccess] = useState('');
|
||||
const [activeAction, setActiveAction] = useState<null | 'start' | 'stop' | 'restart'>(null);
|
||||
const [activeTab, setActiveTab] = useState('overview');
|
||||
const [newRoot, setNewRoot] = useState<string | null>(null);
|
||||
const [showRoot, setShowRoot] = useState(false);
|
||||
// overlay больше не нужен
|
||||
const [stats, setStats] = useState<ServerStats | null>(null);
|
||||
const [actionLoading, setActionLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
|
||||
// Модальные окна
|
||||
const [showPasswordConfirm, setShowPasswordConfirm] = useState(false);
|
||||
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchServer = async () => {
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
const res = await axios.get(`https://ospab.host:5000/api/server/${id}`, { headers });
|
||||
setServer(res.data);
|
||||
// Получаем статистику
|
||||
const statsRes = await axios.get(`https://ospab.host:5000/api/server/${id}/status`, { headers });
|
||||
setStats(statsRes.data.stats);
|
||||
} catch (err) {
|
||||
const error = err as AxiosError;
|
||||
if (error?.response?.status === 404) {
|
||||
setError('Сервер не найден или был удалён.');
|
||||
} else {
|
||||
setError('Ошибка загрузки данных сервера');
|
||||
}
|
||||
console.error('Ошибка загрузки данных сервера:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
fetchServer();
|
||||
}, [id]);
|
||||
|
||||
// Смена root-пароля через backend
|
||||
const handleGenerateRoot = async () => {
|
||||
const loadServer = React.useCallback(async () => {
|
||||
try {
|
||||
setError('');
|
||||
setSuccess('');
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
const res = await axios.post(`https://ospab.host:5000/api/server/${id}/password`, {}, { headers });
|
||||
if (res.data?.status === 'success' && res.data.password) {
|
||||
setNewRoot(res.data.password);
|
||||
setShowRoot(true);
|
||||
setSuccess('Root-пароль успешно изменён!');
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
|
||||
const response = await axios.get(`${API_URL}/api/server/${id}/status`, { headers });
|
||||
setServer(response.data);
|
||||
setError(null);
|
||||
} catch (err: unknown) {
|
||||
console.error('Ошибка загрузки сервера:', err);
|
||||
if (axios.isAxiosError(err) && err.response?.status === 404) {
|
||||
setError('Сервер не найден');
|
||||
} else {
|
||||
setError('Ошибка смены root-пароля');
|
||||
console.error('Ошибка смены root-пароля:', res.data);
|
||||
setError('Не удалось загрузить данные сервера');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Ошибка смены root-пароля');
|
||||
console.error('Ошибка смены root-пароля:', err);
|
||||
const axiosErr = err as AxiosError;
|
||||
if (axiosErr && axiosErr.response) {
|
||||
console.error('Ответ сервера:', axiosErr.response.data);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Реальные действия управления сервером
|
||||
const handleAction = async (action: 'start' | 'stop' | 'restart') => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setActiveAction(action);
|
||||
setError('');
|
||||
setSuccess('');
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
const res = await axios.post(`https://ospab.host:5000/api/server/${id}/${action}`, {}, { headers });
|
||||
if (res.data?.status === 'success' || res.data?.message === 'Статус сервера изменён успешно') {
|
||||
// Обновить статус сервера и статистику после действия
|
||||
const updated = await axios.get(`https://ospab.host:5000/api/server/${id}`, { headers });
|
||||
setServer(updated.data);
|
||||
const statsRes = await axios.get(`https://ospab.host:5000/api/server/${id}/status`, { headers });
|
||||
setStats(statsRes.data.stats);
|
||||
setSuccess('Действие выполнено успешно!');
|
||||
} else {
|
||||
setError(`Ошибка: ${res.data?.message || 'Не удалось выполнить действие'}`);
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Ошибка управления сервером');
|
||||
console.error('Ошибка управления сервером:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setActiveAction(null);
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => {
|
||||
loadServer();
|
||||
const interval = setInterval(loadServer, 10000); // Обновляем каждые 10 секунд
|
||||
return () => clearInterval(interval);
|
||||
}, [loadServer]);
|
||||
|
||||
const handleAction = async (action: 'start' | 'stop' | 'restart') => {
|
||||
try {
|
||||
setActionLoading(true);
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
|
||||
await axios.post(`${API_URL}/api/server/${id}/${action}`, {}, { headers });
|
||||
|
||||
setTimeout(loadServer, 2000); // Обновляем через 2 секунды
|
||||
addToast(`Команда "${action}" отправлена успешно`, 'success');
|
||||
} catch (err) {
|
||||
console.error(`Ошибка выполнения ${action}:`, err);
|
||||
addToast(`Не удалось выполнить команду "${action}"`, 'error');
|
||||
} finally {
|
||||
setActionLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePasswordChange = async () => {
|
||||
setShowPasswordConfirm(false);
|
||||
|
||||
try {
|
||||
setActionLoading(true);
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
|
||||
const response = await axios.post(`${API_URL}/api/server/${id}/password`, {}, { headers });
|
||||
|
||||
if (response.data.status === 'success') {
|
||||
addToast('Пароль успешно изменён! Новый пароль отображается ниже.', 'success');
|
||||
loadServer();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Ошибка смены пароля:', err);
|
||||
addToast('Не удалось сменить пароль', 'error');
|
||||
} finally {
|
||||
setActionLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
setShowDeleteConfirm(false);
|
||||
|
||||
try {
|
||||
setActionLoading(true);
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
|
||||
await axios.delete(`${API_URL}/api/server/${id}`, { headers });
|
||||
|
||||
addToast('Сервер успешно удалён', 'success');
|
||||
navigate('/dashboard/servers');
|
||||
} catch (err) {
|
||||
console.error('Ошибка удаления сервера:', err);
|
||||
addToast('Не удалось удалить сервер', 'error');
|
||||
} finally {
|
||||
setActionLoading(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>
|
||||
);
|
||||
}
|
||||
|
||||
if (error || !server) {
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
|
||||
<p className="text-red-800 text-xl">{error || 'Сервер не найден'}</p>
|
||||
<button
|
||||
onClick={() => navigate('/dashboard/servers')}
|
||||
className="mt-4 px-4 py-2 bg-gray-800 text-white rounded-lg hover:bg-gray-900"
|
||||
>
|
||||
Вернуться к списку серверов
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col items-center bg-gray-50">
|
||||
<div className="bg-white rounded-3xl shadow-xl p-10 w-full max-w-7xl mt-10 flex flex-row min-h-[700px]">
|
||||
<aside className="w-64 pr-8 border-r border-gray-200 flex flex-col gap-2">
|
||||
<h1 className="text-2xl font-bold text-gray-800 mb-6">Сервер #{server?.id}</h1>
|
||||
{TABS.map(tab => (
|
||||
<button
|
||||
key={tab.key}
|
||||
onClick={() => setActiveTab(tab.key)}
|
||||
className={`w-full text-left px-5 py-3 rounded-xl font-semibold transition-colors duration-200 mb-1 ${activeTab === tab.key ? 'bg-ospab-primary text-white shadow-lg' : 'text-gray-600 hover:bg-gray-100'}`}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</aside>
|
||||
<main className="flex-1 pl-8">
|
||||
{activeTab === 'overview' && server && (
|
||||
<div className="bg-gradient-to-br from-ospab-primary/80 to-ospab-primary-dark/80 rounded-2xl shadow-lg p-8 flex flex-col items-start w-full max-w-2xl mx-auto">
|
||||
<div className="grid grid-cols-2 gap-4 w-full mb-6">
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-sm text-gray-700">Статус</span>
|
||||
<span className={`text-base font-semibold px-3 py-1 rounded-xl ${server.status === 'running' ? 'bg-green-100 text-green-800' : server.status === 'stopped' ? 'bg-red-100 text-red-800' : 'bg-yellow-100 text-yellow-800'} shadow w-fit`}>{server.status === 'running' ? 'Работает' : server.status === 'stopped' ? 'Остановлен' : server.status}</span>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-sm text-gray-700">IP-адрес</span>
|
||||
<span className="font-mono text-base text-gray-900">{server.ip || '—'}</span>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-sm text-gray-700">Операционная система</span>
|
||||
<span className="text-gray-900">{server.os.name} <span className="text-xs text-gray-500">({server.os.type})</span></span>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-sm text-gray-700">Тариф</span>
|
||||
<span className="text-base font-semibold px-3 py-1 rounded-xl bg-ospab-primary/10 text-ospab-primary shadow w-fit">{server.tariff.name}</span>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-sm text-gray-700">Цена</span>
|
||||
<span className="font-mono text-base text-gray-900">{server.tariff.price}₽</span>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-sm text-gray-700">Root-пароль</span>
|
||||
{(() => {
|
||||
const created = new Date(server.createdAt);
|
||||
const now = new Date();
|
||||
const diffMin = (now.getTime() - created.getTime()) / 1000 / 60;
|
||||
if (server.rootPassword && diffMin <= 30) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 relative">
|
||||
<span
|
||||
className="font-mono text-base bg-gray-100 text-gray-900 px-3 py-1 rounded"
|
||||
style={{ userSelect: showRoot ? 'text' : 'none', WebkitUserSelect: showRoot ? 'text' : 'none' }}
|
||||
>{showRoot ? server.rootPassword : '************'}</span>
|
||||
{!showRoot ? (
|
||||
<button
|
||||
className="bg-ospab-primary text-white px-2 py-1 rounded text-xs font-bold hover:bg-ospab-primary-dark transition"
|
||||
onClick={() => setShowRoot(true)}
|
||||
>Показать</button>
|
||||
) : (
|
||||
<button
|
||||
className="bg-ospab-primary text-white px-2 py-1 rounded text-xs font-bold hover:bg-ospab-primary-dark transition"
|
||||
onClick={() => { navigator.clipboard.writeText(server.rootPassword || ''); setShowRoot(false); }}
|
||||
>Скопировать</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<span className="font-mono text-base text-gray-900">—</span>
|
||||
);
|
||||
}
|
||||
})()}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col md:flex-row gap-6 w-full mt-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-lg">📅</span>
|
||||
<span className="text-sm text-gray-700">Создан:</span>
|
||||
<span className="font-semibold text-gray-900">{new Date(server.createdAt).toLocaleString()}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-lg">🔄</span>
|
||||
<span className="text-sm text-gray-700">Обновлён:</span>
|
||||
<span className="font-semibold text-gray-900">{new Date(server.updatedAt).toLocaleString()}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'console' && server && (
|
||||
<ServerConsole />
|
||||
)}
|
||||
|
||||
{activeTab === 'stats' && (
|
||||
<div className="bg-gray-100 rounded-xl p-6">
|
||||
<div className="mb-2 font-bold">Графики нагрузки</div>
|
||||
<div className="flex gap-6">
|
||||
<div className="w-1/2 h-32 bg-white rounded-lg shadow-inner flex flex-col items-center justify-center">
|
||||
<div className="font-bold text-gray-700">CPU</div>
|
||||
<div className="text-2xl text-ospab-primary">{stats?.data?.cpu ? (stats.data.cpu * 100).toFixed(1) : '—'}%</div>
|
||||
</div>
|
||||
<div className="w-1/2 h-32 bg-white rounded-lg shadow-inner flex flex-col items-center justify-center">
|
||||
<div className="font-bold text-gray-700">RAM</div>
|
||||
<div className="text-2xl text-ospab-primary">{stats?.data?.memory?.usage ? stats.data.memory.usage.toFixed(1) : '—'}%</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'manage' && server && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex gap-6">
|
||||
<button
|
||||
className={`bg-green-500 hover:bg-green-600 text-white px-6 py-3 rounded-full font-bold flex items-center justify-center ${server.status === 'running' ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
onClick={() => handleAction('start')}
|
||||
disabled={server.status === 'running' || loading}
|
||||
>
|
||||
{loading && activeAction === 'start' ? (
|
||||
<span className="flex items-center gap-2">
|
||||
<svg className="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"></path>
|
||||
</svg>
|
||||
Выполняется...
|
||||
</span>
|
||||
) : 'Запустить'}
|
||||
</button>
|
||||
<button
|
||||
className={`bg-yellow-500 hover:bg-yellow-600 text-white px-6 py-3 rounded-full font-bold flex items-center justify-center ${server.status !== 'running' ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
onClick={() => handleAction('restart')}
|
||||
disabled={server.status !== 'running' || loading}
|
||||
>
|
||||
{loading && activeAction === 'restart' ? (
|
||||
<span className="flex items-center gap-2">
|
||||
<svg className="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"></path>
|
||||
</svg>
|
||||
Выполняется...
|
||||
</span>
|
||||
) : 'Перезагрузить'}
|
||||
</button>
|
||||
<button
|
||||
className={`bg-red-500 hover:bg-red-600 text-white px-6 py-3 rounded-full font-bold flex items-center justify-center ${server.status === 'stopped' ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
onClick={() => handleAction('stop')}
|
||||
disabled={server.status === 'stopped' || loading}
|
||||
>
|
||||
{loading && activeAction === 'stop' ? (
|
||||
<span className="flex items-center gap-2">
|
||||
<svg className="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"></path>
|
||||
</svg>
|
||||
Выполняется...
|
||||
</span>
|
||||
) : 'Остановить'}
|
||||
</button>
|
||||
</div>
|
||||
{success && (
|
||||
<div className="text-green-600 text-base font-semibold mt-2">{success}</div>
|
||||
)}
|
||||
{error && (
|
||||
<div className="text-red-500 text-base font-semibold mt-2">{error}</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'network' && (
|
||||
<div className="bg-gray-100 rounded-xl p-6 text-center text-gray-500">Сеть: здесь будет управление сетевыми настройками</div>
|
||||
)}
|
||||
{activeTab === 'backups' && (
|
||||
<div className="bg-gray-100 rounded-xl p-6 text-center text-gray-500">Бэкапы: здесь будет управление резервными копиями</div>
|
||||
)}
|
||||
{activeTab === 'monitoring' && (
|
||||
<div className="bg-gray-100 rounded-xl p-6 text-center text-gray-500">Мониторинг: здесь будет расширенный мониторинг</div>
|
||||
)}
|
||||
{activeTab === 'logs' && (
|
||||
<div className="bg-gray-100 rounded-xl p-6 text-center text-gray-500">Логи: здесь будут логи сервера</div>
|
||||
)}
|
||||
{activeTab === 'security' && server && (
|
||||
<div className="space-y-4">
|
||||
<button className="bg-ospab-primary text-white px-6 py-3 rounded-full font-bold" onClick={handleGenerateRoot}>Сгенерировать новый root-пароль</button>
|
||||
{showRoot && newRoot && (
|
||||
<div className="bg-gray-100 rounded-xl p-6 flex flex-col items-center">
|
||||
<div className="mb-2 font-bold text-lg">Ваш новый root-пароль:</div>
|
||||
<div
|
||||
className="font-mono text-xl bg-white px-6 py-3 rounded-lg shadow-inner"
|
||||
style={{ userSelect: 'none', WebkitUserSelect: 'none' }}
|
||||
>{newRoot.replace(/./g, '*')}</div>
|
||||
<button
|
||||
className="bg-ospab-primary text-white px-2 py-1 rounded text-xs font-bold hover:bg-ospab-primary-dark transition mt-2"
|
||||
onClick={() => setShowRoot(false)}
|
||||
>Скрыть</button>
|
||||
</div>
|
||||
)}
|
||||
{success && (
|
||||
<div className="text-green-600 text-base font-semibold mt-2">{success}</div>
|
||||
)}
|
||||
{error && (
|
||||
<div className="text-red-500 text-base font-semibold mt-2">{error}</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
{/* Header */}
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-800">Сервер #{server.id}</h1>
|
||||
<p className="text-gray-600 mt-1">{server.tariff.name} - {server.os.name}</p>
|
||||
</div>
|
||||
<span className={`px-4 py-2 rounded-lg font-semibold ${getStatusColor(server.status)}`}>
|
||||
{getStatusText(server.status)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Server Info */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
|
||||
<div className="bg-white rounded-lg shadow p-6">
|
||||
<h2 className="text-xl font-semibold mb-4">Информация</h2>
|
||||
<div className="space-y-3 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-600">IP адрес:</span>
|
||||
<span className="font-medium">{server.ipAddress || 'Создаётся...'}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-600">Root пароль:</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-mono">
|
||||
{showPassword ? server.rootPassword : '••••••••'}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="text-blue-600 hover:text-blue-800"
|
||||
>
|
||||
{showPassword ? '👁️' : '👁️🗨️'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-600">Создан:</span>
|
||||
<span>{new Date(server.createdAt).toLocaleString('ru-RU')}</span>
|
||||
</div>
|
||||
{server.nextPaymentDate && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-600">След. платёж:</span>
|
||||
<span>{new Date(server.nextPaymentDate).toLocaleDateString('ru-RU')}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-600">Автопродление:</span>
|
||||
<span>{server.autoRenew ? '✅ Включено' : '❌ Выключено'}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stats */}
|
||||
<div className="bg-white rounded-lg shadow p-6">
|
||||
<h2 className="text-xl font-semibold mb-4">Статистика</h2>
|
||||
{server.stats?.data ? (
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<div className="flex justify-between text-sm mb-1">
|
||||
<span>CPU</span>
|
||||
<span>{server.stats.data.cpu?.toFixed(1)}%</span>
|
||||
</div>
|
||||
<div className="w-full bg-gray-200 rounded-full h-2">
|
||||
<div
|
||||
className="bg-blue-600 h-2 rounded-full"
|
||||
style={{ width: `${server.stats.data.cpu || 0}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex justify-between text-sm mb-1">
|
||||
<span>RAM</span>
|
||||
<span>{((server.stats.data.memory?.usage || 0) / 1024 / 1024).toFixed(0)} MB</span>
|
||||
</div>
|
||||
<div className="w-full bg-gray-200 rounded-full h-2">
|
||||
<div
|
||||
className="bg-green-600 h-2 rounded-full"
|
||||
style={{ width: `${Math.min(((server.stats.data.memory?.usage || 0) / 1024 / 1024 / 1024) * 100, 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-gray-500">Статистика недоступна</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Control Buttons */}
|
||||
<div className="bg-white rounded-lg shadow p-6 mb-6">
|
||||
<h2 className="text-xl font-semibold mb-4">Управление</h2>
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<button
|
||||
onClick={() => handleAction('start')}
|
||||
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')}
|
||||
disabled={actionLoading}
|
||||
className="px-4 py-3 bg-yellow-600 text-white rounded-lg hover:bg-yellow-700 disabled:opacity-50 disabled:cursor-not-allowed transition"
|
||||
>
|
||||
🔄 Перезагрузить
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setShowPasswordConfirm(true)}
|
||||
disabled={actionLoading}
|
||||
className="px-4 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition"
|
||||
>
|
||||
🔑 Сменить пароль
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* SSH Access */}
|
||||
<div className="bg-white rounded-lg shadow p-6 mb-6">
|
||||
<h2 className="text-xl font-semibold mb-4">SSH Доступ</h2>
|
||||
<div className="bg-gray-900 text-gray-100 p-4 rounded-lg font-mono text-sm">
|
||||
<p>ssh root@{server.ipAddress || 'создаётся...'}</p>
|
||||
<p className="text-gray-400 mt-2">Пароль: {showPassword ? server.rootPassword : '••••••••'}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 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>
|
||||
<p className="text-red-700 mb-4">
|
||||
Удаление сервера - необратимое действие. Все данные будут утеряны!
|
||||
</p>
|
||||
<button
|
||||
onClick={() => setShowDeleteConfirm(true)}
|
||||
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>
|
||||
|
||||
{/* Модальные окна */}
|
||||
<Modal
|
||||
isOpen={showPasswordConfirm}
|
||||
onClose={() => setShowPasswordConfirm(false)}
|
||||
title="Смена root-пароля"
|
||||
type="warning"
|
||||
onConfirm={handlePasswordChange}
|
||||
confirmText="Да, сменить пароль"
|
||||
cancelText="Отмена"
|
||||
>
|
||||
<p>Вы уверены, что хотите сменить root-пароль для этого сервера?</p>
|
||||
<p className="mt-2 text-sm text-gray-500">
|
||||
Новый пароль будет сгенерирован автоматически и отображён на этой странице.
|
||||
</p>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
isOpen={showDeleteConfirm}
|
||||
onClose={() => setShowDeleteConfirm(false)}
|
||||
title="Удаление сервера"
|
||||
type="danger"
|
||||
onConfirm={handleDelete}
|
||||
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 ServerPanel;
|
||||
export default ServerPanel;
|
||||
|
||||
@@ -1,88 +1,172 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import axios from 'axios';
|
||||
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;
|
||||
updatedAt: string;
|
||||
os: { name: string; type: string };
|
||||
tariff: { name: string; price: number };
|
||||
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('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchServers = async () => {
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
const res = await axios.get('https://ospab.host:5000/api/server', { headers });
|
||||
console.log('Ответ API серверов:', res.data);
|
||||
// Защита от получения HTML вместо JSON
|
||||
if (typeof res.data === 'string' && res.data.startsWith('<!doctype html')) {
|
||||
setError('Ошибка соединения с backend: получен HTML вместо JSON. Проверьте адрес и порт.');
|
||||
setServers([]);
|
||||
} else if (Array.isArray(res.data)) {
|
||||
setServers(res.data);
|
||||
} else {
|
||||
setError('Некорректный формат данных серверов');
|
||||
setServers([]);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Ошибка загрузки серверов:', err);
|
||||
setError('Ошибка загрузки серверов');
|
||||
setServers([]);
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
fetchServers();
|
||||
loadServers();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="p-8 bg-white rounded-3xl shadow-xl max-w-4xl mx-auto">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h2 className="text-3xl font-bold text-gray-800">Мои серверы</h2>
|
||||
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>
|
||||
{loading ? (
|
||||
<p className="text-lg text-gray-500">Загрузка...</p>
|
||||
) : error ? (
|
||||
<div className="text-center">
|
||||
<p className="text-lg text-red-500 mb-4">{error}</p>
|
||||
<button className="bg-ospab-primary text-white px-6 py-3 rounded-full font-bold hover:bg-ospab-primary-dark transition" onClick={() => window.location.reload()}>Перезагрузить страницу</button>
|
||||
);
|
||||
}
|
||||
|
||||
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="text-center">
|
||||
<p className="text-lg text-gray-500 mb-4">У вас пока нет активных серверов.</p>
|
||||
<a href="/tariffs" className="inline-block bg-ospab-primary text-white px-6 py-3 rounded-full font-bold hover:bg-ospab-primary-dark transition">Посмотреть тарифы</a>
|
||||
)}
|
||||
|
||||
{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 gap-8">
|
||||
{servers.map(server => (
|
||||
<div key={server.id} className="bg-white p-8 rounded-2xl shadow-xl flex flex-col gap-4">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold text-gray-800 mb-2">{server.tariff.name}</h2>
|
||||
<p className="text-lg text-gray-600">ОС: {server.os.name} ({server.os.type})</p>
|
||||
<p className="text-lg text-gray-600">Статус: <span className="font-bold">{server.status}</span></p>
|
||||
<p className="text-sm text-gray-400">Создан: {new Date(server.createdAt).toLocaleString()}</p>
|
||||
<p className="text-sm text-gray-400">Обновлён: {new Date(server.updatedAt).toLocaleString()}</p>
|
||||
<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>
|
||||
<Link
|
||||
to={`/dashboard/server/${server.id}`}
|
||||
className="bg-ospab-primary text-white px-6 py-3 rounded-full font-bold hover:bg-ospab-primary-dark transition"
|
||||
>
|
||||
Перейти в панель управления
|
||||
</Link>
|
||||
|
||||
<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>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,53 +1,434 @@
|
||||
import { useState } from "react";
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import axios from "axios";
|
||||
import { API_URL } from "../../config/api";
|
||||
import { Modal } from "../../components/Modal";
|
||||
import { useToast } from "../../components/Toast";
|
||||
|
||||
interface AccountInfo {
|
||||
id: number;
|
||||
email: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
const Settings = () => {
|
||||
const [tab, setTab] = useState<'email' | 'password'>('email');
|
||||
const [email, setEmail] = useState("");
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
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);
|
||||
|
||||
// TODO: получить email и username из API
|
||||
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-8 bg-white rounded-3xl shadow-xl max-w-xl mx-auto mt-6">
|
||||
<h2 className="text-2xl font-bold mb-4">Настройки аккаунта</h2>
|
||||
<div className="flex space-x-4 mb-6">
|
||||
<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 ${tab === 'email' ? 'bg-ospab-primary text-white' : 'bg-gray-100 text-gray-700'}`}
|
||||
onClick={() => setTab('email')}
|
||||
>
|
||||
Смена email
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`px-4 py-2 rounded-lg font-semibold ${tab === 'password' ? 'bg-ospab-primary text-white' : 'bg-gray-100 text-gray-700'}`}
|
||||
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 === 'email' ? (
|
||||
<form className="space-y-6">
|
||||
<div>
|
||||
<label className="block text-gray-700 mb-2">Email</label>
|
||||
<input type="email" value={email} onChange={e => setEmail(e.target.value)} className="w-full px-4 py-2 border rounded-lg bg-gray-100" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-gray-700 mb-2">Имя пользователя</label>
|
||||
<input type="text" value={username} onChange={e => setUsername(e.target.value)} className="w-full px-4 py-2 border rounded-lg bg-gray-100" />
|
||||
</div>
|
||||
<button type="button" className="bg-ospab-primary text-white px-6 py-2 rounded-lg font-bold">Сохранить email</button>
|
||||
</form>
|
||||
) : (
|
||||
<form className="space-y-6">
|
||||
<div>
|
||||
<label className="block text-gray-700 mb-2">Новый пароль</label>
|
||||
<input type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="Новый пароль" className="w-full px-4 py-2 border rounded-lg" />
|
||||
</div>
|
||||
<button type="button" className="bg-ospab-primary text-white px-6 py-2 rounded-lg font-bold">Сохранить пароль</button>
|
||||
</form>
|
||||
|
||||
{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>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -16,26 +16,26 @@ const Summary = ({ userData }: SummaryProps) => {
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="p-8 bg-white rounded-3xl shadow-xl">
|
||||
<h2 className="text-3xl font-bold text-gray-800 mb-6">Сводка по аккаунту</h2>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
|
||||
<div className="bg-gray-100 p-6 rounded-2xl flex flex-col items-start">
|
||||
<p className="text-xl font-medium text-gray-700">Баланс:</p>
|
||||
<p className="text-4xl font-extrabold text-ospab-primary mt-2">₽ {userData.balance?.toFixed ? userData.balance.toFixed(2) : Number(userData.balance).toFixed(2)}</p>
|
||||
<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="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-6 rounded-2xl flex flex-col items-start">
|
||||
<p className="text-xl font-medium text-gray-700">Активные серверы:</p>
|
||||
<p className="text-4xl font-extrabold text-gray-800 mt-2">{activeServers.length}</p>
|
||||
<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-6 rounded-2xl flex flex-col items-start">
|
||||
<p className="text-xl font-medium text-gray-700">Открытые тикеты:</p>
|
||||
<p className="text-4xl font-extrabold text-gray-800 mt-2">{openTickets.length}</p>
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-lg text-gray-500">
|
||||
<p className="text-base lg:text-lg text-gray-500">
|
||||
Добро пожаловать в ваш личный кабинет, {userData.user?.username || 'пользователь'}! Здесь вы можете быстро получить доступ к основным разделам.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
export interface User {
|
||||
username: string;
|
||||
operator: number;
|
||||
isAdmin?: boolean;
|
||||
}
|
||||
|
||||
export interface Ticket {
|
||||
|
||||
@@ -1,32 +1,60 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { Link, useNavigate, useLocation } from 'react-router-dom';
|
||||
import axios from 'axios';
|
||||
import useAuth from '../context/useAuth';
|
||||
import { Turnstile } from '@marsidev/react-turnstile';
|
||||
import type { TurnstileInstance } from '@marsidev/react-turnstile';
|
||||
import { API_URL } from '../config/api';
|
||||
|
||||
const LoginPage = () => {
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [turnstileToken, setTurnstileToken] = useState<string | null>(null);
|
||||
const turnstileRef = useRef<TurnstileInstance>(null);
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const { login, isLoggedIn } = useAuth();
|
||||
|
||||
const siteKey = import.meta.env.VITE_TURNSTILE_SITE_KEY;
|
||||
|
||||
// Если уже авторизован — редирект на dashboard
|
||||
useEffect(() => {
|
||||
if (isLoggedIn) {
|
||||
navigate('/dashboard', { replace: true });
|
||||
}
|
||||
}, [isLoggedIn, navigate]);
|
||||
|
||||
// Обработка OAuth токена из URL
|
||||
const params = new URLSearchParams(location.search);
|
||||
const token = params.get('token');
|
||||
const authError = params.get('error');
|
||||
|
||||
if (token) {
|
||||
login(token);
|
||||
navigate('/dashboard', { replace: true });
|
||||
}
|
||||
|
||||
if (authError) {
|
||||
setError('Ошибка авторизации через социальную сеть. Попробуйте снова.');
|
||||
}
|
||||
}, [isLoggedIn, navigate, location, login]);
|
||||
|
||||
const handleLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
|
||||
if (!turnstileToken) {
|
||||
setError('Пожалуйста, подтвердите, что вы не робот.');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const response = await axios.post('https://ospab.host:5000/api/auth/login', {
|
||||
const response = await axios.post(`${API_URL}/api/auth/login`, {
|
||||
email: email,
|
||||
password: password,
|
||||
turnstileToken: turnstileToken,
|
||||
});
|
||||
login(response.data.token);
|
||||
// Возврат на исходную страницу, если был редирект
|
||||
@@ -35,6 +63,12 @@ const LoginPage = () => {
|
||||
const from = state?.from?.pathname || '/dashboard';
|
||||
navigate(from);
|
||||
} catch (err) {
|
||||
// Сброс капчи при ошибке
|
||||
if (turnstileRef.current) {
|
||||
turnstileRef.current.reset();
|
||||
}
|
||||
setTurnstileToken(null);
|
||||
|
||||
if (axios.isAxiosError(err) && err.response) {
|
||||
setError(err.response.data.message || 'Неизвестная ошибка входа.');
|
||||
} else {
|
||||
@@ -45,6 +79,10 @@ const LoginPage = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleOAuthLogin = (provider: string) => {
|
||||
window.location.href = `${API_URL}/api/auth/${provider}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<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">
|
||||
@@ -68,9 +106,24 @@ const LoginPage = () => {
|
||||
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}
|
||||
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 ? 'Входим...' : 'Войти'}
|
||||
@@ -81,6 +134,57 @@ const LoginPage = () => {
|
||||
<p className="text-sm text-red-600">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Социальные сети */}
|
||||
<div className="mt-6">
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<div className="w-full border-t border-gray-300"></div>
|
||||
</div>
|
||||
<div className="relative flex justify-center text-sm">
|
||||
<span className="px-2 bg-white text-gray-500">Или войти через</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 grid grid-cols-1 sm:grid-cols-3 gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleOAuthLogin('google')}
|
||||
className="w-full flex items-center justify-center px-3 py-2 border border-gray-300 rounded-lg shadow-sm bg-white text-xs sm:text-sm font-medium text-gray-700 hover:bg-gray-50 transition"
|
||||
>
|
||||
<svg className="h-5 w-5 mr-1 sm:mr-2 flex-shrink-0" viewBox="0 0 24 24">
|
||||
<path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
|
||||
<path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
|
||||
<path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/>
|
||||
<path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
|
||||
</svg>
|
||||
<span className="truncate">Google</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleOAuthLogin('github')}
|
||||
className="w-full flex items-center justify-center px-3 py-2 border border-gray-300 rounded-lg shadow-sm bg-white text-xs sm:text-sm font-medium text-gray-700 hover:bg-gray-50 transition"
|
||||
>
|
||||
<svg className="h-5 w-5 mr-1 sm:mr-2 flex-shrink-0" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path fillRule="evenodd" d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z" clipRule="evenodd"/>
|
||||
</svg>
|
||||
<span className="truncate">GitHub</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleOAuthLogin('yandex')}
|
||||
className="w-full flex items-center justify-center px-3 py-2 border border-gray-300 rounded-lg shadow-sm bg-white text-xs sm:text-sm font-medium text-gray-700 hover:bg-gray-50 transition"
|
||||
>
|
||||
<svg className="h-5 w-5 mr-1 sm:mr-2 flex-shrink-0" viewBox="0 0 24 24">
|
||||
<path fill="#FC3F1D" d="M13.04 1.5H8.87c-4.62 0-6.9 2.07-6.9 6.28v2.6c0 2.48.68 4.16 2.04 5.18L8.73 22.5h2.84l-4.56-6.56c-1.04-.8-1.56-2.16-1.56-4.16v-2.6c0-3.04 1.44-4.36 4.42-4.36h3.17c2.98 0 4.42 1.32 4.42 4.36v1.56h2.48v-1.56c0-4.21-2.28-6.28-6.9-6.28z"/>
|
||||
</svg>
|
||||
<span className="truncate">Yandex</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="mt-6 text-gray-600">
|
||||
Нет аккаунта?{' '}
|
||||
<Link to="/register" className="text-ospab-primary font-bold hover:underline">
|
||||
|
||||
@@ -1,38 +1,87 @@
|
||||
import { useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import { Link, useNavigate, useLocation } from 'react-router-dom';
|
||||
import axios from 'axios';
|
||||
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';
|
||||
|
||||
const RegisterPage = () => {
|
||||
const { addToast } = useToast();
|
||||
const [username, setUsername] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [turnstileToken, setTurnstileToken] = useState<string | null>(null);
|
||||
const turnstileRef = useRef<TurnstileInstance>(null);
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const { login } = useAuth();
|
||||
|
||||
const siteKey = import.meta.env.VITE_TURNSTILE_SITE_KEY;
|
||||
|
||||
// Обработка OAuth токена из URL
|
||||
useEffect(() => {
|
||||
const params = new URLSearchParams(location.search);
|
||||
const token = params.get('token');
|
||||
const authError = params.get('error');
|
||||
|
||||
if (token) {
|
||||
login(token);
|
||||
navigate('/dashboard', { replace: true });
|
||||
}
|
||||
|
||||
if (authError) {
|
||||
setError('Ошибка авторизации через социальную сеть. Попробуйте снова.');
|
||||
}
|
||||
}, [location, login, navigate]);
|
||||
|
||||
const handleRegister = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(''); // Очищаем предыдущие ошибки
|
||||
|
||||
if (!turnstileToken) {
|
||||
setError('Пожалуйста, подтвердите, что вы не робот.');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
await axios.post('https://ospab.host:5000/api/auth/register', {
|
||||
await axios.post(`${API_URL}/api/auth/register`, {
|
||||
username: username,
|
||||
email: email,
|
||||
password: password
|
||||
password: password,
|
||||
turnstileToken: turnstileToken,
|
||||
});
|
||||
|
||||
alert('Регистрация прошла успешно! Теперь вы можете войти.');
|
||||
addToast('Регистрация прошла успешно! Теперь вы можете войти.', 'success');
|
||||
navigate('/login');
|
||||
|
||||
} catch (err) {
|
||||
// Сброс капчи при ошибке
|
||||
if (turnstileRef.current) {
|
||||
turnstileRef.current.reset();
|
||||
}
|
||||
setTurnstileToken(null);
|
||||
|
||||
if (axios.isAxiosError(err) && err.response) {
|
||||
const errorMsg = err.response.data.message || 'Неизвестная ошибка регистрации.';
|
||||
setError(errorMsg);
|
||||
} else {
|
||||
setError('Произошла ошибка сети. Пожалуйста, попробуйте позже.');
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleOAuthLogin = (provider: string) => {
|
||||
window.location.href = `${API_URL}/api/auth/${provider}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<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">
|
||||
@@ -58,17 +107,86 @@ const RegisterPage = () => {
|
||||
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"
|
||||
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={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 && (
|
||||
<p className="mt-4 text-sm text-red-500">{error}</p>
|
||||
)}
|
||||
|
||||
{/* Социальные сети */}
|
||||
<div className="mt-6">
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<div className="w-full border-t border-gray-300"></div>
|
||||
</div>
|
||||
<div className="relative flex justify-center text-sm">
|
||||
<span className="px-2 bg-white text-gray-500">Или зарегистрироваться через</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 grid grid-cols-1 sm:grid-cols-3 gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleOAuthLogin('google')}
|
||||
className="w-full flex items-center justify-center px-3 py-2 border border-gray-300 rounded-lg shadow-sm bg-white text-xs sm:text-sm font-medium text-gray-700 hover:bg-gray-50 transition"
|
||||
>
|
||||
<svg className="h-5 w-5 mr-1 sm:mr-2 flex-shrink-0" viewBox="0 0 24 24">
|
||||
<path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
|
||||
<path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
|
||||
<path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/>
|
||||
<path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
|
||||
</svg>
|
||||
<span className="truncate">Google</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleOAuthLogin('github')}
|
||||
className="w-full flex items-center justify-center px-3 py-2 border border-gray-300 rounded-lg shadow-sm bg-white text-xs sm:text-sm font-medium text-gray-700 hover:bg-gray-50 transition"
|
||||
>
|
||||
<svg className="h-5 w-5 mr-1 sm:mr-2 flex-shrink-0" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path fillRule="evenodd" d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z" clipRule="evenodd"/>
|
||||
</svg>
|
||||
<span className="truncate">GitHub</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleOAuthLogin('yandex')}
|
||||
className="w-full flex items-center justify-center px-3 py-2 border border-gray-300 rounded-lg shadow-sm bg-white text-xs sm:text-sm font-medium text-gray-700 hover:bg-gray-50 transition"
|
||||
>
|
||||
<svg className="h-5 w-5 mr-1 sm:mr-2 flex-shrink-0" viewBox="0 0 24 24">
|
||||
<path fill="#FC3F1D" d="M13.04 1.5H8.87c-4.62 0-6.9 2.07-6.9 6.28v2.6c0 2.48.68 4.16 2.04 5.18L8.73 22.5h2.84l-4.56-6.56c-1.04-.8-1.56-2.16-1.56-4.16v-2.6c0-3.04 1.44-4.36 4.42-4.36h3.17c2.98 0 4.42 1.32 4.42 4.36v1.56h2.48v-1.56c0-4.21-2.28-6.28-6.9-6.28z"/>
|
||||
</svg>
|
||||
<span className="truncate">Yandex</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="mt-6 text-gray-600">
|
||||
Уже есть аккаунт?{' '}
|
||||
<Link to="/login" className="text-ospab-primary font-bold hover:underline">
|
||||
|
||||
@@ -36,10 +36,10 @@ const TariffsPage = () => {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 py-20">
|
||||
<div className="min-h-screen bg-gray-50 py-12 lg:py-20">
|
||||
<div className="container mx-auto px-4">
|
||||
<h1 className="text-4xl md:text-5xl font-bold text-center mb-6 text-gray-900">Тарифы</h1>
|
||||
<p className="text-lg text-gray-600 text-center mb-10 max-w-2xl mx-auto">
|
||||
<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 ? (
|
||||
@@ -49,22 +49,22 @@ const TariffsPage = () => {
|
||||
) : tariffs.length === 0 ? (
|
||||
<p className="text-lg text-gray-500 text-center">Нет доступных тарифов.</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-8 mb-20">
|
||||
<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-12 rounded-3xl shadow-2xl text-left flex flex-col justify-between transition-transform hover:scale-105 duration-300 min-h-[340px]">
|
||||
<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-4xl font-bold text-gray-800 mb-4">{tariff.name}</h2>
|
||||
<p className="mb-4 text-5xl font-extrabold text-ospab-primary">₽{tariff.price}<span className="text-xl font-normal text-gray-500">/мес</span></p>
|
||||
<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-lg text-gray-700 mb-6 list-disc list-inside">
|
||||
<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}>{desc.trim()}</li>
|
||||
<li key={i} className="break-words">{desc.trim()}</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
className="mt-4 px-8 py-4 rounded-full text-white font-bold text-xl transition-colors transform hover:scale-105 bg-ospab-primary hover:bg-ospab-accent"
|
||||
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)}
|
||||
>
|
||||
Купить
|
||||
|
||||
Reference in New Issue
Block a user