ssh! и документы
This commit is contained in:
80
ospabhost/frontend/src/assets/logo.svg
Normal file
80
ospabhost/frontend/src/assets/logo.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 72 KiB |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
Before Width: | Height: | Size: 4.0 KiB |
120
ospabhost/frontend/src/components/ServerConsole.tsx
Normal file
120
ospabhost/frontend/src/components/ServerConsole.tsx
Normal file
@@ -0,0 +1,120 @@
|
||||
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;
|
||||
@@ -10,7 +10,8 @@ const DashboardTempl: React.FC<DashboardTemplProps> = ({ children }) => {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<Header />
|
||||
<div className="pt-16">
|
||||
<div className="border-t border-gray-200" />
|
||||
<div>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import logo from '../assets/logo.svg';
|
||||
|
||||
const Footer = () => {
|
||||
const currentYear = new Date().getFullYear();
|
||||
@@ -9,6 +10,9 @@ const Footer = () => {
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-8 text-center md:text-left">
|
||||
{/* About Section */}
|
||||
<div>
|
||||
<div className="mb-4 flex justify-center md:justify-start">
|
||||
<img src={logo} alt="Логотип" className="h-16 w-auto" />
|
||||
</div>
|
||||
<h3 className="text-xl font-bold mb-4">О нас</h3>
|
||||
<p className="text-sm text-gray-400">
|
||||
ospab.host - это надежный хостинг для ваших проектов. Мы предлагаем высокую производительность и круглосуточную поддержку.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import useAuth from '../context/useAuth';
|
||||
import logo from '../assets/logo.svg';
|
||||
|
||||
const Header = () => {
|
||||
const { isLoggedIn, logout } = useAuth();
|
||||
@@ -9,10 +10,13 @@ const Header = () => {
|
||||
};
|
||||
|
||||
return (
|
||||
<header className="fixed top-0 left-0 right-0 z-50 bg-white shadow-md">
|
||||
<header className="static bg-white shadow-md">
|
||||
<div className="container mx-auto px-4 py-4 flex justify-between items-center">
|
||||
<div className="text-xl font-bold text-gray-800">
|
||||
<Link to="/" className="font-mono text-2xl">ospab.host</Link>
|
||||
<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>
|
||||
|
||||
@@ -10,7 +10,7 @@ const PageTmpl: React.FC<PageTmplProps> = ({ children }) => {
|
||||
return (
|
||||
<div className="flex flex-col min-h-screen">
|
||||
<Header />
|
||||
<main className="flex-grow pt-16">
|
||||
<main className="flex-grow">
|
||||
{children}
|
||||
</main>
|
||||
<Footer />
|
||||
|
||||
@@ -1,14 +1,33 @@
|
||||
|
||||
const AboutPage = () => {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex items-center justify-center py-20 px-4">
|
||||
<div className="bg-white p-10 rounded-3xl shadow-2xl max-w-4xl mx-auto text-center">
|
||||
<h1 className="text-4xl md:text-5xl font-bold text-gray-900 mb-6">О компании ospab.host</h1>
|
||||
<p className="text-lg text-gray-700 mb-4">
|
||||
Мы предоставляем надежные и масштабируемые хостинг-решения для разработчиков, стартапов и крупных компаний. Наша миссия — дать вам инструменты, необходимые для реализации ваших идей в интернете, обеспечивая при этом высокую производительность и безопасность.
|
||||
</p>
|
||||
<p className="text-lg text-gray-700">
|
||||
Наша инфраструктура построена на современных технологиях, а круглосуточная поддержка всегда готова помочь вам. Мы верим, что качественный хостинг должен быть доступен каждому.
|
||||
</p>
|
||||
<div className="min-h-screen bg-gradient-to-br from-blue-100 via-white to-ospab-primary flex items-center justify-center py-20 px-4">
|
||||
<div className="bg-white p-10 md:p-16 rounded-3xl shadow-2xl max-w-4xl mx-auto text-center border-4 border-ospab-primary/20">
|
||||
<h1 className="text-5xl md:text-6xl font-extrabold text-ospab-primary mb-8 drop-shadow-lg">История ospab.host</h1>
|
||||
<div className="flex flex-col md:flex-row items-center gap-8 mb-8">
|
||||
<img src="/me.jpg" alt="Георгий" className="w-32 h-32 rounded-full shadow-lg border-4 border-ospab-primary mx-auto" />
|
||||
<div className="text-left md:text-center">
|
||||
<h2 className="text-3xl font-bold text-gray-900 mb-2">Георгий, основатель</h2>
|
||||
<p className="text-lg text-gray-700 mb-2">Возраст: 13 лет</p>
|
||||
<p className="text-lg text-gray-700">Великий Новгород, Россия</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-lg text-gray-800 leading-relaxed mb-6">
|
||||
<p className="mb-4">В сентябре 2025 года я, Георгий, начал работу над первым дата-центром (ЦОД) и крупным хостингом в Великом Новгороде. Всё началось с мечты — создать место, где любой сможет разместить свой проект, сайт или сервер с максимальной надёжностью и скоростью.</p>
|
||||
<p className="mb-4">Сейчас я работаю над хостингом для будущего ЦОД, а мой друг-инвестор помогает с развитием инфраструктуры. Мы строим не просто сервис, а сообщество, где каждый клиент — как друг, а поддержка всегда рядом.</p>
|
||||
<p className="mb-4">ospab.host — это не просто хостинг. Это первый шаг к цифровому будущему Великого Новгорода, созданный с нуля школьником, который верит в технологии и силу дружбы.</p>
|
||||
<p className="mb-4">Наша миссия — сделать качественный хостинг доступным для всех, а ЦОД — гордостью города. Мы используем современные технологии, заботимся о безопасности и всегда готовы помочь.</p>
|
||||
</div>
|
||||
<div className="bg-ospab-primary/10 rounded-xl p-6 mt-8">
|
||||
<h3 className="text-2xl font-bold text-ospab-primary mb-2">Почему выбирают ospab.host?</h3>
|
||||
<ul className="list-disc list-inside text-lg text-gray-700 text-left mx-auto max-w-xl">
|
||||
<li>Первый ЦОД и крупный хостинг в Великом Новгороде</li>
|
||||
<li>Личная поддержка от основателя</li>
|
||||
<li>Современная инфраструктура и технологии</li>
|
||||
<li>Доступные тарифы для всех</li>
|
||||
<li>История, которой можно гордиться</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -36,7 +36,7 @@ const Billing = () => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', checkFile);
|
||||
formData.append('amount', String(amount));
|
||||
const response = await axios.post('http://localhost:5000/api/check/upload', formData, {
|
||||
const response = await axios.post('https://ospab.host:5000/api/check/upload', formData, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
// 'Content-Type' не указываем вручную для FormData!
|
||||
|
||||
@@ -33,9 +33,11 @@ const Checkout: React.FC<CheckoutProps> = ({ onSuccess }) => {
|
||||
// Загрузка тарифов и ОС
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
const [tariffRes, osRes] = await Promise.all([
|
||||
axios.get('http://localhost:5000/api/tariff'),
|
||||
axios.get('http://localhost:5000/api/os'),
|
||||
axios.get('https://ospab.host:5000/api/tariff', { headers }),
|
||||
axios.get('https://ospab.host:5000/api/os', { headers }),
|
||||
]);
|
||||
setTariffs(tariffRes.data);
|
||||
setOses(osRes.data);
|
||||
@@ -62,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('http://localhost:5000/api/server/create', {
|
||||
const res = await axios.post('https://ospab.host:5000/api/server/create', {
|
||||
tariffId: selectedTariff,
|
||||
osId: selectedOs,
|
||||
}, {
|
||||
@@ -76,7 +78,7 @@ const Checkout: React.FC<CheckoutProps> = ({ onSuccess }) => {
|
||||
}
|
||||
// После успешной покупки обновляем userData
|
||||
try {
|
||||
const userRes = await axios.get('http://localhost:5000/api/auth/me', { headers: token ? { Authorization: `Bearer ${token}` } : {} });
|
||||
const userRes = await axios.get('https://ospab.host:5000/api/auth/me', { headers: token ? { Authorization: `Bearer ${token}` } : {} });
|
||||
window.dispatchEvent(new CustomEvent('userDataUpdate', {
|
||||
detail: {
|
||||
user: userRes.data.user,
|
||||
|
||||
@@ -18,7 +18,7 @@ interface ICheck {
|
||||
user?: IUser;
|
||||
}
|
||||
|
||||
const API_URL = 'http://localhost:5000/api/check';
|
||||
const API_URL = 'https://ospab.host:5000/api/check';
|
||||
|
||||
const CheckVerification: React.FC = () => {
|
||||
const [checks, setChecks] = useState<ICheck[]>([]);
|
||||
@@ -61,7 +61,7 @@ const CheckVerification: React.FC = () => {
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
const userRes = await axios.get('http://localhost:5000/api/auth/me', { headers });
|
||||
const userRes = await axios.get('https://ospab.host:5000/api/auth/me', { headers });
|
||||
// Глобально обновить userData через типизированное событие (для Dashboard)
|
||||
window.dispatchEvent(new CustomEvent<import('./types').UserData>('userDataUpdate', {
|
||||
detail: {
|
||||
@@ -109,8 +109,8 @@ const CheckVerification: React.FC = () => {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col items-center gap-2 md:ml-8">
|
||||
<a href={`http://localhost:5000${check.fileUrl}`} target="_blank" rel="noopener noreferrer" className="block mb-2">
|
||||
<img src={`http://localhost:5000${check.fileUrl}`} alt="Чек" className="w-32 h-32 object-contain rounded-xl border" />
|
||||
<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>
|
||||
{check.status === 'pending' && (
|
||||
<>
|
||||
|
||||
@@ -49,7 +49,7 @@ const Dashboard = () => {
|
||||
return;
|
||||
}
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
const userRes = await axios.get('http://localhost:5000/api/auth/me', { headers });
|
||||
const userRes = await axios.get('https://ospab.host:5000/api/auth/me', { headers });
|
||||
setUserData({
|
||||
user: userRes.data.user,
|
||||
balance: userRes.data.user.balance ?? 0,
|
||||
@@ -75,7 +75,7 @@ const Dashboard = () => {
|
||||
const token = localStorage.getItem('access_token');
|
||||
if (!token) return;
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
const userRes = await axios.get('http://localhost:5000/api/auth/me', { headers });
|
||||
const userRes = await axios.get('https://ospab.host:5000/api/auth/me', { headers });
|
||||
setUserData({
|
||||
user: userRes.data.user,
|
||||
balance: userRes.data.user.balance ?? 0,
|
||||
@@ -198,7 +198,12 @@ const Dashboard = () => {
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex-1 p-8">
|
||||
<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>
|
||||
)}
|
||||
<Routes>
|
||||
<Route path="/" element={<Summary userData={userData ?? { user: { username: '', operator: 0 }, balance: 0, servers: [], tickets: [] }} />} />
|
||||
<Route path="servers" element={<Servers />} />
|
||||
|
||||
@@ -1,315 +1,10 @@
|
||||
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import ServerConsole from '../../components/ServerConsole';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import axios, { AxiosError } from 'axios';
|
||||
import { useServerStats } from '../../hooks/useSocket';
|
||||
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
|
||||
|
||||
// Встроенная секция консоли
|
||||
function ConsoleSection({ serverId }: { serverId: number }) {
|
||||
const [consoleUrl, setConsoleUrl] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const handleOpenConsole = async () => {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
const res = await axios.post(`http://localhost:5000/api/proxmox/console`, { vmid: serverId }, { headers });
|
||||
if (res.data?.status === 'success' && res.data.url) {
|
||||
setConsoleUrl(res.data.url);
|
||||
} else {
|
||||
setError('Ошибка открытия консоли');
|
||||
}
|
||||
} catch {
|
||||
setError('Ошибка открытия консоли');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-gray-100 rounded-xl p-6 text-gray-700 font-mono text-sm flex flex-col items-center">
|
||||
<div className="mb-2 font-bold">Консоль сервера</div>
|
||||
{!consoleUrl ? (
|
||||
<button
|
||||
className="bg-ospab-primary text-white px-6 py-3 rounded-full font-bold mb-4"
|
||||
onClick={handleOpenConsole}
|
||||
disabled={loading}
|
||||
>{loading ? 'Открытие...' : 'Открыть noVNC консоль'}</button>
|
||||
) : (
|
||||
<iframe
|
||||
src={consoleUrl}
|
||||
title="noVNC Console"
|
||||
className="w-full h-[600px] rounded-lg border"
|
||||
allowFullScreen
|
||||
/>
|
||||
)}
|
||||
{error && <div className="text-red-500 text-base font-semibold text-center mt-2">{error}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Модальное окно для изменения конфигурации
|
||||
function ResizeModal({ serverId, onClose, onSuccess }: { serverId: number; onClose: () => void; onSuccess: () => void }) {
|
||||
const [cores, setCores] = useState('');
|
||||
const [memory, setMemory] = useState('');
|
||||
const [disk, setDisk] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const handleResize = async () => {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
const data: any = {};
|
||||
if (cores) data.cores = Number(cores);
|
||||
if (memory) data.memory = Number(memory);
|
||||
if (disk) data.disk = Number(disk);
|
||||
|
||||
const res = await axios.put(`http://localhost:5000/api/server/${serverId}/resize`, data, { headers });
|
||||
if (res.data?.status === 'success') {
|
||||
onSuccess();
|
||||
onClose();
|
||||
} else {
|
||||
setError('Ошибка изменения конфигурации');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Ошибка изменения конфигурации');
|
||||
console.error(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" onClick={onClose}>
|
||||
<div className="bg-white rounded-3xl shadow-xl p-8 max-w-md w-full" onClick={(e) => e.stopPropagation()}>
|
||||
<h2 className="text-2xl font-bold mb-6">Изменить конфигурацию</h2>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-semibold mb-2">Количество ядер CPU</label>
|
||||
<input
|
||||
type="number"
|
||||
value={cores}
|
||||
onChange={(e) => setCores(e.target.value)}
|
||||
className="w-full px-4 py-2 border rounded-lg"
|
||||
placeholder="Оставьте пустым, чтобы не менять"
|
||||
min="1"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-semibold mb-2">RAM (МБ)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={memory}
|
||||
onChange={(e) => setMemory(e.target.value)}
|
||||
className="w-full px-4 py-2 border rounded-lg"
|
||||
placeholder="Например: 2048"
|
||||
min="512"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-semibold mb-2">Диск (ГБ)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={disk}
|
||||
onChange={(e) => setDisk(e.target.value)}
|
||||
className="w-full px-4 py-2 border rounded-lg"
|
||||
placeholder="Например: 40"
|
||||
min="10"
|
||||
/>
|
||||
</div>
|
||||
{error && <div className="text-red-500">{error}</div>}
|
||||
<div className="flex gap-4">
|
||||
<button
|
||||
onClick={handleResize}
|
||||
disabled={loading}
|
||||
className="flex-1 bg-ospab-primary text-white px-6 py-3 rounded-full font-bold disabled:opacity-50"
|
||||
>
|
||||
{loading ? 'Изменение...' : 'Применить'}
|
||||
</button>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="flex-1 bg-gray-300 text-gray-700 px-6 py-3 rounded-full font-bold"
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Компонент для управления снэпшотами
|
||||
function SnapshotsSection({ serverId }: { serverId: number }) {
|
||||
const [snapshots, setSnapshots] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [snapName, setSnapName] = useState('');
|
||||
const [snapDesc, setSnapDesc] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
loadSnapshots();
|
||||
}, [serverId]);
|
||||
|
||||
const loadSnapshots = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
const res = await axios.get(`http://localhost:5000/api/server/${serverId}/snapshots`, { headers });
|
||||
if (res.data?.status === 'success') {
|
||||
setSnapshots(res.data.data || []);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error loading snapshots:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateSnapshot = async () => {
|
||||
if (!snapName) {
|
||||
setError('Введите имя снэпшота');
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
const res = await axios.post(
|
||||
`http://localhost:5000/api/server/${serverId}/snapshots`,
|
||||
{ snapname: snapName, description: snapDesc },
|
||||
{ headers }
|
||||
);
|
||||
if (res.data?.status === 'success') {
|
||||
setSnapName('');
|
||||
setSnapDesc('');
|
||||
loadSnapshots();
|
||||
} else {
|
||||
setError('Ошибка создания снэпшота');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Ошибка создания снэпшота');
|
||||
console.error(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRollback = async (snapname: string) => {
|
||||
if (!confirm(`Восстановить из снэпшота ${snapname}? Текущее состояние будет потеряно.`)) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
await axios.post(
|
||||
`http://localhost:5000/api/server/${serverId}/snapshots/rollback`,
|
||||
{ snapname },
|
||||
{ headers }
|
||||
);
|
||||
alert('Снэпшот восстановлен');
|
||||
} catch (err) {
|
||||
alert('Ошибка восстановления снэпшота');
|
||||
console.error(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (snapname: string) => {
|
||||
if (!confirm(`Удалить снэпшот ${snapname}?`)) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
await axios.delete(
|
||||
`http://localhost:5000/api/server/${serverId}/snapshots`,
|
||||
{ data: { snapname }, headers }
|
||||
);
|
||||
loadSnapshots();
|
||||
} catch (err) {
|
||||
alert('Ошибка удаления снэпшота');
|
||||
console.error(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-gray-100 rounded-xl p-6">
|
||||
<h3 className="text-xl font-bold mb-4">Управление снэпшотами</h3>
|
||||
|
||||
<div className="bg-white rounded-lg p-4 mb-4">
|
||||
<h4 className="font-semibold mb-3">Создать новый снэпшот</h4>
|
||||
<div className="space-y-3">
|
||||
<input
|
||||
type="text"
|
||||
value={snapName}
|
||||
onChange={(e) => setSnapName(e.target.value)}
|
||||
placeholder="Имя снэпшота (например: backup-2024)"
|
||||
className="w-full px-4 py-2 border rounded-lg"
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
value={snapDesc}
|
||||
onChange={(e) => setSnapDesc(e.target.value)}
|
||||
placeholder="Описание (опционально)"
|
||||
className="w-full px-4 py-2 border rounded-lg"
|
||||
/>
|
||||
{error && <div className="text-red-500 text-sm">{error}</div>}
|
||||
<button
|
||||
onClick={handleCreateSnapshot}
|
||||
disabled={loading}
|
||||
className="bg-ospab-primary text-white px-6 py-2 rounded-full font-bold disabled:opacity-50"
|
||||
>
|
||||
{loading ? 'Создание...' : 'Создать снэпшот'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg p-4">
|
||||
<h4 className="font-semibold mb-3">Существующие снэпшоты</h4>
|
||||
{snapshots.length === 0 ? (
|
||||
<p className="text-gray-500">Снэпшотов пока нет</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{snapshots.map((snap) => (
|
||||
<div key={snap.name} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
|
||||
<div>
|
||||
<div className="font-semibold">{snap.name}</div>
|
||||
<div className="text-sm text-gray-600">{snap.description || 'Без описания'}</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => handleRollback(snap.name)}
|
||||
className="bg-blue-500 text-white px-4 py-1 rounded-full text-sm font-semibold hover:bg-blue-600"
|
||||
>
|
||||
Восстановить
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(snap.name)}
|
||||
className="bg-red-500 text-white px-4 py-1 rounded-full text-sm font-semibold hover:bg-red-600"
|
||||
>
|
||||
Удалить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Типы
|
||||
interface Server {
|
||||
id: number;
|
||||
status: string;
|
||||
@@ -328,40 +23,44 @@ interface ServerStats {
|
||||
};
|
||||
}
|
||||
|
||||
// ...existing code...
|
||||
|
||||
// ConsoleSection больше не нужен
|
||||
|
||||
const TABS = [
|
||||
{ key: 'overview', label: 'Обзор' },
|
||||
{ key: 'console', label: 'Консоль' },
|
||||
{ key: 'stats', label: 'Статистика' },
|
||||
{ key: 'manage', label: 'Управление' },
|
||||
{ key: 'snapshots', label: 'Снэпшоты' },
|
||||
{ key: 'resize', 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 [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 [showResizeModal, setShowResizeModal] = useState(false);
|
||||
|
||||
// Real-time WebSocket stats
|
||||
const { stats: realtimeStats, alerts, connected } = useServerStats(server?.id || null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchServer = async () => {
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
const res = await axios.get(`http://localhost:5000/api/server/${id}`, { headers });
|
||||
const res = await axios.get(`https://ospab.host:5000/api/server/${id}`, { headers });
|
||||
setServer(res.data);
|
||||
// Получаем статистику
|
||||
const statsRes = await axios.get(`http://localhost:5000/api/server/${id}/status`, { headers });
|
||||
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;
|
||||
@@ -381,18 +80,26 @@ const ServerPanel: React.FC = () => {
|
||||
// Смена root-пароля через backend
|
||||
const handleGenerateRoot = async () => {
|
||||
try {
|
||||
setError('');
|
||||
setSuccess('');
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
const res = await axios.post(`http://localhost:5000/api/server/${id}/password`, {}, { headers });
|
||||
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-пароль успешно изменён!');
|
||||
} else {
|
||||
setError('Ошибка смены root-пароля');
|
||||
console.error('Ошибка смены root-пароля:', res.data);
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Ошибка смены root-пароля');
|
||||
console.error('Ошибка смены root-пароля:', err);
|
||||
const axiosErr = err as AxiosError;
|
||||
if (axiosErr && axiosErr.response) {
|
||||
console.error('Ответ сервера:', axiosErr.response.data);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -400,16 +107,19 @@ const ServerPanel: React.FC = () => {
|
||||
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(`http://localhost:5000/api/server/${id}/${action}`, {}, { headers });
|
||||
if (res.data?.status === 'success') {
|
||||
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(`http://localhost:5000/api/server/${id}`, { headers });
|
||||
const updated = await axios.get(`https://ospab.host:5000/api/server/${id}`, { headers });
|
||||
setServer(updated.data);
|
||||
const statsRes = await axios.get(`http://localhost:5000/api/server/${id}/status`, { headers });
|
||||
const statsRes = await axios.get(`https://ospab.host:5000/api/server/${id}/status`, { headers });
|
||||
setStats(statsRes.data.stats);
|
||||
setSuccess('Действие выполнено успешно!');
|
||||
} else {
|
||||
setError(`Ошибка: ${res.data?.message || 'Не удалось выполнить действие'}`);
|
||||
}
|
||||
@@ -418,229 +128,217 @@ const ServerPanel: React.FC = () => {
|
||||
console.error('Ошибка управления сервером:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setActiveAction(null);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return <div className="flex min-h-screen items-center justify-center"><span className="text-gray-500 text-lg">Загрузка...</span></div>;
|
||||
}
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-gray-50">
|
||||
<div className="bg-white rounded-3xl shadow-xl p-10 max-w-xl w-full flex flex-col items-center">
|
||||
<span className="text-red-500 text-xl font-bold mb-4">{error}</span>
|
||||
<button
|
||||
className="bg-ospab-primary text-white px-6 py-3 rounded-full font-bold hover:bg-ospab-primary-dark transition"
|
||||
onClick={() => window.location.href = '/dashboard/servers'}
|
||||
>
|
||||
Вернуться к списку серверов
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!server) {
|
||||
return <div className="flex min-h-screen items-center justify-center"><span className="text-red-500 text-lg">Сервер не найден</span></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 max-w-3xl w-full mt-10">
|
||||
<h1 className="text-3xl font-bold text-gray-800 mb-6">Панель управления сервером #{server.id}</h1>
|
||||
<div className="flex gap-4 mb-8">
|
||||
<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={`px-5 py-2 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'}`}
|
||||
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>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{activeTab === 'overview' && (
|
||||
<div className="space-y-4">
|
||||
<div className="text-lg text-gray-800 font-bold">Статус: <span className="font-normal">{server.status}</span></div>
|
||||
<div className="text-lg text-gray-800 font-bold">Тариф: <span className="font-normal">{server.tariff.name} ({server.tariff.price}₽)</span></div>
|
||||
<div className="text-lg text-gray-800 font-bold">ОС: <span className="font-normal">{server.os.name} ({server.os.type})</span></div>
|
||||
<div className="text-lg text-gray-800 font-bold">IP: <span className="font-normal">{server.ip || '—'}</span></div>
|
||||
<div className="text-lg text-gray-800 font-bold">Создан: <span className="font-normal">{new Date(server.createdAt).toLocaleString()}</span></div>
|
||||
<div className="text-lg text-gray-800 font-bold">Обновлён: <span className="font-normal">{new Date(server.updatedAt).toLocaleString()}</span></div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
{activeTab === 'console' && (
|
||||
<ConsoleSection serverId={server.id} />
|
||||
)}
|
||||
|
||||
{activeTab === 'stats' && (
|
||||
<div className="space-y-6">
|
||||
{/* WebSocket connection status */}
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<div className={`w-3 h-3 rounded-full ${connected ? 'bg-green-500' : 'bg-red-500'}`}></div>
|
||||
<span className="text-sm text-gray-600">
|
||||
{connected ? 'Подключено к live-мониторингу' : 'Нет подключения к мониторингу'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Alerts */}
|
||||
{alerts.length > 0 && (
|
||||
<div className="bg-yellow-50 border border-yellow-200 rounded-xl p-4">
|
||||
<h3 className="font-bold text-yellow-800 mb-2">⚠️ Предупреждения</h3>
|
||||
<div className="space-y-1">
|
||||
{alerts.map((alert, idx) => (
|
||||
<div key={idx} className="text-yellow-700 text-sm">
|
||||
{alert.message}
|
||||
</div>
|
||||
))}
|
||||
</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>
|
||||
)}
|
||||
|
||||
{/* Real-time stats cards */}
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div className="bg-white rounded-xl p-6 shadow-sm">
|
||||
<div className="font-bold text-gray-700 mb-2">CPU</div>
|
||||
<div className="text-3xl text-ospab-primary font-bold">
|
||||
{realtimeStats?.data?.cpu ? (realtimeStats.data.cpu * 100).toFixed(1) : stats?.data?.cpu ? (stats.data.cpu * 100).toFixed(1) : '—'}%
|
||||
<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>
|
||||
<div className="bg-white rounded-xl p-6 shadow-sm">
|
||||
<div className="font-bold text-gray-700 mb-2">RAM</div>
|
||||
<div className="text-3xl text-ospab-primary font-bold">
|
||||
{realtimeStats?.data?.memory?.usage?.toFixed(1) || stats?.data?.memory?.usage?.toFixed(1) || '—'}%
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white rounded-xl p-6 shadow-sm">
|
||||
<div className="font-bold text-gray-700 mb-2">Disk</div>
|
||||
<div className="text-3xl text-ospab-primary font-bold">
|
||||
{realtimeStats?.data?.disk?.usage?.toFixed(1) || '—'}%
|
||||
<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>
|
||||
)}
|
||||
|
||||
{/* Charts */}
|
||||
{realtimeStats?.data?.rrdData && realtimeStats.data.rrdData.length > 0 && (
|
||||
<div className="bg-white rounded-xl p-6 shadow-sm">
|
||||
<h3 className="font-bold text-gray-800 mb-4">История использования (последний час)</h3>
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<LineChart data={realtimeStats.data.rrdData}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis dataKey="time" hide />
|
||||
<YAxis />
|
||||
<Tooltip />
|
||||
<Legend />
|
||||
<Line type="monotone" dataKey="cpu" stroke="#8b5cf6" name="CPU %" />
|
||||
<Line type="monotone" dataKey="mem" stroke="#3b82f6" name="Memory (bytes)" />
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
)}
|
||||
{activeTab === 'console' && server && (
|
||||
<ServerConsole />
|
||||
)}
|
||||
|
||||
{/* Detailed stats */}
|
||||
{activeTab === 'stats' && (
|
||||
<div className="bg-gray-100 rounded-xl p-6">
|
||||
<div className="mb-2 font-bold">Детальная статистика</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="bg-white rounded-lg p-4">
|
||||
<div className="text-sm text-gray-600">Memory Used</div>
|
||||
<div className="text-lg font-semibold">
|
||||
{realtimeStats?.data?.memory?.used
|
||||
? `${(realtimeStats.data.memory.used / (1024 * 1024 * 1024)).toFixed(2)} GB`
|
||||
: '—'}
|
||||
</div>
|
||||
<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="bg-white rounded-lg p-4">
|
||||
<div className="text-sm text-gray-600">Memory Max</div>
|
||||
<div className="text-lg font-semibold">
|
||||
{realtimeStats?.data?.memory?.max
|
||||
? `${(realtimeStats.data.memory.max / (1024 * 1024 * 1024)).toFixed(2)} GB`
|
||||
: '—'}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white rounded-lg p-4">
|
||||
<div className="text-sm text-gray-600">Network In</div>
|
||||
<div className="text-lg font-semibold">
|
||||
{realtimeStats?.data?.network?.in
|
||||
? `${(realtimeStats.data.network.in / (1024 * 1024)).toFixed(2)} MB`
|
||||
: '—'}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white rounded-lg p-4">
|
||||
<div className="text-sm text-gray-600">Network Out</div>
|
||||
<div className="text-lg font-semibold">
|
||||
{realtimeStats?.data?.network?.out
|
||||
? `${(realtimeStats.data.network.out / (1024 * 1024)).toFixed(2)} MB`
|
||||
: '—'}
|
||||
</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>
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
|
||||
{activeTab === 'manage' && (
|
||||
<div className="flex gap-6">
|
||||
<button className="bg-green-500 hover:bg-green-600 text-white px-6 py-3 rounded-full font-bold" onClick={() => handleAction('start')}>Запустить</button>
|
||||
<button className="bg-yellow-500 hover:bg-yellow-600 text-white px-6 py-3 rounded-full font-bold" onClick={() => handleAction('restart')}>Перезагрузить</button>
|
||||
<button className="bg-red-500 hover:bg-red-600 text-white px-6 py-3 rounded-full font-bold" onClick={() => handleAction('stop')}>Остановить</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'snapshots' && (
|
||||
<SnapshotsSection serverId={server.id} />
|
||||
)}
|
||||
|
||||
{activeTab === 'resize' && (
|
||||
<div className="bg-gray-100 rounded-xl p-6">
|
||||
<h3 className="text-xl font-bold mb-4">Изменение конфигурации сервера</h3>
|
||||
<p className="text-gray-600 mb-4">
|
||||
Вы можете увеличить или уменьшить ресурсы вашего сервера (CPU, RAM, диск).
|
||||
Изменения вступят в силу после перезапуска сервера.
|
||||
</p>
|
||||
<button
|
||||
onClick={() => setShowResizeModal(true)}
|
||||
className="bg-ospab-primary text-white px-6 py-3 rounded-full font-bold hover:bg-opacity-90"
|
||||
>
|
||||
Изменить конфигурацию
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'security' && (
|
||||
<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 select-all">{newRoot}</div>
|
||||
<div className="text-gray-500 mt-2">Скопируйте пароль — он будет показан только один раз!</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>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</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>
|
||||
)}
|
||||
|
||||
{/* Resize Modal */}
|
||||
{showResizeModal && (
|
||||
<ResizeModal
|
||||
serverId={server.id}
|
||||
onClose={() => setShowResizeModal(false)}
|
||||
onSuccess={() => {
|
||||
// Reload server data after resize
|
||||
const fetchServer = async () => {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
const res = await axios.get(`http://localhost:5000/api/server/${id}`, { headers });
|
||||
setServer(res.data);
|
||||
};
|
||||
fetchServer();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{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>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ServerPanel;
|
||||
export default ServerPanel;
|
||||
@@ -21,7 +21,7 @@ const Servers: React.FC = () => {
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
const res = await axios.get('http://localhost:5000/api/server', { headers });
|
||||
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')) {
|
||||
@@ -47,9 +47,6 @@ const Servers: React.FC = () => {
|
||||
<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>
|
||||
{servers.length === 0 && !loading && !error && (
|
||||
<a href="/tariffs" className="bg-ospab-primary text-white px-4 py-2 rounded font-bold hover:bg-ospab-primary-dark transition">Купить сервер</a>
|
||||
)}
|
||||
</div>
|
||||
{loading ? (
|
||||
<p className="text-lg text-gray-500">Загрузка...</p>
|
||||
|
||||
@@ -32,7 +32,7 @@ const TicketResponse: React.FC = () => {
|
||||
setError('');
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const res = await axios.get('http://localhost:5000/api/ticket', {
|
||||
const res = await axios.get('https://ospab.host:5000/api/ticket', {
|
||||
withCredentials: true,
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {}
|
||||
});
|
||||
@@ -52,7 +52,7 @@ const TicketResponse: React.FC = () => {
|
||||
setError('');
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
await axios.post('http://localhost:5000/api/ticket/respond', {
|
||||
await axios.post('https://ospab.host:5000/api/ticket/respond', {
|
||||
ticketId,
|
||||
message: responseMsg[ticketId]
|
||||
}, {
|
||||
@@ -74,7 +74,7 @@ const TicketResponse: React.FC = () => {
|
||||
setError('');
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
await axios.post('http://localhost:5000/api/ticket/close', { ticketId }, {
|
||||
await axios.post('https://ospab.host:5000/api/ticket/close', { ticketId }, {
|
||||
withCredentials: true,
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {}
|
||||
});
|
||||
|
||||
@@ -39,7 +39,7 @@ const TicketsPage: React.FC<TicketsPageProps> = ({ setUserData }) => {
|
||||
const fetchTickets = async () => {
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const res = await axios.get('http://localhost:5000/api/ticket', {
|
||||
const res = await axios.get('https://ospab.host:5000/api/ticket', {
|
||||
withCredentials: true,
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {}
|
||||
});
|
||||
@@ -58,7 +58,7 @@ const TicketsPage: React.FC<TicketsPageProps> = ({ setUserData }) => {
|
||||
const token = localStorage.getItem('access_token');
|
||||
if (!token) return;
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
const userRes = await axios.get('http://localhost:5000/api/auth/me', { headers });
|
||||
const userRes = await axios.get('https://ospab.host:5000/api/auth/me', { headers });
|
||||
setUserData({
|
||||
user: userRes.data.user,
|
||||
balance: userRes.data.user.balance ?? 0,
|
||||
@@ -81,7 +81,7 @@ const TicketsPage: React.FC<TicketsPageProps> = ({ setUserData }) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const token = localStorage.getItem('access_token');
|
||||
await axios.post('http://localhost:5000/api/ticket/create', { title, message }, {
|
||||
await axios.post('https://ospab.host:5000/api/ticket/create', { title, message }, {
|
||||
withCredentials: true,
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {}
|
||||
});
|
||||
@@ -99,7 +99,7 @@ const TicketsPage: React.FC<TicketsPageProps> = ({ setUserData }) => {
|
||||
|
||||
const respondTicket = async (ticketId: number) => {
|
||||
const token = localStorage.getItem('access_token');
|
||||
await axios.post('http://localhost:5000/api/ticket/respond', { ticketId, message: responseMsg }, {
|
||||
await axios.post('https://ospab.host:5000/api/ticket/respond', { ticketId, message: responseMsg }, {
|
||||
withCredentials: true,
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {}
|
||||
});
|
||||
@@ -110,7 +110,7 @@ const TicketsPage: React.FC<TicketsPageProps> = ({ setUserData }) => {
|
||||
|
||||
const closeTicket = async (ticketId: number) => {
|
||||
const token = localStorage.getItem('access_token');
|
||||
await axios.post('http://localhost:5000/api/ticket/close', { ticketId }, {
|
||||
await axios.post('https://ospab.host:5000/api/ticket/close', { ticketId }, {
|
||||
withCredentials: true,
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {}
|
||||
});
|
||||
|
||||
@@ -24,7 +24,7 @@ const LoginPage = () => {
|
||||
setError('');
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const response = await axios.post('http://localhost:5000/api/auth/login', {
|
||||
const response = await axios.post('https://ospab.host:5000/api/auth/login', {
|
||||
email: email,
|
||||
password: password,
|
||||
});
|
||||
|
||||
@@ -14,7 +14,7 @@ const RegisterPage = () => {
|
||||
setError(''); // Очищаем предыдущие ошибки
|
||||
|
||||
try {
|
||||
await axios.post('http://localhost:5000/api/auth/register', {
|
||||
await axios.post('https://ospab.host:5000/api/auth/register', {
|
||||
username: username,
|
||||
email: email,
|
||||
password: password
|
||||
|
||||
@@ -1,49 +1,47 @@
|
||||
|
||||
import { useState, useEffect, useContext } from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import axios from 'axios';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import AuthContext from '../context/authcontext';
|
||||
|
||||
const TariffsPage = () => {
|
||||
const [tariffs, setTariffs] = useState<Array<{id:number;name:string;price:number;description?:string}>>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const navigate = useNavigate();
|
||||
const { isLoggedIn } = useContext(AuthContext);
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
const fetchTariffs = async () => {
|
||||
try {
|
||||
const res = await axios.get('http://localhost:5000/api/tariff');
|
||||
console.log('Ответ API тарифов:', res.data);
|
||||
if (Array.isArray(res.data)) {
|
||||
setTariffs(res.data);
|
||||
} else {
|
||||
setError('Некорректный формат данных тарифов');
|
||||
setTariffs([]);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Ошибка загрузки тарифов:', err);
|
||||
setError('Ошибка загрузки тарифов');
|
||||
const fetchTariffs = async () => {
|
||||
try {
|
||||
const res = await axios.get('https://ospab.host:5000/api/tariff');
|
||||
console.log('Ответ API тарифов:', res.data);
|
||||
if (Array.isArray(res.data)) {
|
||||
setTariffs(res.data);
|
||||
} else {
|
||||
setError('Некорректный формат данных тарифов');
|
||||
setTariffs([]);
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
fetchTariffs();
|
||||
}, []);
|
||||
} catch (err) {
|
||||
console.error('Ошибка загрузки тарифов:', err);
|
||||
setError('Ошибка загрузки тарифов');
|
||||
setTariffs([]);
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
fetchTariffs();
|
||||
}, []);
|
||||
|
||||
const handleBuy = (tariffId: number) => {
|
||||
if (!isLoggedIn) {
|
||||
navigate('/login');
|
||||
return;
|
||||
}
|
||||
navigate(`/dashboard/checkout?tariff=${tariffId}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 py-20">
|
||||
<div className="container mx-auto px-4">
|
||||
<h1 className="text-4xl md:text-5xl font-bold text-center mb-16 text-gray-900">Тарифы</h1>
|
||||
<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">
|
||||
Выберите тариф для размещения сайта или сервера. ospab.host — надёжно и удобно!
|
||||
</p>
|
||||
{loading ? (
|
||||
<p className="text-lg text-gray-500 text-center">Загрузка...</p>
|
||||
) : error ? (
|
||||
|
||||
Reference in New Issue
Block a user