sitemap и тд
This commit is contained in:
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 {
|
||||
|
||||
Reference in New Issue
Block a user