BIG_UPDATE deleted vps, added s3 infrastructure.

This commit is contained in:
Georgiy Syralev
2025-11-23 14:35:16 +03:00
parent ae1f93a934
commit c4c2610480
173 changed files with 22684 additions and 5894 deletions

View File

@@ -1,9 +1,32 @@
import { useState, useEffect, useCallback } from 'react';
import axios from 'axios';
import { API_URL } from '../../config/api';
import { useToast } from '../../components/Toast';
import { useToast } from '../../hooks/useToast';
import { showConfirm, showPrompt } from '../../components/modalHelpers';
interface Server {
id: number;
name: string;
status: string;
vmid: number;
ipAddress: string | null;
nextPaymentDate: string | null;
tariff: {
name: string;
};
os: {
name: string;
};
}
interface Transaction {
id: number;
type: string;
amount: number;
description: string;
createdAt: string;
}
interface User {
id: number;
username: string;
@@ -18,22 +41,28 @@ interface User {
};
}
interface UserDetails extends User {
servers: Server[];
transactions: Transaction[];
}
interface Statistics {
users: { total: number };
servers: { total: number; active: number; suspended: number };
balance: { total: number };
checks: { pending: number };
tickets: { open: number };
recentTransactions: any[];
recentTransactions: Transaction[];
}
const AdminPanel = () => {
const { addToast } = useToast();
const [users, setUsers] = useState<User[]>([]);
const [statistics, setStatistics] = useState<Statistics | null>(null);
const [selectedUser, setSelectedUser] = useState<any>(null);
const [selectedUser, setSelectedUser] = useState<UserDetails | null>(null);
const [loading, setLoading] = useState(true);
const [activeTab, setActiveTab] = useState<'users' | 'stats'>('stats');
const [testingPush, setTestingPush] = useState(false);
// Модальные окна
const [showBalanceModal, setShowBalanceModal] = useState(false);
@@ -54,10 +83,13 @@ const AdminPanel = () => {
setUsers(usersRes.data.data);
setStatistics(statsRes.data.data);
} catch (error: any) {
} catch (error) {
console.error('Ошибка загрузки данных админки:', error);
if (error.response?.status === 403) {
addToast('У вас нет прав администратора', 'error');
if (error && typeof error === 'object' && 'response' in error) {
const axiosError = error as { response?: { status?: number } };
if (axiosError.response?.status === 403) {
addToast('У вас нет прав администратора', 'error');
}
}
} finally {
setLoading(false);
@@ -148,6 +180,140 @@ const AdminPanel = () => {
}
};
const handleTestPushNotification = async () => {
console.log('🧪 [FRONTEND] Начинаем тестовую отправку Push-уведомления...');
setTestingPush(true);
try {
const token = localStorage.getItem('access_token');
console.log('📝 [FRONTEND] Токен найден:', token ? 'Да' : 'Нет');
if (!token) {
addToast('Токен не найден. Пожалуйста, войдите снова.', 'error');
return;
}
// Проверяем разрешения
console.log('🔍 [FRONTEND] Проверяем разрешения на уведомления...');
console.log(' Notification.permission:', Notification.permission);
if (Notification.permission !== 'granted') {
addToast('⚠️ Уведомления не разрешены! Включите их на странице "Уведомления"', 'error');
console.log('❌ [FRONTEND] Уведомления не разрешены');
return;
}
// Проверяем Service Worker
console.log('🔍 [FRONTEND] Проверяем Service Worker...');
const registration = await navigator.serviceWorker.ready;
console.log(' ✅ Service Worker готов:', registration);
// Проверяем Push подписку
console.log('🔍 [FRONTEND] Проверяем Push подписку...');
const subscription = await registration.pushManager.getSubscription();
if (subscription) {
console.log(' ✅ Push подписка найдена:', subscription.endpoint.substring(0, 50) + '...');
} else {
console.log(' ❌ Push подписка НЕ найдена');
addToast('❌ Push подписка не найдена! Включите уведомления заново.', 'error');
return;
}
const headers = { Authorization: `Bearer ${token}` };
console.log('📤 [FRONTEND] Отправляем запрос на:', `${API_URL}/api/notifications/test-push`);
const response = await axios.post(
`${API_URL}/api/notifications/test-push`,
{},
{ headers }
);
console.log('✅ [FRONTEND] Ответ от сервера:', response.data);
if (response.data.success) {
addToast('✅ Тестовое уведомление отправлено! Ждите системное уведомление в углу экрана.', 'success');
console.log('💡 [FRONTEND] ВАЖНО: Уведомление должно появиться как СИСТЕМНОЕ уведомление');
console.log(' Windows: правый нижний угол экрана (Action Center)');
console.log(' macOS: правый верхний угол');
console.log(' Это НЕ уведомление на сайте, а уведомление браузера/ОС!');
if (response.data.data) {
console.log('📊 [FRONTEND] Детали:', {
notificationId: response.data.data.notificationId,
subscriptionsCount: response.data.data.subscriptionsCount
});
}
} else {
addToast(`${response.data.message}`, 'error');
}
} catch (error) {
console.error('❌ [FRONTEND] Ошибка отправки тестового уведомления:', error);
if (axios.isAxiosError(error)) {
console.error('📋 [FRONTEND] Детали ошибки Axios:', {
status: error.response?.status,
statusText: error.response?.statusText,
data: error.response?.data,
url: error.config?.url
});
const errorMessage = error.response?.data?.message || error.message;
addToast(`Ошибка: ${errorMessage}`, 'error');
if (error.response?.status === 403) {
console.log('⚠️ [FRONTEND] 403 Forbidden - проверьте права администратора');
} else if (error.response?.status === 400) {
console.log('⚠️ [FRONTEND] 400 Bad Request - возможно, нет активных подписок');
}
} else {
addToast('Ошибка отправки тестового уведомления', 'error');
}
} finally {
setTestingPush(false);
}
};
const handleTestLocalNotification = () => {
console.log('🔔 [FRONTEND] Тестируем локальное уведомление (без сервера)...');
if (Notification.permission !== 'granted') {
addToast('⚠️ Уведомления не разрешены!', 'error');
console.log('❌ [FRONTEND] Notification.permission:', Notification.permission);
return;
}
try {
const notification = new Notification('🔔 Локальный тест', {
body: 'Если вы видите это уведомление, значит браузер и ОС настроены правильно!',
icon: '/logo192.png',
badge: '/favicon.svg',
tag: 'local-test',
requireInteraction: false
});
console.log('✅ [FRONTEND] Локальное уведомление создано:', notification);
addToast('✅ Локальное уведомление отправлено!', 'success');
notification.onclick = () => {
console.log('🖱️ [FRONTEND] Клик по локальному уведомлению');
window.focus();
notification.close();
};
setTimeout(() => {
notification.close();
}, 5000);
} catch (error) {
console.error('❌ [FRONTEND] Ошибка локального уведомления:', error);
addToast('Ошибка создания уведомления', 'error');
}
};
if (loading) {
return (
<div className="flex justify-center items-center h-screen">
@@ -158,7 +324,40 @@ const AdminPanel = () => {
return (
<div className="container mx-auto px-4 py-8">
<h1 className="text-3xl font-bold mb-8">Админ-панель</h1>
<div className="flex justify-between items-center mb-8">
<h1 className="text-3xl font-bold">Админ-панель</h1>
{/* Кнопки тестовых уведомлений */}
<div className="flex gap-3">
<button
onClick={handleTestLocalNotification}
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2 transition-all"
title="Локальный тест (без сервера) - должно появиться сразу в углу экрана"
>
<span className="text-xl">🔔</span>
<span>Локальный тест</span>
</button>
<button
onClick={handleTestPushNotification}
disabled={testingPush}
className="px-6 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center gap-2 transition-all"
title="Push-уведомление через сервер - требует подписку"
>
{testingPush ? (
<>
<div className="animate-spin h-5 w-5 border-2 border-white border-t-transparent rounded-full"></div>
<span>Отправка...</span>
</>
) : (
<>
<span className="text-xl">🧪</span>
<span>Тест Push</span>
</>
)}
</button>
</div>
</div>
{/* Tabs */}
<div className="flex gap-4 mb-6 border-b">
@@ -229,7 +428,9 @@ const AdminPanel = () => {
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium">{user.balance.toFixed(2)} </td>
<td className="px-6 py-4 whitespace-nowrap text-sm">{user._count.servers}</td>
<td className="px-6 py-4 whitespace-nowrap text-sm">
{user.isAdmin ? '✅' : '❌'}
<span className={user.isAdmin ? 'text-green-600 font-medium' : 'text-gray-400'}>
{user.isAdmin ? 'Да' : 'Нет'}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm space-x-2">
<button
@@ -297,7 +498,7 @@ const AdminPanel = () => {
{/* Servers */}
<h3 className="text-xl font-bold mb-4">Серверы ({selectedUser.servers.length})</h3>
<div className="space-y-4 mb-6">
{selectedUser.servers.map((server: any) => (
{selectedUser.servers.map((server) => (
<div key={server.id} className="border p-4 rounded">
<div className="flex justify-between items-center">
<div>
@@ -326,7 +527,7 @@ const AdminPanel = () => {
{/* Transactions */}
<h3 className="text-xl font-bold mb-4">Последние транзакции</h3>
<div className="space-y-2">
{selectedUser.transactions?.slice(0, 10).map((tx: any) => (
{selectedUser.transactions?.slice(0, 10).map((tx) => (
<div key={tx.id} className="flex justify-between border-b pb-2">
<div>
<p className="font-medium">{tx.description}</p>

View File

@@ -1,139 +1,383 @@
// 3. Исправляем frontend/src/pages/dashboard/billing.tsx
import { useState } from 'react';
import axios from 'axios';
import { useState, useEffect } from 'react';
import apiClient from '../../utils/apiClient';
import QRCode from 'react-qr-code';
import { API_URL } from '../../config/api';
const sbpUrl = import.meta.env.VITE_SBP_QR_URL;
const cardNumber = import.meta.env.VITE_CARD_NUMBER;
interface Check {
id: number;
amount: number;
status: 'pending' | 'approved' | 'rejected';
fileUrl: string;
createdAt: string;
}
const Billing = () => {
const [amount, setAmount] = useState(0);
const [isPaymentGenerated, setIsPaymentGenerated] = useState(false);
const [copyStatus, setCopyStatus] = useState('');
const [amount, setAmount] = useState<number>(0);
const [balance, setBalance] = useState<number>(0);
const [checks, setChecks] = useState<Check[]>([]);
const [checkFile, setCheckFile] = useState<File | null>(null);
const [checkStatus, setCheckStatus] = useState('');
const [uploadLoading, setUploadLoading] = useState(false);
const [message, setMessage] = useState('');
const [messageType, setMessageType] = useState<'success' | 'error'>('success');
const [isPaymentGenerated, setIsPaymentGenerated] = useState(false);
const handleGeneratePayment = () => {
if (amount > 0) setIsPaymentGenerated(true);
const quickAmounts = [100, 500, 1000, 3000, 5000];
useEffect(() => {
fetchBalance();
fetchChecks();
}, []);
// Получить защищённый URL для файла чека
const getCheckFileUrl = (fileUrl: string): string => {
const filename = fileUrl.split('/').pop();
return `${API_URL}/api/check/file/${filename}`;
};
const fetchBalance = async () => {
try {
console.log('[Billing] Загрузка баланса...');
const res = await apiClient.get(`${API_URL}/api/user/balance`);
console.log('[Billing] Ответ от сервера:', res.data);
const balanceValue = res.data.balance || 0;
setBalance(balanceValue);
console.log('[Billing] Баланс загружен:', balanceValue);
} catch (error) {
console.error('[Billing] Ошибка загрузки баланса:', error);
}
};
const fetchChecks = async () => {
try {
console.log('[Billing] Загрузка истории чеков...');
const res = await apiClient.get(`${API_URL}/api/check/my`);
const checksData = res.data.data || [];
setChecks(checksData);
console.log('[Billing] История чеков загружена:', checksData.length, 'чеков');
} catch (error) {
console.error('[Billing] Ошибка загрузки истории чеков:', error);
}
};
const showMessage = (msg: string, type: 'success' | 'error' = 'success') => {
setMessage(msg);
setMessageType(type);
setTimeout(() => setMessage(''), 5000);
};
const handleCopyCard = () => {
if (cardNumber) {
navigator.clipboard.writeText(cardNumber);
setCopyStatus('Скопировано!');
setTimeout(() => setCopyStatus(''), 2000);
showMessage('Номер карты скопирован!', 'success');
}
};
const handleGeneratePayment = () => {
if (amount > 0) {
setIsPaymentGenerated(true);
}
};
const handleCheckUpload = async () => {
if (!checkFile || amount <= 0) return;
if (!checkFile || amount <= 0) {
console.error('[Billing] Ошибка валидации:', { checkFile: !!checkFile, amount });
showMessage('Укажите сумму и выберите файл', 'error');
return;
}
console.log('[Billing] Начало загрузки чека:', {
fileName: checkFile.name,
fileSize: checkFile.size,
amount
});
setUploadLoading(true);
try {
const token = localStorage.getItem('access_token');
const formData = new FormData();
formData.append('file', checkFile);
formData.append('amount', String(amount));
const response = await axios.post('https://ospab.host:5000/api/check/upload', formData, {
console.log('[Billing] Отправка запроса на /api/check/upload...');
const response = await apiClient.post(`${API_URL}/api/check/upload`, formData, {
headers: {
Authorization: `Bearer ${token}`,
// 'Content-Type' не указываем вручную для FormData!
'Content-Type': 'multipart/form-data',
},
withCredentials: true,
});
setCheckStatus('Чек успешно загружен! Ожидайте проверки.');
console.log('[Billing] ✅ Чек успешно загружен:', response.data);
showMessage('✅ Чек успешно отправлен! Ожидайте проверки оператором (обычно до 24 часов)', 'success');
setCheckFile(null);
console.log('Чек успешно загружен:', response.data);
setAmount(0);
setIsPaymentGenerated(false);
// Обновляем список чеков
await fetchChecks();
console.log('[Billing] История чеков обновлена');
} catch (error) {
setCheckStatus('Ошибка загрузки чека.');
console.error('Ошибка загрузки чека:', error);
const err = error as { response?: { data?: { error?: string; message?: string }; status?: number }; message?: string };
console.error('[Billing] Ошибка загрузки чека:', {
message: err.message,
response: err.response?.data,
status: err.response?.status,
});
const errorMessage = err.response?.data?.error ||
err.response?.data?.message ||
'Ошибка загрузки чека. Попробуйте снова';
showMessage(`${errorMessage}`, 'error');
}
setUploadLoading(false);
};
const getStatusText = (status: string) => {
switch (status) {
case 'approved':
return 'Зачислено';
case 'rejected':
return 'Отклонено';
default:
return 'На проверке';
}
};
const getStatusColor = (status: string) => {
switch (status) {
case 'approved':
return 'text-green-600';
case 'rejected':
return 'text-red-600';
default:
return 'text-yellow-600';
}
};
return (
<div className="p-4 lg:p-8 bg-white rounded-2xl lg:rounded-3xl shadow-xl max-w-2xl mx-auto">
<div className="p-4 lg:p-8 bg-white rounded-2xl lg:rounded-3xl shadow-xl max-w-4xl mx-auto">
<h2 className="text-2xl lg:text-3xl font-bold text-gray-800 mb-4 lg:mb-6">Пополнение баланса</h2>
{/* Только QR-код и карта, без реквизитов */}
{/* Сообщение */}
{message && (
<div className={`mb-4 p-3 border rounded-xl text-sm font-medium ${
messageType === 'success'
? 'bg-green-50 border-green-200 text-green-700'
: 'bg-red-50 border-red-200 text-red-700'
}`}>
{message}
</div>
)}
{/* Текущий баланс */}
<div className="bg-gray-100 p-4 lg:p-6 rounded-xl lg:rounded-2xl mb-6">
<p className="text-sm text-gray-600 mb-1">Текущий баланс</p>
<p className="text-3xl lg:text-4xl font-extrabold text-ospab-primary">{balance.toFixed(2)} </p>
</div>
{!isPaymentGenerated ? (
<div>
<p className="text-base lg:text-lg text-gray-500 mb-4">
Пополните свой баланс, чтобы оплачивать услуги. Минимальная сумма пополнения: 1 руб.
</p>
{/* Ввод суммы */}
<div className="mb-4">
<label htmlFor="amount" className="block text-gray-700 font-medium mb-2">Сумма ()</label>
<label htmlFor="amount" className="block text-gray-700 font-semibold mb-2">
Сумма пополнения ()
</label>
<input
type="number"
id="amount"
value={amount}
value={amount || ''}
onChange={(e) => setAmount(Number(e.target.value))}
className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-ospab-primary"
min="1"
placeholder="Введите сумму"
/>
</div>
{/* Быстрые суммы */}
<div className="mb-6">
<p className="text-sm text-gray-600 mb-2">Быстрый выбор:</p>
<div className="grid grid-cols-3 md:grid-cols-5 gap-2">
{quickAmounts.map((quickAmount) => (
<button
key={quickAmount}
onClick={() => setAmount(quickAmount)}
className={`px-3 py-2 rounded-lg text-sm font-medium transition ${
amount === quickAmount
? 'bg-ospab-primary text-white'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
}`}
>
{quickAmount}
</button>
))}
</div>
</div>
<button
onClick={handleGeneratePayment}
className="w-full px-5 py-3 rounded-full text-white font-bold transition-colors transform hover:scale-105 bg-ospab-primary hover:bg-ospab-accent"
disabled={amount <= 0}
className="w-full px-5 py-3 rounded-xl text-white font-bold transition-colors bg-ospab-primary hover:bg-ospab-accent disabled:bg-gray-300 disabled:cursor-not-allowed"
>
Сгенерировать платеж
Перейти к оплате
</button>
</div>
) : (
<div className="text-center">
<div>
<p className="text-base lg:text-lg text-gray-700 mb-4">
Для пополнения баланса переведите <strong>{amount}</strong>.
</p>
<p className="text-sm text-gray-500 mb-6">
Ваш заказ будет обработан вручную после проверки чека.
</p>
<div>
{/* Инструкция */}
<div className="bg-blue-50 border border-blue-200 rounded-xl p-4 mb-6">
<p className="font-bold text-blue-800 mb-2">Инструкция по оплате</p>
<ol className="text-sm text-blue-700 space-y-1 list-decimal list-inside">
<li>Переведите <strong>{amount}</strong> по СБП или на карту</li>
<li>Сохраните чек об оплате</li>
<li>Загрузите чек ниже для проверки</li>
</ol>
</div>
{/* QR-код для оплаты по СБП */}
<div className="bg-gray-100 p-4 lg:p-6 rounded-xl lg:rounded-2xl inline-block mb-6 w-full max-w-md mx-auto">
<h3 className="text-lg lg:text-xl font-bold text-gray-800 mb-2">Оплата по СБП</h3>
<div className="flex justify-center p-4 bg-white rounded-lg">
<QRCode value={sbpUrl || 'https://qr.nspk.ru/FAKE-QR-LINK'} size={Math.min(window.innerWidth - 100, 256)} />
{/* QR-код и карта */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
{/* QR СБП */}
<div className="bg-gray-100 p-4 rounded-xl">
<h3 className="text-lg font-bold text-gray-800 mb-3">Оплата по СБП</h3>
<div className="flex justify-center p-4 bg-white rounded-lg">
<QRCode value={sbpUrl || 'https://qr.nspk.ru/FAKE'} size={200} />
</div>
<p className="mt-3 text-xs text-gray-600 text-center">
Отсканируйте QR-код в приложении банка
</p>
</div>
{/* Номер карты */}
<div className="bg-gray-100 p-4 rounded-xl">
<h3 className="text-lg font-bold text-gray-800 mb-3">Номер карты</h3>
<p className="text-xl font-mono font-bold text-gray-800 break-all mb-3 bg-white p-4 rounded-lg">
{cardNumber || '0000 0000 0000 0000'}
</p>
<button
onClick={handleCopyCard}
className="w-full px-4 py-2 rounded-lg text-white font-semibold bg-gray-700 hover:bg-gray-800 transition"
>
Скопировать номер карты
</button>
</div>
<p className="mt-4 text-xs lg:text-sm text-gray-600">
Отсканируйте QR-код через мобильное приложение вашего банка.
</p>
</div>
{/* Номер карты с кнопкой копирования */}
<div className="bg-gray-100 p-4 lg:p-6 rounded-xl lg:rounded-2xl mb-6">
<h3 className="text-lg lg:text-xl font-bold text-gray-800 mb-2">Оплата по номеру карты</h3>
<p className="text-xl lg:text-2xl font-bold text-gray-800 select-all break-words">{cardNumber || '0000 0000 0000 0000'}</p>
<button
onClick={handleCopyCard}
className="mt-4 px-4 py-2 rounded-full text-white font-bold transition-colors transform hover:scale-105 bg-gray-500 hover:bg-gray-700 w-full lg:w-auto"
>
Скопировать номер карты
</button>
{copyStatus && <p className="mt-2 text-sm text-green-500">{copyStatus}</p>}
{/* Загрузка чека */}
<div className="bg-gray-50 border-2 border-dashed border-gray-300 rounded-xl p-6 mb-4">
<h3 className="text-lg font-bold text-gray-800 mb-3">Загрузка чека</h3>
{checkFile ? (
<div>
<p className="text-gray-700 mb-2">
<strong>Выбран файл:</strong> {checkFile.name}
</p>
<p className="text-sm text-gray-500 mb-3">
Размер: {(checkFile.size / 1024 / 1024).toFixed(2)} МБ
</p>
<div className="flex gap-2">
<button
onClick={() => setCheckFile(null)}
className="px-4 py-2 bg-gray-300 rounded-lg hover:bg-gray-400 transition"
>
Удалить
</button>
<button
onClick={handleCheckUpload}
disabled={uploadLoading}
className="flex-1 px-4 py-2 bg-ospab-primary text-white rounded-lg hover:bg-ospab-accent transition disabled:bg-gray-400"
>
{uploadLoading ? 'Загрузка...' : 'Отправить чек'}
</button>
</div>
</div>
) : (
<div className="text-center">
<p className="text-gray-600 mb-2">
<label className="text-ospab-primary cursor-pointer hover:underline font-semibold">
Нажмите, чтобы выбрать файл
<input
type="file"
accept="image/*,application/pdf"
onChange={(e) => e.target.files && setCheckFile(e.target.files[0])}
className="hidden"
/>
</label>
</p>
<p className="text-sm text-gray-500">JPG, PNG, PDF (до 10 МБ)</p>
</div>
)}
</div>
{/* Форма загрузки чека и инструкции */}
<div className="bg-blue-50 p-4 lg:p-6 rounded-xl lg:rounded-2xl border-l-4 border-blue-500 text-left mb-6">
<p className="font-bold text-blue-800 text-sm lg:text-base">Загрузите чек для проверки:</p>
<input type="file" accept="image/*,application/pdf" onChange={e => setCheckFile(e.target.files?.[0] || null)} className="mt-2 text-sm w-full" />
<button onClick={handleCheckUpload} disabled={!checkFile || uploadLoading} className="mt-2 bg-blue-500 text-white px-4 py-2 rounded w-full lg:w-auto">
{uploadLoading ? 'Загрузка...' : 'Отправить чек'}
</button>
{checkStatus && <div className="mt-2 text-green-600 text-sm">{checkStatus}</div>}
</div>
<div className="bg-red-50 p-4 lg:p-6 rounded-xl lg:rounded-2xl border-l-4 border-red-500 text-left mb-6">
<p className="font-bold text-red-800 text-sm lg:text-base">Важно:</p>
<p className="text-xs lg:text-sm text-red-700">
После оплаты сделайте скриншот или сохраните чек и загрузите его для проверки.
</p>
</div>
<p className="mt-4 text-gray-600 text-sm lg:text-base">
После подтверждения ваш баланс будет пополнен. Ожидайте проверки чека оператором.
</p>
<button
onClick={() => {
setIsPaymentGenerated(false);
setAmount(0);
}}
className="w-full px-4 py-2 bg-gray-200 text-gray-700 rounded-xl hover:bg-gray-300 transition"
>
Изменить сумму
</button>
</div>
)}
{/* История чеков */}
<div className="mt-8 pt-8 border-t border-gray-200">
<h3 className="text-xl font-bold text-gray-800 mb-4">История чеков</h3>
{checks.length > 0 ? (
<div className="space-y-3">
{checks.map((check) => (
<div
key={check.id}
className="bg-gray-50 p-4 rounded-xl flex items-center justify-between"
>
<div>
<p className="font-semibold text-gray-800">{check.amount} </p>
<p className="text-sm text-gray-500">
{new Date(check.createdAt).toLocaleString('ru-RU')}
</p>
</div>
<div className="flex items-center gap-3">
<span className={`font-semibold ${getStatusColor(check.status)}`}>
{getStatusText(check.status)}
</span>
<a
href={getCheckFileUrl(check.fileUrl)}
target="_blank"
rel="noopener noreferrer"
className="text-ospab-primary hover:underline text-sm"
onClick={(e) => {
e.preventDefault();
const token = localStorage.getItem('access_token');
const url = getCheckFileUrl(check.fileUrl);
// Открываем в новом окне с токеном в заголовке через fetch
fetch(url, {
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(res => res.blob())
.then(blob => {
const objectUrl = URL.createObjectURL(blob);
window.open(objectUrl, '_blank');
})
.catch(err => {
console.error('Ошибка загрузки чека:', err);
showMessage('Не удалось загрузить чек', 'error');
});
}}
>
Чек
</a>
</div>
</div>
))}
</div>
) : (
<p className="text-gray-500 text-center py-4">История чеков пуста</p>
)}
</div>
</div>
);
};
export default Billing;
export default Billing;

View File

@@ -0,0 +1,342 @@
import React, { useState, useEffect, useCallback } from 'react';
import axios from 'axios';
import { API_URL } from '../../config/api';
import { useToast } from '../../hooks/useToast';
import { useNavigate } from 'react-router-dom';
import { Modal } from '../../components/Modal';
interface Post {
id: number;
title: string;
content: string;
excerpt: string;
coverImage: string | null;
url: string;
status: string;
views: number;
createdAt: string;
publishedAt: string | null;
author: {
id: number;
username: string;
};
_count: {
comments: number;
};
}
interface Comment {
id: number;
content: string;
authorName: string | null;
status: string;
createdAt: string;
user: {
id: number;
username: string;
} | null;
post: {
id: number;
title: string;
};
}
const BlogAdmin: React.FC = () => {
const { addToast } = useToast();
const navigate = useNavigate();
const [posts, setPosts] = useState<Post[]>([]);
const [comments, setComments] = useState<Comment[]>([]);
const [loading, setLoading] = useState(true);
const [activeTab, setActiveTab] = useState<'posts' | 'comments'>('posts');
// Модальное окно удаления
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [postToDelete, setPostToDelete] = useState<number | null>(null);
const loadData = useCallback(async () => {
try {
setLoading(true);
const token = localStorage.getItem('access_token');
const headers = { Authorization: `Bearer ${token}` };
const [postsRes, commentsRes] = await Promise.all([
axios.get(`${API_URL}/api/blog/admin/posts`, { headers }),
axios.get(`${API_URL}/api/blog/admin/comments`, { headers })
]);
setPosts(postsRes.data.data);
setComments(commentsRes.data.data);
} catch (error) {
console.error('Ошибка загрузки данных:', error);
addToast('Не удалось загрузить данные', 'error');
} finally {
setLoading(false);
}
}, [addToast]);
useEffect(() => {
loadData();
}, [loadData]);
// Открыть редактор для нового поста
const handleNewPost = () => {
navigate('/dashboard/blogeditor');
};
// Открыть редактор для редактирования поста
const handleEditPost = (postId: number) => {
navigate(`/dashboard/blogeditor/${postId}`);
};
// Удалить пост
const handleDeletePost = async () => {
if (!postToDelete) return;
try {
const token = localStorage.getItem('access_token');
const headers = { Authorization: `Bearer ${token}` };
await axios.delete(`${API_URL}/api/blog/admin/posts/${postToDelete}`, { headers });
addToast('Пост удалён', 'success');
setShowDeleteModal(false);
setPostToDelete(null);
loadData();
} catch (error) {
console.error('Ошибка удаления поста:', error);
addToast('Не удалось удалить пост', 'error');
}
};
// Модерация комментария
const handleModerateComment = async (commentId: number, status: 'approved' | 'rejected') => {
try {
const token = localStorage.getItem('access_token');
const headers = { Authorization: `Bearer ${token}` };
await axios.patch(`${API_URL}/api/blog/admin/comments/${commentId}`, { status }, { headers });
addToast(`Комментарий ${status === 'approved' ? 'одобрен' : 'отклонён'}`, 'success');
loadData();
} catch (error) {
console.error('Ошибка модерации:', error);
addToast('Ошибка модерации комментария', 'error');
}
};
// Удалить комментарий
const handleDeleteComment = async (commentId: number) => {
try {
const token = localStorage.getItem('access_token');
const headers = { Authorization: `Bearer ${token}` };
await axios.delete(`${API_URL}/api/blog/admin/comments/${commentId}`, { headers });
addToast('Комментарий удалён', 'success');
loadData();
} catch (error) {
console.error('Ошибка удаления комментария:', error);
addToast('Не удалось удалить комментарий', 'error');
}
};
const getStatusBadge = (status: string) => {
const styles = {
draft: 'bg-gray-200 text-gray-700',
published: 'bg-green-200 text-green-700',
archived: 'bg-red-200 text-red-700',
pending: 'bg-yellow-200 text-yellow-700',
approved: 'bg-green-200 text-green-700',
rejected: 'bg-red-200 text-red-700'
};
const labels = {
draft: 'Черновик',
published: 'Опубликовано',
archived: 'Архив',
pending: 'На модерации',
approved: 'Одобрен',
rejected: 'Отклонён'
};
return (
<span className={`px-2 py-1 rounded text-xs font-semibold ${styles[status as keyof typeof styles]}`}>
{labels[status as keyof typeof labels]}
</span>
);
};
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleString('ru-RU');
};
if (loading) {
return (
<div className="flex justify-center items-center h-screen">
<div className="text-xl">Загрузка...</div>
</div>
);
}
return (
<div className="container mx-auto px-4 py-8">
<h1 className="text-4xl font-bold mb-8">Управление блогом</h1>
{/* Tabs */}
<div className="flex gap-4 mb-6 border-b">
<button
className={`px-4 py-2 ${activeTab === 'posts' ? 'border-b-2 border-blue-500 font-bold' : ''}`}
onClick={() => setActiveTab('posts')}
>
Статьи ({posts.length})
</button>
<button
className={`px-4 py-2 ${activeTab === 'comments' ? 'border-b-2 border-blue-500 font-bold' : ''}`}
onClick={() => setActiveTab('comments')}
>
Комментарии ({comments.filter(c => c.status === 'pending').length})
</button>
</div>
{/* Posts Tab */}
{activeTab === 'posts' && (
<div>
<button
onClick={handleNewPost}
className="mb-6 px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
>
Создать статью
</button>
<div className="bg-white rounded-lg shadow overflow-hidden">
<table className="min-w-full">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Заголовок</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">URL</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Статус</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Просмотры</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Комментарии</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Дата</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Действия</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{posts.map((post) => (
<tr key={post.id} className="hover:bg-gray-50">
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm font-medium text-gray-900">{post.title}</div>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
/blog/{post.url}
</td>
<td className="px-6 py-4 whitespace-nowrap">
{getStatusBadge(post.status)}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
Просмотров: {post.views}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
Комментариев: {post._count.comments}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{formatDate(post.createdAt)}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm space-x-2">
<button
onClick={() => handleEditPost(post.id)}
className="text-blue-600 hover:text-blue-800"
>
Редактировать
</button>
<button
onClick={() => {
setPostToDelete(post.id);
setShowDeleteModal(true);
}}
className="text-red-600 hover:text-red-800"
>
Удалить
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
{/* Comments Tab */}
{activeTab === 'comments' && (
<div className="space-y-4">
{comments.map((comment) => (
<div key={comment.id} className="bg-white p-6 rounded-lg shadow">
<div className="flex justify-between items-start mb-4">
<div>
<p className="text-sm text-gray-500">
К статье: <strong>{comment.post.title}</strong>
</p>
<p className="text-sm text-gray-500">
Автор: <strong>{comment.user ? comment.user.username : comment.authorName}</strong>
{' '} {formatDate(comment.createdAt)}
</p>
</div>
{getStatusBadge(comment.status)}
</div>
<p className="text-gray-700 mb-4 whitespace-pre-wrap">{comment.content}</p>
<div className="flex gap-2">
{comment.status === 'pending' && (
<>
<button
onClick={() => handleModerateComment(comment.id, 'approved')}
className="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700"
>
Одобрить
</button>
<button
onClick={() => handleModerateComment(comment.id, 'rejected')}
className="px-4 py-2 bg-yellow-600 text-white rounded hover:bg-yellow-700"
>
Отклонить
</button>
</>
)}
<button
onClick={() => handleDeleteComment(comment.id)}
className="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
>
Удалить
</button>
</div>
</div>
))}
{comments.length === 0 && (
<p className="text-center text-gray-400 py-8">Комментариев нет</p>
)}
</div>
)}
{/* Delete Confirmation Modal */}
<Modal
isOpen={showDeleteModal}
onClose={() => {
setShowDeleteModal(false);
setPostToDelete(null);
}}
title="Удаление статьи"
type="danger"
onConfirm={handleDeletePost}
confirmText="Да, удалить"
cancelText="Отмена"
>
<p>Вы уверены, что хотите удалить эту статью?</p>
<p className="mt-2 text-sm text-gray-600">
Все комментарии к статье также будут удалены. Это действие необратимо.
</p>
</Modal>
</div>
);
};
export default BlogAdmin;

View File

@@ -0,0 +1,321 @@
import React, { useState, useEffect, useCallback, useRef } from 'react';
import axios from 'axios';
import { API_URL } from '../../config/api';
import { useToast } from '../../hooks/useToast';
import { useNavigate, useParams } from 'react-router-dom';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
const BlogEditor: React.FC = () => {
const { addToast } = useToast();
const navigate = useNavigate();
const { postId } = useParams<{ postId?: string }>();
const quillRef = useRef<ReactQuill>(null);
const [loading, setLoading] = useState(false);
const [formData, setFormData] = useState({
title: '',
content: '',
excerpt: '',
coverImage: '',
url: '',
status: 'draft'
});
const loadPost = useCallback(async (id: number) => {
try {
setLoading(true);
const token = localStorage.getItem('access_token');
const headers = { Authorization: `Bearer ${token}` };
const response = await axios.get(`${API_URL}/api/blog/admin/posts/${id}`, { headers });
const post = response.data.data;
setFormData({
title: post.title,
content: post.content,
excerpt: post.excerpt || '',
coverImage: post.coverImage || '',
url: post.url,
status: post.status
});
} catch (error) {
console.error('Ошибка загрузки поста:', error);
addToast('Не удалось загрузить пост', 'error');
navigate('/dashboard/blogadmin');
} finally {
setLoading(false);
}
}, [addToast, navigate]);
// Загрузить пост для редактирования
useEffect(() => {
if (postId) {
loadPost(parseInt(postId));
}
}, [postId, loadPost]);
// Сохранить пост
const handleSavePost = async () => {
if (!formData.title || !formData.content || !formData.url) {
addToast('Заполните обязательные поля (Заголовок, URL, Содержание)', 'error');
return;
}
try {
setLoading(true);
const token = localStorage.getItem('access_token');
const headers = { Authorization: `Bearer ${token}` };
if (postId) {
// Обновление
await axios.put(`${API_URL}/api/blog/admin/posts/${postId}`, formData, { headers });
addToast('Пост обновлён', 'success');
} else {
// Создание
await axios.post(`${API_URL}/api/blog/admin/posts`, formData, { headers });
addToast('Пост создан', 'success');
}
navigate('/dashboard/blogadmin');
} catch (error) {
console.error('Ошибка сохранения поста:', error);
const message = error instanceof Error && 'response' in error
? (error as { response?: { data?: { message?: string } } }).response?.data?.message
: 'Ошибка сохранения';
addToast(message || 'Ошибка сохранения', 'error');
} finally {
setLoading(false);
}
};
// Обработчик загрузки изображений для Quill
const imageHandler = useCallback(() => {
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*');
input.click();
input.onchange = async () => {
const file = input.files?.[0];
if (!file) return;
// Проверка размера файла (макс 10MB)
if (file.size > 10 * 1024 * 1024) {
addToast('Файл слишком большой. Максимальный размер: 10MB', 'error');
return;
}
try {
const formData = new FormData();
formData.append('image', file);
const token = localStorage.getItem('access_token');
const headers = {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data'
};
const response = await axios.post(
`${API_URL}/api/blog/admin/upload-image`,
formData,
{ headers }
);
const imageUrl = response.data.data.url;
// Вставляем изображение в редактор
if (quillRef.current) {
const editor = quillRef.current.getEditor();
const range = editor.getSelection();
editor.insertEmbed(range?.index || 0, 'image', imageUrl);
}
addToast('Изображение загружено', 'success');
} catch (error) {
console.error('Ошибка загрузки изображения:', error);
addToast('Не удалось загрузить изображение', 'error');
}
};
}, [addToast]);
// Конфигурация Quill
const quillModules = {
toolbar: {
container: [
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
[{ 'font': [] }],
[{ 'size': ['small', false, 'large', 'huge'] }],
['bold', 'italic', 'underline', 'strike'],
[{ 'color': [] }, { 'background': [] }],
[{ 'list': 'ordered'}, { 'list': 'bullet' }],
[{ 'align': [] }],
['link', 'image', 'video'],
['blockquote', 'code-block'],
['clean']
],
handlers: {
image: imageHandler
}
}
};
if (loading) {
return (
<div className="flex justify-center items-center h-screen">
<div className="text-xl">Загрузка...</div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-50">
<div className="container mx-auto px-4 py-6">
{/* Header */}
<div className="bg-white rounded-lg shadow-sm p-4 mb-6 flex justify-between items-center">
<h1 className="text-2xl font-bold">
{postId ? 'Редактирование статьи' : 'Новая статья'}
</h1>
<div className="flex gap-3">
<button
onClick={() => navigate('/dashboard/blogadmin')}
className="px-6 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors"
disabled={loading}
>
Назад
</button>
<button
onClick={handleSavePost}
className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50"
disabled={loading}
>
{loading ? 'Сохранение...' : 'Сохранить'}
</button>
</div>
</div>
{/* Main Content */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Editor Area */}
<div className="lg:col-span-2 space-y-6">
{/* Title */}
<div className="bg-white rounded-lg shadow-sm p-6">
<label className="block text-sm font-medium text-gray-700 mb-2">
Заголовок статьи <span className="text-red-500">*</span>
</label>
<input
type="text"
value={formData.title}
onChange={(e) => setFormData({ ...formData, title: e.target.value })}
className="w-full px-4 py-3 text-lg border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
placeholder="Введите заголовок статьи..."
/>
</div>
{/* Content Editor */}
<div className="bg-white rounded-lg shadow-sm p-6">
<label className="block text-sm font-medium text-gray-700 mb-2">
Содержание статьи <span className="text-red-500">*</span>
</label>
<div className="border border-gray-300 rounded-lg overflow-hidden">
<ReactQuill
ref={quillRef}
theme="snow"
value={formData.content}
onChange={(value) => setFormData({ ...formData, content: value })}
modules={quillModules}
className="bg-white"
style={{ minHeight: '500px' }}
/>
</div>
<p className="text-xs text-gray-500 mt-2">
Используйте кнопку изображения для загрузки картинок в статью
</p>
</div>
</div>
{/* Sidebar - Settings */}
<div className="space-y-6">
{/* URL */}
<div className="bg-white rounded-lg shadow-sm p-6">
<label className="block text-sm font-medium text-gray-700 mb-2">
URL статьи <span className="text-red-500">*</span>
</label>
<div className="flex items-center mb-2">
<span className="text-gray-500 text-sm mr-2">/blog/</span>
<input
type="text"
value={formData.url}
onChange={(e) => setFormData({ ...formData, url: e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, '-') })}
className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
placeholder="my-awesome-post"
/>
</div>
<p className="text-xs text-gray-500">
Используйте латиницу, цифры и дефисы
</p>
</div>
{/* Status */}
<div className="bg-white rounded-lg shadow-sm p-6">
<label className="block text-sm font-medium text-gray-700 mb-2">
Статус публикации
</label>
<select
value={formData.status}
onChange={(e) => setFormData({ ...formData, status: e.target.value })}
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
>
<option value="draft">Черновик</option>
<option value="published">Опубликовано</option>
<option value="archived">📦 Архив</option>
</select>
</div>
{/* Excerpt */}
<div className="bg-white rounded-lg shadow-sm p-6">
<label className="block text-sm font-medium text-gray-700 mb-2">
Краткое описание
</label>
<textarea
value={formData.excerpt}
onChange={(e) => setFormData({ ...formData, excerpt: e.target.value })}
rows={4}
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
placeholder="Краткое описание для отображения в ленте блога..."
/>
</div>
{/* Cover Image */}
<div className="bg-white rounded-lg shadow-sm p-6">
<label className="block text-sm font-medium text-gray-700 mb-2">
Обложка статьи
</label>
<input
type="text"
value={formData.coverImage}
onChange={(e) => setFormData({ ...formData, coverImage: e.target.value })}
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
placeholder="https://example.com/image.jpg"
/>
{formData.coverImage && (
<div className="mt-3">
<img
src={formData.coverImage}
alt="Preview"
className="w-full h-32 object-cover rounded-lg"
onError={(e) => {
e.currentTarget.src = 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="100" height="100"%3E%3Crect fill="%23ddd" width="100" height="100"/%3E%3Ctext x="50%25" y="50%25" text-anchor="middle" dy=".3em" fill="%23999"%3EНе загружено%3C/text%3E%3C/svg%3E';
}}
/>
</div>
)}
</div>
</div>
</div>
</div>
</div>
);
};
export default BlogEditor;

View File

@@ -1,148 +1,317 @@
import React, { useState, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import axios from 'axios';
interface Tariff {
id: number;
name: string;
price: number;
description?: string;
}
interface OperatingSystem {
id: number;
name: string;
type: string;
template?: string;
}
import React, { useCallback, useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { FiAlertCircle, FiArrowLeft, FiDatabase, FiDollarSign, FiInfo, FiShoppingCart } from 'react-icons/fi';
import apiClient from '../../utils/apiClient';
import { API_URL } from '../../config/api';
import { DEFAULT_STORAGE_PLAN_ID, STORAGE_PLAN_IDS, STORAGE_PLAN_MAP, type StoragePlanId } from '../../constants/storagePlans';
// Упрощённый Checkout только для S3 Bucket
interface CheckoutProps {
onSuccess: () => void;
onSuccess?: () => void;
}
const Checkout: React.FC<CheckoutProps> = ({ onSuccess }) => {
const [tariffs, setTariffs] = useState<Tariff[]>([]);
const [oses, setOses] = useState<OperatingSystem[]>([]);
const [selectedTariff, setSelectedTariff] = useState<number | null>(null);
const [selectedOs, setSelectedOs] = useState<number | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const location = useLocation();
const navigate = useNavigate();
const [planName, setPlanName] = useState<StoragePlanId>(DEFAULT_STORAGE_PLAN_ID);
const [planPrice, setPlanPrice] = useState<number>(STORAGE_PLAN_MAP[DEFAULT_STORAGE_PLAN_ID].price);
const [balance, setBalance] = useState<number>(0);
const [bucketName, setBucketName] = useState<string>('');
const [region, setRegion] = useState<string>('ru-central-1');
const [storageClass, setStorageClass] = useState<string>('standard');
const [isPublic, setIsPublic] = useState<boolean>(false);
const [versioning, setVersioning] = useState<boolean>(false);
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<string>('');
// Загружаем параметры из query (?plan=basic&price=199)
const fetchBalance = useCallback(async () => {
try {
const res = await apiClient.get(`${API_URL}/api/user/balance`);
setBalance(res.data.balance || 0);
} catch (e) {
console.error('Ошибка загрузки баланса', e);
}
}, []);
useEffect(() => {
// Загрузка тарифов и ОС
const fetchData = async () => {
try {
const token = localStorage.getItem('access_token');
const headers = token ? { Authorization: `Bearer ${token}` } : {};
const [tariffRes, osRes] = await Promise.all([
axios.get(`${process.env.VITE_API_URL || 'https://ospab.host:5000'}/api/tariff`, { headers }),
axios.get(`${process.env.VITE_API_URL || 'https://ospab.host:5000'}/api/os`, { headers }),
]);
setTariffs(tariffRes.data);
setOses(osRes.data);
// Автовыбор тарифа из query
const params = new URLSearchParams(location.search);
const tariffId = params.get('tariff');
if (tariffId) {
setSelectedTariff(Number(tariffId));
}
} catch {
setError('Ошибка загрузки тарифов или ОС');
}
};
fetchData();
}, [location.search]);
const params = new URLSearchParams(location.search);
const rawPlan = params.get('plan');
const match = rawPlan ? rawPlan.toLowerCase() : '';
const planId = STORAGE_PLAN_IDS.includes(match as StoragePlanId)
? (match as StoragePlanId)
: DEFAULT_STORAGE_PLAN_ID;
setPlanName(planId);
const handleBuy = async () => {
if (!selectedTariff || !selectedOs) {
setError('Выберите тариф и ОС');
const priceParam = params.get('price');
if (priceParam) {
const numeric = Number(priceParam);
setPlanPrice(Number.isFinite(numeric) && numeric > 0 ? numeric : STORAGE_PLAN_MAP[planId].price);
} else {
setPlanPrice(STORAGE_PLAN_MAP[planId].price);
}
fetchBalance();
}, [location.search, fetchBalance]);
const meta = STORAGE_PLAN_MAP[planName];
const canCreate = () => {
if (!planPrice || !bucketName.trim() || !meta) return false;
if (balance < planPrice) return false;
// Простая валидация имени (можно расширить): маленькие буквы, цифры, тире
return /^[a-z0-9-]{3,40}$/.test(bucketName.trim());
};
const handleCreate = async () => {
if (!canCreate()) {
setError('Проверьте корректность данных и баланс');
return;
}
setLoading(true);
setError('');
try {
const token = localStorage.getItem('access_token') || localStorage.getItem('token');
console.log('Покупка сервера:', { tariffId: selectedTariff, osId: selectedOs });
const res = await axios.post(`${process.env.VITE_API_URL || 'https://ospab.host:5000'}/api/server/create`, {
tariffId: selectedTariff,
osId: selectedOs,
}, {
headers: token ? { Authorization: `Bearer ${token}` } : {},
withCredentials: true,
// POST на будущий endpoint S3
const res = await apiClient.post(`${API_URL}/api/storage/buckets`, {
name: bucketName.trim(),
plan: planName,
quotaGb: meta?.quotaGb || 0,
region,
storageClass,
public: isPublic,
versioning
});
if (res.data && res.data.error === 'Недостаточно средств на балансе') {
setError('Недостаточно средств на балансе. Пополните баланс и попробуйте снова.');
setLoading(false);
return;
}
// После успешной покупки обновляем userData
try {
const userRes = await axios.get(`${process.env.VITE_API_URL || 'https://ospab.host:5000'}/api/auth/me`, { headers: token ? { Authorization: `Bearer ${token}` } : {} });
window.dispatchEvent(new CustomEvent('userDataUpdate', {
detail: {
user: userRes.data.user,
balance: userRes.data.user.balance ?? 0,
servers: userRes.data.user.servers ?? [],
tickets: userRes.data.user.tickets ?? [],
}
}));
} catch (err) {
console.error('Ошибка обновления userData после покупки:', err);
}
onSuccess();
} catch (err) {
if (axios.isAxiosError(err) && err.response?.data?.error === 'Недостаточно средств на балансе') {
setError('Недостаточно средств на балансе. Пополните баланс и попробуйте снова.');
if (res.data?.error) {
setError(res.data.error);
} else {
setError('Ошибка покупки сервера');
// Обновляем пользовательские данные и баланс (если списание произошло на сервере)
try {
const userRes = await apiClient.get(`${API_URL}/api/auth/me`);
window.dispatchEvent(new CustomEvent('userDataUpdate', {
detail: { user: userRes.data.user }
}));
} catch (e) {
console.error('Ошибка обновления userData', e);
}
if (onSuccess) onSuccess();
navigate('/dashboard/storage');
}
console.error('Ошибка покупки сервера:', err);
} catch (e: unknown) {
let message = 'Ошибка создания бакета';
if (e && typeof e === 'object' && 'response' in e) {
const resp = (e as { response?: { data?: { message?: string } } }).response;
if (resp?.data?.message) message = resp.data.message;
}
setError(message);
console.error(e);
} finally {
setLoading(false);
}
setLoading(false);
};
return (
<div className="p-8 bg-white rounded-3xl shadow-xl max-w-xl mx-auto">
<h2 className="text-2xl font-bold mb-4">Покупка сервера</h2>
{error && <p className="text-red-500 mb-2">{error}</p>}
<div className="mb-4">
<label className="block font-semibold mb-2">Тариф:</label>
<select
className="w-full border rounded px-3 py-2"
value={selectedTariff ?? ''}
onChange={e => setSelectedTariff(Number(e.target.value))}
<div className="max-w-5xl mx-auto">
{/* Header */}
<div className="mb-6">
<button
onClick={() => navigate('/dashboard/storage')}
className="flex items-center gap-2 px-4 py-2 text-ospab-primary hover:bg-ospab-primary/5 rounded-lg transition-colors mb-4"
>
<option value="">Выберите тариф</option>
{tariffs.map(t => (
<option key={t.id} value={t.id}>
{t.name} {t.price}
</option>
))}
</select>
<FiArrowLeft />
<span>Назад к хранилищу</span>
</button>
<h1 className="text-3xl font-bold text-gray-800 flex items-center gap-2">
<FiDatabase className="text-ospab-primary" /> Создание S3 Bucket
</h1>
<p className="text-gray-600 mt-1">План: {meta?.title}{planPrice ? ` • ₽${planPrice}/мес` : ''}</p>
</div>
<div className="mb-4">
<label className="block font-semibold mb-2">Операционная система:</label>
<select
className="w-full border rounded px-3 py-2"
value={selectedOs ?? ''}
onChange={e => setSelectedOs(Number(e.target.value))}
>
<option value="">Выберите ОС</option>
{oses.map(os => (
<option key={os.id} value={os.id}>
{os.name} ({os.type})
</option>
))}
</select>
{error && (
<div className="bg-red-50 border border-red-200 rounded-xl p-4 mb-6 flex items-start gap-3">
<FiAlertCircle className="text-red-500 text-xl flex-shrink-0 mt-0.5" />
<div>
<p className="text-red-700 font-semibold">Ошибка</p>
<p className="text-red-600 text-sm">{error}</p>
</div>
</div>
)}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Left */}
<div className="lg:col-span-2 space-y-6">
{/* Bucket settings */}
<div className="bg-white rounded-xl shadow-md p-6">
<h2 className="text-xl font-bold text-gray-800 mb-4">Параметры бакета</h2>
<div className="space-y-5">
<div>
<label className="block text-sm font-semibold text-gray-700 mb-2">Имя бакета</label>
<input
type="text"
value={bucketName}
onChange={(e) => setBucketName(e.target.value)}
placeholder="например: media-assets"
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-ospab-primary focus:border-transparent transition-all"
/>
<p className="text-xs text-gray-500 mt-1">Допустимы: a-z 0-9 - (340 символов)</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-semibold text-gray-700 mb-2">Регион</label>
<select
value={region}
onChange={(e) => setRegion(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-ospab-primary focus:border-transparent"
>
<option value="ru-central-1">ru-central-1</option>
<option value="eu-east-1">eu-east-1</option>
<option value="eu-west-1">eu-west-1</option>
</select>
</div>
<div>
<label className="block text-sm font-semibold text-gray-700 mb-2">Класс хранения</label>
<select
value={storageClass}
onChange={(e) => setStorageClass(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-ospab-primary focus:border-transparent"
>
<option value="standard">Standard</option>
<option value="infrequent">Infrequent</option>
<option value="archive">Archive</option>
</select>
</div>
</div>
<div className="flex items-center gap-4">
<label className="flex items-center gap-2 cursor-pointer select-none">
<input
type="checkbox"
checked={isPublic}
onChange={(e) => setIsPublic(e.target.checked)}
className="rounded"
/>
<span className="text-sm text-gray-700">Публичный доступ</span>
</label>
<label className="flex items-center gap-2 cursor-pointer select-none">
<input
type="checkbox"
checked={versioning}
onChange={(e) => setVersioning(e.target.checked)}
className="rounded"
/>
<span className="text-sm text-gray-700">Версионирование</span>
</label>
</div>
</div>
</div>
{/* Plan info */}
<div className="bg-white rounded-xl shadow-md p-6">
<div className="flex items-center gap-2 mb-4">
<FiInfo className="text-ospab-primary text-xl" />
<h2 className="text-xl font-bold text-gray-800">Информация о плане</h2>
</div>
{meta ? (
<div className="space-y-3">
<p className="text-gray-700 text-sm">Включённый объём: <span className="font-semibold">{meta.quotaGb} GB</span></p>
<ul className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm text-gray-600">
{meta.included.slice(0, 4).map((d) => (
<li key={d} className="flex items-center gap-2">
<span className="w-1.5 h-1.5 bg-ospab-primary rounded-full"></span>{d}
</li>
))}
</ul>
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 text-sm text-gray-700">
Оплата списывается помесячно при создании бакета. Использование сверх квоты будет тарифицироваться позже.
</div>
</div>
) : (
<p className="text-gray-500 text-sm">Параметры плана не найдены. Вернитесь на страницу тарифов.</p>
)}
</div>
</div>
{/* Right */}
<div className="lg:col-span-1">
<div className="bg-white rounded-xl shadow-md p-6 sticky top-4">
<div className="flex items-center gap-2 mb-6">
<FiShoppingCart className="text-ospab-primary text-xl" />
<h2 className="text-xl font-bold text-gray-800">Итого</h2>
</div>
<div className="bg-gradient-to-br from-ospab-primary to-ospab-accent rounded-lg p-4 mb-6 text-white">
<div className="flex items-center gap-2 mb-2">
<FiDollarSign className="text-lg" />
<p className="text-white/80 text-sm">Баланс</p>
</div>
<p className="text-2xl font-bold mb-3">{balance.toFixed(2)}</p>
<button
onClick={() => navigate('/dashboard/billing')}
className="w-full bg-white/20 hover:bg-white/30 px-4 py-2 rounded-lg transition-colors text-sm font-semibold"
>Пополнить баланс</button>
</div>
<div className="space-y-4 mb-6">
<div>
<p className="text-sm text-gray-500 mb-1">План</p>
{meta ? (
<div className="bg-gray-50 rounded-lg p-3">
<p className="font-semibold text-gray-800 mb-1">{meta.title}</p>
<p className="text-sm text-gray-600">{planPrice}/мес</p>
</div>
) : (
<p className="text-gray-400 text-sm">Не выбран</p>
)}
</div>
<div>
<p className="text-sm text-gray-500 mb-1">Имя бакета</p>
{bucketName ? (
<div className="bg-gray-50 rounded-lg p-3">
<p className="font-semibold text-gray-800">{bucketName}</p>
</div>
) : (
<p className="text-gray-400 text-sm">Не указано</p>
)}
</div>
{planName && (
<div className="pt-4 border-t border-gray-200">
<div className="space-y-2 mb-3 text-sm">
<div className="flex justify-between">
<span className="text-gray-600">Стоимость:</span>
<span className="font-semibold">{planPrice}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-600">Баланс:</span>
<span className="font-semibold">{balance.toFixed(2)}</span>
</div>
</div>
<div className="flex justify-between pt-3 border-t border-gray-200">
<span className="text-gray-800 font-semibold">Остаток:</span>
<span className={`font-bold text-lg ${balance - planPrice >= 0 ? 'text-green-600' : 'text-red-600'}`}>{(balance - planPrice).toFixed(2)}</span>
</div>
</div>
)}
</div>
<button
onClick={handleCreate}
disabled={!canCreate() || loading}
className={`w-full py-3 rounded-lg font-bold flex items-center justify-center gap-2 transition-colors ${
!canCreate() || loading ? 'bg-gray-300 text-gray-500 cursor-not-allowed' : 'bg-ospab-primary text-white hover:bg-ospab-primary/90 shadow-lg hover:shadow-xl'
}`}
>
{loading ? (<><div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div><span>Создание...</span></>) : (<><FiShoppingCart /><span>Создать бакет</span></>)}
</button>
{!canCreate() && (
<p className="text-xs text-gray-500 text-center mt-3">Заполните имя бакета, выберите план и убедитесь в достаточном балансе</p>
)}
</div>
</div>
</div>
<button
className="bg-ospab-primary text-white px-6 py-2 rounded font-bold w-full"
onClick={handleBuy}
disabled={loading}
>
{loading ? 'Покупка...' : 'Купить сервер'}
</button>
</div>
);
};

View File

@@ -1,6 +1,6 @@
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import apiClient from '../../utils/apiClient';
import { API_URL } from '../../config/api';
interface IUser {
@@ -25,18 +25,48 @@ const CheckVerification: React.FC = () => {
const [actionLoading, setActionLoading] = useState<number | null>(null);
const [error, setError] = useState<string>('');
// Получить защищённый URL для файла чека
const getCheckFileUrl = (fileUrl: string): string => {
const filename = fileUrl.split('/').pop();
return `${API_URL}/api/check/file/${filename}`;
};
// Открыть изображение чека в новом окне с авторизацией
const openCheckImage = async (fileUrl: string) => {
try {
const token = localStorage.getItem('access_token');
const url = getCheckFileUrl(fileUrl);
const response = await fetch(url, {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (!response.ok) {
throw new Error('Ошибка загрузки изображения');
}
const blob = await response.blob();
const objectUrl = URL.createObjectURL(blob);
window.open(objectUrl, '_blank');
} catch (error) {
console.error('[CheckVerification] Ошибка загрузки изображения:', error);
alert('Не удалось загрузить изображение чека');
}
};
useEffect(() => {
const fetchChecks = async (): Promise<void> => {
console.log('[CheckVerification] Загрузка чеков для проверки...');
setLoading(true);
setError('');
try {
const token = localStorage.getItem('access_token');
const res = await axios.get<ICheck[]>(`${API_URL}/api/check`, {
headers: { Authorization: `Bearer ${token}` },
withCredentials: true,
});
const res = await apiClient.get<ICheck[]>(`${API_URL}/api/check`);
setChecks(res.data);
} catch {
console.log('[CheckVerification] Загружено чеков:', res.data.length);
} catch (err) {
console.error('[CheckVerification] Ошибка загрузки чеков:', err);
setError('Ошибка загрузки чеков');
setChecks([]);
}
@@ -46,35 +76,41 @@ const CheckVerification: React.FC = () => {
}, []);
const handleAction = async (checkId: number, action: 'approve' | 'reject'): Promise<void> => {
console.log(`[CheckVerification] ${action === 'approve' ? 'Подтверждение' : 'Отклонение'} чека #${checkId}`);
setActionLoading(checkId);
setError('');
try {
const token = localStorage.getItem('access_token');
await axios.post(`${API_URL}/api/check/${action}`, { checkId }, {
headers: { Authorization: `Bearer ${token}` },
withCredentials: true,
});
setChecks((prevChecks: ICheck[]) => prevChecks.map((c: ICheck) => c.id === checkId ? { ...c, status: action === 'approve' ? 'approved' : 'rejected' } : c));
await apiClient.post(`${API_URL}/api/check/${action}`, { checkId });
console.log(`[CheckVerification] Чек #${checkId} ${action === 'approve' ? 'подтверждён' : 'отклонён'}`);
setChecks((prevChecks: ICheck[]) =>
prevChecks.map((c: ICheck) =>
c.id === checkId ? { ...c, status: action === 'approve' ? 'approved' : 'rejected' } : c
)
);
// Если подтверждение — обновить баланс пользователя
if (action === 'approve') {
try {
const token = localStorage.getItem('access_token');
const headers = { Authorization: `Bearer ${token}` };
const userRes = await axios.get(`${API_URL}/api/auth/me`, { headers });
console.log('[CheckVerification] Обновление данных пользователя...');
const userRes = await apiClient.get(`${API_URL}/api/auth/me`);
// Глобально обновить userData через типизированное событие (для Dashboard)
window.dispatchEvent(new CustomEvent<import('./types').UserData>('userDataUpdate', {
detail: {
user: userRes.data.user,
balance: userRes.data.user.balance ?? 0,
servers: userRes.data.user.servers ?? [],
tickets: userRes.data.user.tickets ?? [],
}
}));
console.log('[CheckVerification] Данные пользователя обновлены');
} catch (error) {
console.error('Ошибка обновления userData:', error);
console.error('[CheckVerification] Ошибка обновления userData:', error);
}
}
} catch {
} catch (err) {
console.error(`[CheckVerification] Ошибка ${action === 'approve' ? 'подтверждения' : 'отклонения'}:`, err);
setError('Ошибка действия');
}
setActionLoading(null);
@@ -108,9 +144,16 @@ const CheckVerification: React.FC = () => {
</div>
</div>
<div className="flex flex-col items-center gap-2 md:ml-8">
<a href={`${API_URL}${check.fileUrl}`} target="_blank" rel="noopener noreferrer" className="block mb-2">
<img src={`${API_URL}${check.fileUrl}`} alt="Чек" className="w-32 h-32 object-contain rounded-xl border" />
</a>
<button
onClick={() => openCheckImage(check.fileUrl)}
className="block mb-2 cursor-pointer hover:opacity-80 transition-opacity"
>
<div className="w-32 h-32 flex items-center justify-center bg-gray-200 rounded-xl border">
<span className="text-gray-600 text-sm text-center px-2">
Нажмите для просмотра чека
</span>
</div>
</button>
{check.status === 'pending' && (
<>
<button

View File

@@ -1,31 +1,34 @@
// frontend/src/pages/dashboard/mainpage.tsx
import { useState, useEffect } from 'react';
import { useState, useEffect, useContext } from 'react';
import { Routes, Route, Link, useNavigate, useLocation } from 'react-router-dom';
import axios from 'axios';
import { isAxiosError } from 'axios';
import apiClient from '../../utils/apiClient';
import AuthContext from '../../context/authcontext';
import { useContext } from 'react';
// Импортируем компоненты для вкладок
import Summary from './summary';
import Servers from './servers';
import ServerPanel from './serverpanel';
import TicketsPage from './tickets';
import Billing from './billing';
import Settings from './settings';
import Notifications from './notificatons';
import NotificationsPage from './notifications';
import CheckVerification from './checkverification';
import TicketResponse from './ticketresponse';
import Checkout from './checkout';
import TariffsPage from '../tariffs';
import StoragePage from './storage';
import AdminPanel from './admin';
import BlogAdmin from './blogadmin';
import BlogEditor from './blogeditor';
// Новые компоненты для тикетов
import TicketDetailPage from './tickets/detail';
import NewTicketPage from './tickets/new';
const Dashboard = () => {
const [userData, setUserData] = useState<import('./types').UserData | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState<boolean>(false);
const navigate = useNavigate();
const location = useLocation();
const { logout } = useContext(AuthContext);
const { userData, setUserData, logout, refreshUser, isInitialized } = useContext(AuthContext);
const [activeTab, setActiveTab] = useState('summary');
@@ -46,17 +49,10 @@ const Dashboard = () => {
navigate('/login');
return;
}
const headers = { Authorization: `Bearer ${token}` };
const userRes = await axios.get('https://ospab.host:5000/api/auth/me', { headers });
setUserData({
user: userRes.data.user,
balance: userRes.data.user.balance ?? 0,
servers: userRes.data.user.servers ?? [],
tickets: userRes.data.user.tickets ?? [],
});
await refreshUser();
} catch (err) {
console.error('Ошибка загрузки данных:', err);
if (axios.isAxiosError(err) && err.response?.status === 401) {
if (isAxiosError(err) && err.response?.status === 401) {
logout();
navigate('/login');
}
@@ -72,12 +68,10 @@ const Dashboard = () => {
try {
const token = localStorage.getItem('access_token');
if (!token) return;
const headers = { Authorization: `Bearer ${token}` };
const userRes = await axios.get('https://ospab.host:5000/api/auth/me', { headers });
const userRes = await apiClient.get('/api/auth/me');
setUserData({
user: userRes.data.user,
balance: userRes.data.user.balance ?? 0,
servers: userRes.data.user.servers ?? [],
tickets: userRes.data.user.tickets ?? [],
});
} catch (err) {
@@ -102,7 +96,7 @@ const Dashboard = () => {
const isOperator = userData?.user?.operator === 1;
const isAdmin = userData?.user?.isAdmin === true;
if (loading) {
if (!isInitialized || loading) {
return (
<div className="flex min-h-screen items-center justify-center">
<span className="text-gray-500 text-lg">Загрузка...</span>
@@ -113,7 +107,7 @@ const Dashboard = () => {
// Вкладки для сайдбара
const tabs = [
{ key: 'summary', label: 'Сводка', to: '/dashboard' },
{ key: 'servers', label: 'Серверы', to: '/dashboard/servers' },
{ key: 'storage', label: 'Хранилище', to: '/dashboard/storage' },
{ key: 'tickets', label: 'Тикеты', to: '/dashboard/tickets' },
{ key: 'billing', label: 'Баланс', to: '/dashboard/billing' },
{ key: 'settings', label: 'Настройки', to: '/dashboard/settings' },
@@ -125,7 +119,8 @@ const Dashboard = () => {
];
const superAdminTabs = [
{ key: 'admin', label: '👑 Админ-панель', to: '/dashboard/admin' },
{ key: 'admin', label: 'Админ-панель', to: '/dashboard/admin' },
{ key: 'blogadmin', label: 'Блог', to: '/dashboard/blogadmin' },
];
return (
@@ -163,7 +158,7 @@ const Dashboard = () => {
)}
{isAdmin && (
<span className="inline-block px-2 py-1 bg-red-100 text-red-800 text-xs font-semibold rounded-full">
👑 Супер Админ
Супер Админ
</span>
)}
</div>
@@ -260,19 +255,21 @@ const Dashboard = () => {
</div>
<div className="flex-1 p-4 lg:p-8 pt-6 lg:pt-12 overflow-x-hidden">
<Routes>
<Route path="/" element={<Summary userData={userData ?? { user: { username: '', operator: 0 }, balance: 0, servers: [], tickets: [] }} />} />
<Route path="servers" element={<Servers />} />
<Route path="server/:id" element={<ServerPanel />} />
<Route path="checkout" element={<Checkout onSuccess={() => navigate('/dashboard')} />} />
<Route path="tariffs" element={<TariffsPage />} />
<Route path="/" element={<Summary userData={userData ?? { user: { username: '', operator: 0 }, balance: 0, tickets: [] }} />} />
<Route path="storage" element={<StoragePage />} />
<Route path="checkout" element={<Checkout onSuccess={() => navigate('/dashboard/storage')} />} />
{userData && (
<Route path="tickets" element={<TicketsPage setUserData={setUserData} />} />
<>
<Route path="tickets" element={<TicketsPage setUserData={setUserData} />} />
<Route path="tickets/:id" element={<TicketDetailPage />} />
<Route path="tickets/new" element={<NewTicketPage />} />
</>
)}
{userData && (
<Route path="billing" element={<Billing />} />
)}
<Route path="settings" element={<Settings />} />
<Route path="notifications" element={<Notifications />} />
<Route path="notifications" element={<NotificationsPage />} />
{isOperator && (
<>
<Route path="checkverification" element={<CheckVerification />} />
@@ -280,7 +277,12 @@ const Dashboard = () => {
</>
)}
{isAdmin && (
<Route path="admin" element={<AdminPanel />} />
<>
<Route path="admin" element={<AdminPanel />} />
<Route path="blogadmin" element={<BlogAdmin />} />
<Route path="blogeditor" element={<BlogEditor />} />
<Route path="blogeditor/:postId" element={<BlogEditor />} />
</>
)}
</Routes>
</div>

View File

@@ -0,0 +1,364 @@
import { useState, useEffect, useCallback } from 'react';
import { Link } from 'react-router-dom';
import {
getNotifications,
markAsRead,
markAllAsRead,
deleteNotification,
deleteAllRead,
requestPushPermission,
type Notification
} from '../../services/notificationService';
const NotificationsPage = () => {
const [notifications, setNotifications] = useState<Notification[]>([]);
const [loading, setLoading] = useState(true);
const [filter, setFilter] = useState<'all' | 'unread'>('all');
const [pushEnabled, setPushEnabled] = useState(false);
const [pushPermission, setPushPermission] = useState<NotificationPermission>('default');
const checkPushPermission = () => {
if ('Notification' in window) {
const permission = Notification.permission;
setPushPermission(permission);
setPushEnabled(permission === 'granted');
}
};
const loadNotifications = useCallback(async () => {
setLoading(true);
try {
const response = await getNotifications({
page: 1,
limit: 50,
unreadOnly: filter === 'unread'
});
// Проверяем, что response имеет правильную структуру
if (response && Array.isArray(response.notifications)) {
setNotifications(response.notifications);
} else {
console.error('Неверный формат ответа от сервера:', response);
setNotifications([]);
}
} catch (error) {
console.error('Ошибка загрузки уведомлений:', error);
setNotifications([]);
} finally {
setLoading(false);
}
}, [filter]);
useEffect(() => {
loadNotifications();
checkPushPermission();
}, [loadNotifications]);
const handleMarkAsRead = async (id: number) => {
try {
await markAsRead(id);
setNotifications((prev) =>
prev.map((n) => (n.id === id ? { ...n, isRead: true } : n))
);
} catch (error) {
console.error('Ошибка пометки прочитанным:', error);
}
};
const handleMarkAllAsRead = async () => {
try {
await markAllAsRead();
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
} catch (error) {
console.error('Ошибка пометки всех прочитанными:', error);
}
};
const handleDelete = async (id: number) => {
try {
await deleteNotification(id);
setNotifications((prev) => prev.filter((n) => n.id !== id));
} catch (error) {
console.error('Ошибка удаления уведомления:', error);
}
};
const handleDeleteAllRead = async () => {
if (!window.confirm('Удалить все прочитанные уведомления?')) return;
try {
await deleteAllRead();
setNotifications((prev) => prev.filter((n) => !n.isRead));
} catch (error) {
console.error('Ошибка удаления прочитанных:', error);
}
};
const handleEnablePush = async () => {
const success = await requestPushPermission();
if (success) {
setPushEnabled(true);
setPushPermission('granted');
alert('Push-уведомления успешно подключены!');
} else {
alert('Не удалось подключить Push-уведомления. Проверьте разрешения браузера.');
// Обновляем состояние на случай, если пользователь отклонил
checkPushPermission();
}
};
const formatDate = (dateString: string) => {
const date = new Date(dateString);
return date.toLocaleString('ru-RU', {
day: 'numeric',
month: 'long',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
};
const groupNotificationsByDate = (notifications: Notification[]) => {
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
const weekAgo = new Date(today);
weekAgo.setDate(weekAgo.getDate() - 7);
const groups: Record<string, Notification[]> = {
'Сегодня': [],
'Вчера': [],
'За последние 7 дней': [],
'Ранее': []
};
notifications.forEach((notification) => {
const notifDate = new Date(notification.createdAt);
const notifDay = new Date(notifDate.getFullYear(), notifDate.getMonth(), notifDate.getDate());
if (notifDay.getTime() === today.getTime()) {
groups['Сегодня'].push(notification);
} else if (notifDay.getTime() === yesterday.getTime()) {
groups['Вчера'].push(notification);
} else if (notifDate >= weekAgo) {
groups['За последние 7 дней'].push(notification);
} else {
groups['Ранее'].push(notification);
}
});
return groups;
};
const unreadCount = notifications.filter((n) => !n.isRead).length;
const groupedNotifications = groupNotificationsByDate(notifications);
return (
<div className="p-4 lg:p-8">
<div className="max-w-4xl mx-auto">
<h1 className="text-3xl font-bold text-gray-900 mb-6">Уведомления</h1>
{/* Панель действий */}
<div className="bg-white rounded-lg shadow-sm p-4 mb-6">
<div className="flex flex-wrap items-center justify-between gap-4">
{/* Фильтры */}
<div className="flex gap-2">
<button
onClick={() => setFilter('all')}
className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
filter === 'all'
? 'bg-ospab-primary text-white'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
}`}
>
Все ({notifications.length})
</button>
<button
onClick={() => setFilter('unread')}
className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
filter === 'unread'
? 'bg-ospab-primary text-white'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
}`}
>
Непрочитанные ({unreadCount})
</button>
</div>
{/* Действия */}
<div className="flex gap-2">
{unreadCount > 0 && (
<button
onClick={handleMarkAllAsRead}
className="px-4 py-2 rounded-md text-sm font-medium bg-blue-100 text-blue-700 hover:bg-blue-200 transition-colors"
>
Прочитать все
</button>
)}
{notifications.some((n) => n.isRead) && (
<button
onClick={handleDeleteAllRead}
className="px-4 py-2 rounded-md text-sm font-medium bg-red-100 text-red-700 hover:bg-red-200 transition-colors"
>
Удалить прочитанные
</button>
)}
</div>
</div>
{/* Push-уведомления */}
{!pushEnabled && 'Notification' in window && pushPermission !== 'denied' && (
<div className="mt-4 p-4 bg-blue-50 border border-blue-200 rounded-md flex items-start gap-3">
<svg className="w-6 h-6 text-blue-600 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
</svg>
<div className="flex-1">
<h3 className="text-sm font-semibold text-blue-900 mb-1">
Подключите Push-уведомления
</h3>
<p className="text-sm text-blue-700 mb-3">
Получайте мгновенные уведомления на компьютер или телефон при важных событиях
</p>
<button
onClick={handleEnablePush}
className="px-4 py-2 rounded-md text-sm font-medium bg-blue-600 text-white hover:bg-blue-700 transition-colors"
>
Включить уведомления
</button>
</div>
</div>
)}
{/* Уведомления заблокированы */}
{pushPermission === 'denied' && (
<div className="mt-4 p-4 bg-red-50 border border-red-200 rounded-md flex items-start gap-3">
<svg className="w-6 h-6 text-red-600 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
</svg>
<div className="flex-1">
<h3 className="text-sm font-semibold text-red-900 mb-1">
Push-уведомления заблокированы
</h3>
<p className="text-sm text-red-700">
Вы заблокировали уведомления для этого сайта. Чтобы включить их, разрешите уведомления в настройках браузера.
</p>
<p className="text-xs text-red-600 mt-2">
Chrome/Edge: Нажмите на иконку замка слева от адресной строки Уведомления Разрешить<br/>
Firefox: Настройки Приватность и защита Разрешения Уведомления Настройки
</p>
</div>
</div>
)}
</div>
{/* Список уведомлений */}
{loading ? (
<div className="flex justify-center items-center py-12">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-ospab-primary"></div>
</div>
) : notifications.length === 0 ? (
<div className="bg-white rounded-lg shadow-sm p-12 text-center">
<svg className="mx-auto h-16 w-16 text-gray-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
</svg>
<h3 className="text-lg font-medium text-gray-900 mb-2">Нет уведомлений</h3>
<p className="text-gray-600">
{filter === 'unread' ? 'Все уведомления прочитаны' : 'У вас пока нет уведомлений'}
</p>
</div>
) : (
<div className="space-y-6">
{Object.entries(groupedNotifications).map(([groupName, groupNotifications]) => {
if (groupNotifications.length === 0) return null;
return (
<div key={groupName}>
<h2 className="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-3">
{groupName}
</h2>
<div className="space-y-2">
{groupNotifications.map((notification) => (
<div
key={notification.id}
className={`bg-white rounded-lg shadow-sm border-l-4 overflow-hidden transition-all ${
notification.isRead ? 'border-transparent' : 'border-ospab-primary'
}`}
>
<div className="p-4">
<div className="flex items-start gap-4">
{/* Цветовой индикатор */}
<div className={`flex-shrink-0 w-3 h-3 rounded-full mt-2 ${
notification.color === 'green' ? 'bg-green-500' :
notification.color === 'blue' ? 'bg-blue-500' :
notification.color === 'orange' ? 'bg-orange-500' :
notification.color === 'red' ? 'bg-red-500' :
notification.color === 'purple' ? 'bg-purple-500' :
'bg-gray-500'
}`}></div>
{/* Контент */}
<div className="flex-1 min-w-0">
<div className="flex items-start justify-between gap-4">
<div className="flex-1">
<h3 className={`text-base font-semibold ${notification.isRead ? 'text-gray-800' : 'text-gray-900'}`}>
{notification.title}
</h3>
<p className="text-gray-600 mt-1">
{notification.message}
</p>
<p className="text-sm text-gray-400 mt-2">
{formatDate(notification.createdAt)}
</p>
</div>
{/* Действия */}
<div className="flex gap-2">
{!notification.isRead && (
<button
onClick={() => handleMarkAsRead(notification.id)}
className="p-2 text-gray-400 hover:text-blue-600 transition-colors"
title="Пометить прочитанным"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
</button>
)}
<button
onClick={() => handleDelete(notification.id)}
className="p-2 text-gray-400 hover:text-red-600 transition-colors"
title="Удалить"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
</div>
</div>
{/* Ссылка для перехода */}
{notification.actionUrl && (
<Link
to={notification.actionUrl}
className="inline-block mt-3 text-sm text-ospab-primary hover:underline"
>
Перейти
</Link>
)}
</div>
</div>
</div>
</div>
))}
</div>
</div>
);
})}
</div>
)}
</div>
</div>
);
};
export default NotificationsPage;

View File

@@ -1,41 +0,0 @@
const notificationsList = [
{
title: "Создание сервера",
description: "Вы получите уведомление при успешном создании нового сервера или контейнера.",
},
{
title: "Списание оплаты за месяц",
description: "Напоминание о предстоящем списании средств за продление тарифа.",
},
{
title: "Истечение срока действия тарифа",
description: "Уведомление о необходимости продлить тариф, чтобы избежать отключения.",
},
{
title: "Ответ на тикет",
description: "Вы получите уведомление, когда оператор ответит на ваш тикет поддержки.",
},
{
title: "Поступление оплаты",
description: "Уведомление о зачислении средств на ваш баланс.",
},
];
const Notifications = () => {
return (
<div className="p-8 bg-white rounded-3xl shadow-xl max-w-xl mx-auto mt-6">
<h2 className="text-2xl font-bold mb-6">Типы уведомлений</h2>
<ul className="space-y-6">
{notificationsList.map((n, idx) => (
<li key={idx} className="bg-gray-50 border border-gray-200 rounded-xl p-4">
<div className="font-semibold text-lg text-ospab-primary mb-1">{n.title}</div>
<div className="text-gray-700 text-sm">{n.description}</div>
</li>
))}
</ul>
<div className="text-gray-400 text-sm mt-8">Настройка каналов уведомлений (email, Telegram) появится позже.</div>
</div>
);
};
export default Notifications;

View File

@@ -3,7 +3,7 @@ import { useParams, useNavigate } from 'react-router-dom';
import axios from 'axios';
import { API_URL } from '../../config/api';
import { Modal } from '../../components/Modal';
import { useToast } from '../../components/Toast';
import { useToast } from '../../hooks/useToast';
interface ServerData {
id: number;
@@ -222,7 +222,7 @@ const ServerPanel: React.FC = () => {
onClick={() => setShowPassword(!showPassword)}
className="text-blue-600 hover:text-blue-800"
>
{showPassword ? '👁️' : '👁️‍🗨️'}
{showPassword ? 'Скрыть' : 'Показать'}
</button>
</div>
</div>
@@ -238,7 +238,7 @@ const ServerPanel: React.FC = () => {
)}
<div className="flex justify-between">
<span className="text-gray-600">Автопродление:</span>
<span>{server.autoRenew ? 'Включено' : 'Выключено'}</span>
<span>{server.autoRenew ? 'Включено' : 'Выключено'}</span>
</div>
</div>
</div>
@@ -288,14 +288,14 @@ const ServerPanel: React.FC = () => {
disabled={actionLoading || server.status === 'running'}
className="px-4 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition"
>
Запустить
Запустить
</button>
<button
onClick={() => handleAction('stop')}
disabled={actionLoading || server.status === 'stopped'}
className="px-4 py-3 bg-gray-600 text-white rounded-lg hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed transition"
>
Остановить
Остановить
</button>
<button
onClick={() => handleAction('restart')}
@@ -325,7 +325,7 @@ const ServerPanel: React.FC = () => {
{/* Danger Zone */}
<div className="bg-red-50 border border-red-200 rounded-lg p-6">
<h2 className="text-xl font-semibold text-red-800 mb-4"> Опасная зона</h2>
<h2 className="text-xl font-semibold text-red-800 mb-4">Опасная зона</h2>
<p className="text-red-700 mb-4">
Удаление сервера - необратимое действие. Все данные будут утеряны!
</p>
@@ -334,7 +334,7 @@ const ServerPanel: React.FC = () => {
disabled={actionLoading}
className="px-6 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed transition"
>
🗑 Удалить сервер
Удалить сервер
</button>
</div>

View File

@@ -1,174 +0,0 @@
import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { API_URL } from '../../config/api';
interface Server {
id: number;
status: string;
createdAt: string;
ipAddress: string | null;
tariff: {
name: string;
price: number;
};
os: {
name: string;
};
nextPaymentDate: string | null;
autoRenew: boolean;
}
const Servers: React.FC = () => {
const [servers, setServers] = useState<Server[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
loadServers();
}, []);
const loadServers = async () => {
try {
setLoading(true);
const token = localStorage.getItem('access_token');
const headers = { Authorization: `Bearer ${token}` };
const response = await axios.get(`${API_URL}/api/auth/me`, { headers });
setServers(response.data.user.servers || []);
setError(null);
} catch (err: any) {
console.error('Ошибка загрузки серверов:', err);
setError('Не удалось загрузить список серверов');
} finally {
setLoading(false);
}
};
const getStatusColor = (status: string) => {
switch (status) {
case 'running':
return 'bg-green-100 text-green-800';
case 'stopped':
return 'bg-gray-100 text-gray-800';
case 'creating':
return 'bg-blue-100 text-blue-800';
case 'suspended':
return 'bg-red-100 text-red-800';
default:
return 'bg-gray-100 text-gray-800';
}
};
const getStatusText = (status: string) => {
switch (status) {
case 'running':
return 'Работает';
case 'stopped':
return 'Остановлен';
case 'creating':
return 'Создаётся';
case 'suspended':
return 'Приостановлен';
default:
return status;
}
};
if (loading) {
return (
<div className="flex items-center justify-center h-screen">
<div className="text-xl text-gray-600">Загрузка...</div>
</div>
);
}
return (
<div className="container mx-auto px-4 py-8">
<div className="flex justify-between items-center mb-6">
<h1 className="text-3xl font-bold text-gray-800">Мои серверы</h1>
<Link
to="/dashboard/checkout"
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition"
>
+ Купить сервер
</Link>
</div>
{error && (
<div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg">
<p className="text-red-800">{error}</p>
</div>
)}
{servers.length === 0 ? (
<div className="bg-white rounded-lg shadow p-8 text-center">
<div className="text-gray-400 text-6xl mb-4">🖥</div>
<h2 className="text-2xl font-semibold text-gray-700 mb-2">
У вас пока нет серверов
</h2>
<p className="text-gray-600 mb-6">
Купите свой первый сервер, чтобы начать работу
</p>
<Link
to="/dashboard/checkout"
className="inline-block px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition"
>
Выбрать тариф
</Link>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{servers.map((server) => (
<div
key={server.id}
className="bg-white rounded-lg shadow hover:shadow-lg transition p-6"
>
<div className="flex justify-between items-start mb-4">
<div>
<h3 className="text-xl font-semibold text-gray-800">
Сервер #{server.id}
</h3>
<span className={`inline-block px-2 py-1 rounded text-xs font-medium mt-2 ${getStatusColor(server.status)}`}>
{getStatusText(server.status)}
</span>
</div>
</div>
<div className="space-y-2 mb-4 text-sm text-gray-600">
<p>
<span className="font-medium">Тариф:</span> {server.tariff.name}
</p>
<p>
<span className="font-medium">ОС:</span> {server.os.name}
</p>
<p>
<span className="font-medium">IP:</span> {server.ipAddress || 'Н/Д'}
</p>
{server.nextPaymentDate && (
<p>
<span className="font-medium">След. платёж:</span>{' '}
{new Date(server.nextPaymentDate).toLocaleDateString('ru-RU')}
</p>
)}
<p>
<span className="font-medium">Автопродление:</span>{' '}
{server.autoRenew ? '✅ Включено' : '❌ Выключено'}
</p>
</div>
<Link
to={`/dashboard/server/${server.id}`}
className="block w-full text-center px-4 py-2 bg-gray-800 text-white rounded-lg hover:bg-gray-900 transition"
>
Управление
</Link>
</div>
))}
</div>
)}
</div>
);
};
export default Servers;

View File

@@ -0,0 +1,436 @@
import { useState, useEffect, useCallback } from "react";
import axios from "axios";
import { API_URL } from "../../config/api";
import { Modal } from "../../components/Modal";
import { useToast } from "../../hooks/useToast";
interface AccountInfo {
id: number;
email: string;
username: string;
}
const Settings = () => {
const { addToast } = useToast();
const [tab, setTab] = useState<'password' | 'username' | 'delete'>('password');
const [accountInfo, setAccountInfo] = useState<AccountInfo | null>(null);
const [loading, setLoading] = useState(true);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
// Password change states
const [currentPassword, setCurrentPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [passwordCode, setPasswordCode] = useState("");
const [passwordCodeSent, setPasswordCodeSent] = useState(false);
// Username change states
const [newUsername, setNewUsername] = useState("");
const [usernameCode, setUsernameCode] = useState("");
const [usernameCodeSent, setUsernameCodeSent] = useState(false);
// Delete account states
const [deleteCode, setDeleteCode] = useState("");
const [deleteCodeSent, setDeleteCodeSent] = useState(false);
const [message, setMessage] = useState<{ text: string; type: 'success' | 'error' } | null>(null);
const showMessage = useCallback((text: string, type: 'success' | 'error') => {
setMessage({ text, type });
setTimeout(() => setMessage(null), 5000);
}, []);
const fetchAccountInfo = useCallback(async () => {
try {
const token = localStorage.getItem('access_token');
const response = await axios.get(`${API_URL}/api/account/info`, {
headers: { Authorization: `Bearer ${token}` }
});
setAccountInfo(response.data);
} catch (error) {
const err = error as { response?: { data?: { error?: string } } };
showMessage(err.response?.data?.error || 'Ошибка загрузки данных', 'error');
} finally {
setLoading(false);
}
}, [showMessage]);
useEffect(() => {
fetchAccountInfo();
}, [fetchAccountInfo]);
// Password change handlers
const handleRequestPasswordChange = async (e: React.FormEvent) => {
e.preventDefault();
if (newPassword !== confirmPassword) {
showMessage('Пароли не совпадают', 'error');
return;
}
if (newPassword.length < 6) {
showMessage('Пароль должен быть не менее 6 символов', 'error');
return;
}
try {
const token = localStorage.getItem('access_token');
await axios.post(`${API_URL}/api/account/password/request`, {
currentPassword,
newPassword
}, {
headers: { Authorization: `Bearer ${token}` }
});
setPasswordCodeSent(true);
showMessage('Код отправлен на вашу почту', 'success');
} catch (error) {
const err = error as { response?: { data?: { error?: string } } };
showMessage(err.response?.data?.error || 'Ошибка отправки кода', 'error');
}
};
const handleConfirmPasswordChange = async (e: React.FormEvent) => {
e.preventDefault();
try {
const token = localStorage.getItem('access_token');
await axios.post(`${API_URL}/api/account/password/confirm`, {
code: passwordCode
}, {
headers: { Authorization: `Bearer ${token}` }
});
showMessage('Пароль успешно изменён', 'success');
setPasswordCodeSent(false);
setCurrentPassword("");
setNewPassword("");
setConfirmPassword("");
setPasswordCode("");
} catch (error) {
const err = error as { response?: { data?: { error?: string } } };
showMessage(err.response?.data?.error || 'Неверный код', 'error');
}
};
// Username change handlers
const handleRequestUsernameChange = async (e: React.FormEvent) => {
e.preventDefault();
if (newUsername.length < 3 || newUsername.length > 20) {
showMessage('Имя должно быть от 3 до 20 символов', 'error');
return;
}
if (!/^[a-zA-Z0-9_-]+$/.test(newUsername)) {
showMessage('Имя может содержать только буквы, цифры, _ и -', 'error');
return;
}
try {
const token = localStorage.getItem('access_token');
await axios.post(`${API_URL}/api/account/username/request`, {
newUsername
}, {
headers: { Authorization: `Bearer ${token}` }
});
setUsernameCodeSent(true);
showMessage('Код отправлен на вашу почту', 'success');
} catch (error) {
const err = error as { response?: { data?: { error?: string } } };
showMessage(err.response?.data?.error || 'Ошибка отправки кода', 'error');
}
};
const handleConfirmUsernameChange = async (e: React.FormEvent) => {
e.preventDefault();
try {
const token = localStorage.getItem('access_token');
await axios.post(`${API_URL}/api/account/username/confirm`, {
code: usernameCode
}, {
headers: { Authorization: `Bearer ${token}` }
});
showMessage('Имя успешно изменено', 'success');
setUsernameCodeSent(false);
setNewUsername("");
setUsernameCode("");
await fetchAccountInfo();
} catch (error) {
const err = error as { response?: { data?: { error?: string } } };
showMessage(err.response?.data?.error || 'Неверный код', 'error');
}
};
// Delete account handlers
const handleRequestAccountDeletion = async (e: React.FormEvent) => {
e.preventDefault();
setShowDeleteConfirm(true);
};
const confirmAccountDeletion = async () => {
setShowDeleteConfirm(false);
try {
const token = localStorage.getItem('access_token');
await axios.post(`${API_URL}/api/account/delete/request`, {}, {
headers: { Authorization: `Bearer ${token}` }
});
setDeleteCodeSent(true);
addToast('Код отправлен на вашу почту', 'success');
} catch (error) {
const err = error as { response?: { data?: { error?: string } } };
addToast(err.response?.data?.error || 'Ошибка отправки кода', 'error');
}
};
const handleConfirmAccountDeletion = async (e: React.FormEvent) => {
e.preventDefault();
try {
const token = localStorage.getItem('access_token');
await axios.post(`${API_URL}/api/account/delete/confirm`, {
code: deleteCode
}, {
headers: { Authorization: `Bearer ${token}` }
});
showMessage('Аккаунт удалён', 'success');
localStorage.removeItem('access_token');
setTimeout(() => {
window.location.href = '/';
}, 2000);
} catch (error) {
const err = error as { response?: { data?: { error?: string } } };
showMessage(err.response?.data?.error || 'Неверный код', 'error');
}
};
if (loading) {
return (
<div className="p-4 lg:p-8 bg-white rounded-3xl shadow-xl max-w-2xl mx-auto mt-6">
<p className="text-center text-gray-500">Загрузка...</p>
</div>
);
}
return (
<div className="p-4 lg:p-8 bg-white rounded-3xl shadow-xl max-w-2xl mx-auto mt-6">
<h2 className="text-xl lg:text-2xl font-bold mb-4 lg:mb-6">Настройки аккаунта</h2>
{message && (
<div className={`mb-4 p-3 rounded-lg ${message.type === 'success' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
{message.text}
</div>
)}
{accountInfo && (
<div className="mb-6 p-4 bg-gray-50 rounded-lg">
<p className="text-sm text-gray-600">Email: <span className="font-semibold text-gray-900">{accountInfo.email}</span></p>
<p className="text-sm text-gray-600 mt-1">Имя: <span className="font-semibold text-gray-900">{accountInfo.username}</span></p>
</div>
)}
<div className="flex flex-col sm:flex-row sm:space-x-2 space-y-2 sm:space-y-0 mb-6">
<button
type="button"
className={`px-4 py-2 rounded-lg font-semibold text-sm lg:text-base ${tab === 'password' ? 'bg-ospab-primary text-white' : 'bg-gray-100 text-gray-700'}`}
onClick={() => setTab('password')}
>
Смена пароля
</button>
<button
type="button"
className={`px-4 py-2 rounded-lg font-semibold text-sm lg:text-base ${tab === 'username' ? 'bg-ospab-primary text-white' : 'bg-gray-100 text-gray-700'}`}
onClick={() => setTab('username')}
>
Смена имени
</button>
<button
type="button"
className={`px-4 py-2 rounded-lg font-semibold text-sm lg:text-base ${tab === 'delete' ? 'bg-red-600 text-white' : 'bg-gray-100 text-gray-700'}`}
onClick={() => setTab('delete')}
>
Удалить аккаунт
</button>
</div>
{tab === 'password' && (
<div>
{!passwordCodeSent ? (
<form onSubmit={handleRequestPasswordChange} className="space-y-4">
<div>
<label className="block text-gray-700 mb-2 text-sm lg:text-base">Текущий пароль</label>
<input
type="password"
value={currentPassword}
onChange={e => setCurrentPassword(e.target.value)}
className="w-full px-4 py-2 border rounded-lg text-sm lg:text-base"
required
/>
</div>
<div>
<label className="block text-gray-700 mb-2 text-sm lg:text-base">Новый пароль (минимум 6 символов)</label>
<input
type="password"
value={newPassword}
onChange={e => setNewPassword(e.target.value)}
className="w-full px-4 py-2 border rounded-lg text-sm lg:text-base"
required
minLength={6}
/>
</div>
<div>
<label className="block text-gray-700 mb-2 text-sm lg:text-base">Подтвердите новый пароль</label>
<input
type="password"
value={confirmPassword}
onChange={e => setConfirmPassword(e.target.value)}
className="w-full px-4 py-2 border rounded-lg text-sm lg:text-base"
required
/>
</div>
<button type="submit" className="w-full lg:w-auto bg-ospab-primary text-white px-6 py-2 rounded-lg font-bold text-sm lg:text-base">
Отправить код на почту
</button>
</form>
) : (
<form onSubmit={handleConfirmPasswordChange} className="space-y-4">
<div>
<label className="block text-gray-700 mb-2 text-sm lg:text-base">Введите код из письма</label>
<input
type="text"
value={passwordCode}
onChange={e => setPasswordCode(e.target.value)}
className="w-full px-4 py-2 border rounded-lg text-sm lg:text-base"
placeholder="123456"
required
maxLength={6}
/>
</div>
<div className="flex flex-col sm:flex-row space-y-2 sm:space-y-0 sm:space-x-4">
<button type="submit" className="w-full sm:w-auto bg-ospab-primary text-white px-6 py-2 rounded-lg font-bold text-sm lg:text-base">
Подтвердить
</button>
<button
type="button"
onClick={() => setPasswordCodeSent(false)}
className="w-full sm:w-auto bg-gray-300 text-gray-700 px-6 py-2 rounded-lg font-bold text-sm lg:text-base"
>
Отмена
</button>
</div>
</form>
)}
</div>
)}
{tab === 'username' && (
<div>
{!usernameCodeSent ? (
<form onSubmit={handleRequestUsernameChange} className="space-y-4">
<div>
<label className="block text-gray-700 mb-2 text-sm lg:text-base">Новое имя пользователя</label>
<input
type="text"
value={newUsername}
onChange={e => setNewUsername(e.target.value)}
className="w-full px-4 py-2 border rounded-lg text-sm lg:text-base"
placeholder={accountInfo?.username}
required
minLength={3}
maxLength={20}
pattern="[a-zA-Z0-9_-]+"
/>
<p className="text-xs text-gray-500 mt-1">От 3 до 20 символов, только буквы, цифры, _ и -</p>
</div>
<button type="submit" className="w-full lg:w-auto bg-ospab-primary text-white px-6 py-2 rounded-lg font-bold text-sm lg:text-base">
Отправить код на почту
</button>
</form>
) : (
<form onSubmit={handleConfirmUsernameChange} className="space-y-4">
<div>
<label className="block text-gray-700 mb-2 text-sm lg:text-base">Введите код из письма</label>
<input
type="text"
value={usernameCode}
onChange={e => setUsernameCode(e.target.value)}
className="w-full px-4 py-2 border rounded-lg text-sm lg:text-base"
placeholder="123456"
required
maxLength={6}
/>
</div>
<div className="flex flex-col sm:flex-row space-y-2 sm:space-y-0 sm:space-x-4">
<button type="submit" className="w-full sm:w-auto bg-ospab-primary text-white px-6 py-2 rounded-lg font-bold text-sm lg:text-base">
Подтвердить
</button>
<button
type="button"
onClick={() => setUsernameCodeSent(false)}
className="w-full sm:w-auto bg-gray-300 text-gray-700 px-6 py-2 rounded-lg font-bold text-sm lg:text-base"
>
Отмена
</button>
</div>
</form>
)}
</div>
)}
{tab === 'delete' && (
<div>
{!deleteCodeSent ? (
<form onSubmit={handleRequestAccountDeletion} className="space-y-4">
<div className="p-4 bg-red-50 border border-red-200 rounded-lg">
<p className="text-red-700 font-semibold mb-2">Внимание!</p>
<p className="text-red-600 text-sm">Удаление аккаунта приведёт к безвозвратному удалению всех ваших данных: серверов, тикетов, чеков и уведомлений.</p>
</div>
<button type="submit" className="w-full lg:w-auto bg-red-600 text-white px-6 py-2 rounded-lg font-bold text-sm lg:text-base">
Удалить аккаунт
</button>
</form>
) : (
<form onSubmit={handleConfirmAccountDeletion} className="space-y-4">
<div>
<label className="block text-gray-700 mb-2 text-sm lg:text-base">Введите код из письма для подтверждения</label>
<input
type="text"
value={deleteCode}
onChange={e => setDeleteCode(e.target.value)}
className="w-full px-4 py-2 border rounded-lg text-sm lg:text-base"
placeholder="123456"
required
maxLength={6}
/>
</div>
<div className="flex flex-col sm:flex-row space-y-2 sm:space-y-0 sm:space-x-4">
<button type="submit" className="w-full sm:w-auto bg-red-600 text-white px-6 py-2 rounded-lg font-bold text-sm lg:text-base">
Подтвердить удаление
</button>
<button
type="button"
onClick={() => setDeleteCodeSent(false)}
className="w-full sm:w-auto bg-gray-300 text-gray-700 px-6 py-2 rounded-lg font-bold text-sm lg:text-base"
>
Отмена
</button>
</div>
</form>
)}
</div>
)}
{/* Модальное окно подтверждения удаления аккаунта */}
<Modal
isOpen={showDeleteConfirm}
onClose={() => setShowDeleteConfirm(false)}
title="Удаление аккаунта"
type="danger"
onConfirm={confirmAccountDeletion}
confirmText="Да, удалить аккаунт"
cancelText="Отмена"
>
<p className="font-bold text-red-600 mb-2">ВЫ УВЕРЕНЫ?</p>
<p>Это действие необратимо!</p>
<p className="mt-2 text-sm text-gray-600">
После подтверждения на вашу почту будет отправлен код для финального подтверждения удаления.
</p>
</Modal>
</div>
);
};
export default Settings;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,281 @@
import React, { useState, useEffect } from 'react';
import apiClient from '../../../utils/apiClient';
interface Session {
id: number;
device: string;
browser: string;
ipAddress: string;
location: string;
lastActivity: string;
createdAt: string;
isCurrent: boolean;
}
interface LoginHistory {
id: number;
ipAddress: string;
userAgent: string;
success: boolean;
createdAt: string;
}
const SessionsPage: React.FC = () => {
const [sessions, setSessions] = useState<Session[]>([]);
const [loginHistory, setLoginHistory] = useState<LoginHistory[]>([]);
const [loading, setLoading] = useState(true);
const [showHistory, setShowHistory] = useState(false);
useEffect(() => {
fetchSessions();
fetchLoginHistory();
}, []);
const fetchSessions = async () => {
try {
const response = await apiClient.get('/api/sessions');
const sessionsData = Array.isArray(response.data) ? response.data : response.data.sessions;
setSessions(sessionsData || []);
setLoading(false);
} catch (error) {
console.error('Ошибка загрузки сессий:', error);
setLoading(false);
}
};
const fetchLoginHistory = async () => {
try {
const response = await apiClient.get('/api/sessions/history', {
params: { limit: 20 }
});
const historyData = Array.isArray(response.data) ? response.data : response.data.history;
setLoginHistory(historyData || []);
} catch (error) {
console.error('Ошибка загрузки истории входов:', error);
}
};
const terminateSession = async (sessionId: number) => {
if (!confirm('Вы уверены, что хотите завершить эту сессию?')) return;
try {
await apiClient.delete(`/api/sessions/${sessionId}`);
fetchSessions();
} catch (error) {
console.error('Ошибка завершения сессии:', error);
alert('Не удалось завершить сессию');
}
};
const terminateAllOthers = async () => {
if (!confirm('Вы уверены, что хотите завершить все остальные сессии?')) return;
try {
await apiClient.delete('/api/sessions/others/all');
fetchSessions();
alert('Все остальные сессии завершены');
} catch (error) {
console.error('Ошибка завершения сессий:', error);
alert('Не удалось завершить сессии');
}
};
const getDeviceIcon = (device: string) => {
switch (device.toLowerCase()) {
case 'mobile':
return '📱';
case 'tablet':
return '📱';
case 'desktop':
default:
return '💻';
}
};
const formatRelativeTime = (dateString: string) => {
const date = new Date(dateString);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMs / 3600000);
const diffDays = Math.floor(diffMs / 86400000);
if (diffMins < 1) return 'только что';
if (diffMins < 60) return `${diffMins} мин. назад`;
if (diffHours < 24) return `${diffHours} ч. назад`;
if (diffDays < 7) return `${diffDays} дн. назад`;
return date.toLocaleDateString('ru-RU');
};
if (loading) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto"></div>
<p className="mt-4 text-gray-600">Загрузка сессий...</p>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-50 py-8">
<div className="max-w-6xl mx-auto px-4">
{/* Header */}
<div className="mb-8">
<h1 className="text-3xl font-bold text-gray-900 mb-2">Активные сессии</h1>
<p className="text-gray-600">Управляйте устройствами, с которых выполнен вход в ваш аккаунт</p>
</div>
{/* Terminate All Button */}
{sessions.filter(s => !s.isCurrent).length > 0 && (
<div className="mb-6">
<button
onClick={terminateAllOthers}
className="bg-orange-500 hover:bg-orange-600 text-white px-6 py-3 rounded-lg font-medium transition-colors duration-200 flex items-center gap-2"
>
Завершить все остальные сессии
</button>
</div>
)}
{/* Sessions Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-12">
{sessions.map((session) => (
<div
key={session.id}
className={`bg-white rounded-xl shadow-md overflow-hidden transition-all duration-200 hover:shadow-lg ${
session.isCurrent ? 'ring-2 ring-green-500' : ''
}`}
>
<div className="p-6">
{/* Current Badge */}
{session.isCurrent && (
<div className="mb-3">
<span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800">
Текущая сессия
</span>
</div>
)}
{/* Device Info */}
<div className="flex items-start gap-4">
<div className="text-4xl">{getDeviceIcon(session.device)}</div>
<div className="flex-1">
<h3 className="text-lg font-semibold text-gray-900 mb-1">
{session.browser} · {session.device}
</h3>
<div className="space-y-1 text-sm text-gray-600">
<p className="flex items-center gap-2">
<span>{session.ipAddress}</span>
</p>
<p className="flex items-center gap-2">
<span>{session.location}</span>
</p>
<p className="flex items-center gap-2">
<span>Активность: {formatRelativeTime(session.lastActivity)}</span>
</p>
<p className="flex items-center gap-2 text-gray-500">
<span>Вход: {new Date(session.createdAt).toLocaleString('ru-RU')}</span>
</p>
</div>
</div>
</div>
{/* Terminate Button */}
{!session.isCurrent && (
<div className="mt-4 pt-4 border-t border-gray-200">
<button
onClick={() => terminateSession(session.id)}
className="w-full bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg font-medium transition-colors duration-200"
>
Завершить сессию
</button>
</div>
)}
</div>
</div>
))}
</div>
{/* Login History Section */}
<div className="bg-white rounded-xl shadow-md overflow-hidden">
<div className="p-6 border-b border-gray-200">
<button
onClick={() => setShowHistory(!showHistory)}
className="w-full flex items-center justify-between text-left"
>
<div>
<h2 className="text-xl font-bold text-gray-900">История входов</h2>
<p className="text-sm text-gray-600 mt-1">Последние 20 попыток входа в аккаунт</p>
</div>
<span className="text-2xl">{showHistory ? '▼' : '▶'}</span>
</button>
</div>
{showHistory && (
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Статус
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
IP адрес
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Устройство
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Дата и время
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{loginHistory.map((entry) => (
<tr key={entry.id} className={entry.success ? '' : 'bg-red-50'}>
<td className="px-6 py-4 whitespace-nowrap">
<span
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
entry.success
? 'bg-green-100 text-green-800'
: 'bg-red-100 text-red-800'
}`}
>
{entry.success ? 'Успешно' : 'Ошибка'}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{entry.ipAddress}
</td>
<td className="px-6 py-4 text-sm text-gray-600">
{entry.userAgent.substring(0, 60)}...
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-600">
{new Date(entry.createdAt).toLocaleString('ru-RU')}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
{/* Security Tips */}
<div className="mt-8 bg-blue-50 border border-blue-200 rounded-lg p-6">
<h3 className="text-lg font-semibold text-blue-900 mb-3">💡 Советы по безопасности</h3>
<ul className="space-y-2 text-sm text-blue-800">
<li> Регулярно проверяйте список активных сессий</li>
<li> Завершайте сессии на устройствах, которыми больше не пользуетесь</li>
<li> Если вы видите подозрительную активность, немедленно завершите все сессии и смените пароль</li>
<li> Используйте надёжные пароли и двухфакторную аутентификацию</li>
</ul>
</div>
</div>
</div>
);
};
export default SessionsPage;

View File

@@ -0,0 +1,215 @@
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { FiDatabase, FiPlus, FiInfo, FiTrash2, FiSettings, FiExternalLink } from 'react-icons/fi';
import apiClient from '../../utils/apiClient';
import { API_URL } from '../../config/api';
interface StorageBucket {
id: number;
name: string;
plan: string;
quotaGb: number;
usedBytes: number;
objectCount: number;
storageClass: string;
region: string;
public: boolean;
versioning: boolean;
createdAt: string;
updatedAt: string;
}
const StoragePage: React.FC = () => {
const [buckets, setBuckets] = useState<StorageBucket[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const navigate = useNavigate();
useEffect(() => {
fetchBuckets();
}, []);
const fetchBuckets = async () => {
try {
setLoading(true);
const res = await apiClient.get(`${API_URL}/api/storage/buckets`);
setBuckets(res.data.buckets || []);
} catch (e) {
console.error('Ошибка загрузки бакетов', e);
setError('Не удалось загрузить список хранилищ');
} finally {
setLoading(false);
}
};
const formatBytes = (bytes: number): string => {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
};
const getUsagePercent = (usedBytes: number, quotaGb: number): number => {
const quotaBytes = quotaGb * 1024 * 1024 * 1024;
return quotaBytes > 0 ? Math.min((usedBytes / quotaBytes) * 100, 100) : 0;
};
const getPlanColor = (plan: string): string => {
const colors: Record<string, string> = {
basic: 'text-blue-600 bg-blue-50',
standard: 'text-green-600 bg-green-50',
plus: 'text-purple-600 bg-purple-50',
pro: 'text-orange-600 bg-orange-50',
enterprise: 'text-red-600 bg-red-50'
};
return colors[plan] || 'text-gray-600 bg-gray-50';
};
return (
<div className="max-w-7xl mx-auto">
{/* Header */}
<div className="mb-6 flex items-center justify-between flex-wrap gap-4">
<div>
<h1 className="text-3xl font-bold text-gray-800 flex items-center gap-2">
<FiDatabase className="text-ospab-primary" />
S3 Хранилище
</h1>
<p className="text-gray-600 mt-1">Управление вашими объектными хранилищами</p>
</div>
<div className="flex gap-3">
<button
onClick={() => navigate('/tariffs')}
className="px-5 py-2.5 bg-white border-2 border-ospab-primary text-ospab-primary rounded-lg font-semibold hover:bg-ospab-primary hover:text-white transition-all flex items-center gap-2"
>
<FiInfo />
Тарифы
</button>
<button
onClick={() => navigate('/tariffs')}
className="px-5 py-2.5 bg-ospab-primary text-white rounded-lg font-semibold hover:bg-ospab-primary/90 shadow-lg transition-all flex items-center gap-2"
>
<FiPlus />
Создать бакет
</button>
</div>
</div>
{error && (
<div className="bg-red-50 border border-red-200 rounded-xl p-4 mb-6 text-red-700">
{error}
</div>
)}
{loading ? (
<div className="flex justify-center items-center h-64">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-ospab-primary"></div>
</div>
) : buckets.length === 0 ? (
<div className="bg-white rounded-xl shadow-md p-12 text-center">
<FiDatabase className="text-6xl text-gray-300 mx-auto mb-4" />
<h3 className="text-xl font-bold text-gray-800 mb-2">Нет активных хранилищ</h3>
<p className="text-gray-600 mb-6">Создайте ваш первый S3 бакет для хранения файлов, резервных копий и медиа-контента</p>
<button
onClick={() => navigate('/tariffs')}
className="px-6 py-3 bg-ospab-primary text-white rounded-lg font-semibold hover:bg-ospab-primary/90 shadow-lg transition-all inline-flex items-center gap-2"
>
<FiPlus />
Выбрать тариф
</button>
</div>
) : (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{buckets.map((bucket) => {
const usagePercent = getUsagePercent(bucket.usedBytes, bucket.quotaGb);
return (
<div key={bucket.id} className="bg-white rounded-xl shadow-md hover:shadow-lg transition-shadow">
<div className="p-6 border-b border-gray-100">
<div className="flex items-start justify-between mb-3">
<div className="flex items-center gap-3">
<div className="bg-ospab-primary/10 p-3 rounded-lg">
<FiDatabase className="text-ospab-primary text-xl" />
</div>
<div>
<h3 className="text-lg font-bold text-gray-800">{bucket.name}</h3>
<span className={`inline-block px-2 py-1 text-xs font-semibold rounded-full ${getPlanColor(bucket.plan)}`}>
{bucket.plan}
</span>
</div>
</div>
<div className="flex gap-2">
<button className="p-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
<FiSettings />
</button>
<button className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors">
<FiTrash2 />
</button>
</div>
</div>
{/* Usage bar */}
<div className="mb-4">
<div className="flex justify-between text-sm text-gray-600 mb-1">
<span>Использовано: {formatBytes(bucket.usedBytes)}</span>
<span>Квота: {bucket.quotaGb} GB</span>
</div>
<div className="w-full bg-gray-200 rounded-full h-2">
<div
className={`h-2 rounded-full transition-all ${
usagePercent > 90 ? 'bg-red-500' : usagePercent > 70 ? 'bg-yellow-500' : 'bg-green-500'
}`}
style={{ width: `${usagePercent}%` }}
></div>
</div>
<p className="text-xs text-gray-500 mt-1">{usagePercent.toFixed(1)}% использовано</p>
</div>
{/* Stats */}
<div className="grid grid-cols-3 gap-4 mb-4">
<div className="text-center">
<p className="text-2xl font-bold text-ospab-primary">{bucket.objectCount}</p>
<p className="text-xs text-gray-500">Объектов</p>
</div>
<div className="text-center">
<p className="text-sm font-semibold text-gray-700">{bucket.region}</p>
<p className="text-xs text-gray-500">Регион</p>
</div>
<div className="text-center">
<p className="text-sm font-semibold text-gray-700">{bucket.storageClass}</p>
<p className="text-xs text-gray-500">Класс</p>
</div>
</div>
{/* Badges */}
<div className="flex gap-2 flex-wrap">
{bucket.public && (
<span className="inline-flex items-center px-2 py-1 bg-blue-100 text-blue-700 text-xs font-semibold rounded-full">
Публичный
</span>
)}
{bucket.versioning && (
<span className="inline-flex items-center px-2 py-1 bg-purple-100 text-purple-700 text-xs font-semibold rounded-full">
Версионирование
</span>
)}
</div>
</div>
<div className="px-6 py-4 bg-gray-50 flex justify-between items-center">
<p className="text-xs text-gray-500">
Создан: {new Date(bucket.createdAt).toLocaleDateString('ru-RU')}
</p>
<button className="text-ospab-primary hover:text-ospab-primary/80 font-semibold text-sm flex items-center gap-1">
Открыть <FiExternalLink />
</button>
</div>
</div>
);
})}
</div>
)}
</div>
);
};
export default StoragePage;

View File

@@ -1,35 +1,27 @@
import { Link } from 'react-router-dom';
import type { UserData, Ticket, Server } from './types';
import type { UserData, Ticket } from './types';
interface SummaryProps {
userData: UserData;
}
const Summary = ({ userData }: SummaryProps) => {
// Фильтрация открытых тикетов и активных серверов
// Фильтрация открытых тикетов
const openTickets = Array.isArray(userData.tickets)
? userData.tickets.filter((t: Ticket) => t.status !== 'closed')
: [];
const activeServers = Array.isArray(userData.servers)
? userData.servers.filter((s: Server) => s.status === 'active')
: [];
return (
<div className="p-4 lg:p-8 bg-white rounded-2xl lg:rounded-3xl shadow-xl">
<h2 className="text-2xl lg:text-3xl font-bold text-gray-800 mb-4 lg:mb-6">Сводка по аккаунту</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 lg:gap-6 mb-6 lg:mb-8">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 lg:gap-6 mb-6 lg:mb-8">
<div className="bg-gray-100 p-4 lg:p-6 rounded-xl lg:rounded-2xl flex flex-col items-start">
<p className="text-lg lg:text-xl font-medium text-gray-700">Баланс:</p>
<p className="text-3xl lg:text-4xl font-extrabold text-ospab-primary mt-2 break-words"> {userData.balance?.toFixed ? userData.balance.toFixed(2) : Number(userData.balance).toFixed(2)}</p>
<Link to="/dashboard/billing" className="text-sm text-gray-500 hover:underline mt-2">Пополнить баланс </Link>
</div>
<div className="bg-gray-100 p-4 lg:p-6 rounded-xl lg:rounded-2xl flex flex-col items-start">
<p className="text-lg lg:text-xl font-medium text-gray-700">Активные серверы:</p>
<p className="text-3xl lg:text-4xl font-extrabold text-gray-800 mt-2">{activeServers.length}</p>
<Link to="/dashboard/servers" className="text-sm text-gray-500 hover:underline mt-2">Управлять </Link>
</div>
<div className="bg-gray-100 p-4 lg:p-6 rounded-xl lg:rounded-2xl flex flex-col items-start md:col-span-2 lg:col-span-1">
<p className="text-lg lg:text-xl font-medium text-gray-700">Открытые тикеты:</p>
<p className="text-3xl lg:text-4xl font-extrabold text-gray-800 mt-2">{openTickets.length}</p>
<Link to="/dashboard/tickets" className="text-sm text-gray-500 hover:underline mt-2">Служба поддержки </Link>

View File

@@ -1,5 +1,5 @@
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import apiClient from '../../utils/apiClient';
interface Response {
id: number;
@@ -31,16 +31,9 @@ const TicketResponse: React.FC = () => {
const fetchTickets = async () => {
setError('');
try {
const token = localStorage.getItem('access_token');
const res = await axios.get('https://ospab.host:5000/api/ticket', {
withCredentials: true,
headers: token ? { Authorization: `Bearer ${token}` } : {}
});
if (Array.isArray(res.data)) {
setTickets(res.data);
} else {
setTickets([]);
}
const res = await apiClient.get('/api/ticket');
const data = Array.isArray(res.data) ? res.data : res.data?.tickets;
setTickets(data || []);
} catch {
setError('Ошибка загрузки тикетов');
setTickets([]);
@@ -51,13 +44,9 @@ const TicketResponse: React.FC = () => {
setLoading(true);
setError('');
try {
const token = localStorage.getItem('access_token');
await axios.post('https://ospab.host:5000/api/ticket/respond', {
await apiClient.post('/api/ticket/respond', {
ticketId,
message: responseMsg[ticketId]
}, {
withCredentials: true,
headers: token ? { Authorization: `Bearer ${token}` } : {}
});
setResponseMsg(prev => ({ ...prev, [ticketId]: '' }));
fetchTickets();
@@ -73,11 +62,7 @@ const TicketResponse: React.FC = () => {
setLoading(true);
setError('');
try {
const token = localStorage.getItem('access_token');
await axios.post('https://ospab.host:5000/api/ticket/close', { ticketId }, {
withCredentials: true,
headers: token ? { Authorization: `Bearer ${token}` } : {}
});
await apiClient.post('/api/ticket/close', { ticketId });
fetchTickets();
} catch {
setError('Ошибка закрытия тикета');

View File

@@ -1,217 +1,282 @@
import type { UserData, Ticket } from './types';
import type { UserData } from './types';
import React, { useEffect, useState } from 'react';
import useAuth from '../../context/useAuth';
import axios from 'axios';
import { Link, useNavigate } from 'react-router-dom';
import apiClient from '../../utils/apiClient';
// Глобальный логгер ошибок для axios
axios.interceptors.response.use(
response => response,
error => {
if (error.response) {
console.error('Ошибка ответа:', error.response.data);
} else if (error.request) {
console.error('Нет ответа от сервера:', error.request);
} else {
console.error('Ошибка запроса:', error.message);
}
return Promise.reject(error);
}
);
interface Ticket {
id: number;
title: string;
message: string;
status: string;
priority: string;
category: string;
createdAt: string;
updatedAt: string;
responses?: Response[];
assignedTo?: number;
closedAt?: string;
}
interface Response {
id: number;
message: string;
isInternal: boolean;
createdAt: string;
userId: number;
user: {
username: string;
operator: boolean;
};
}
type TicketsPageProps = {
setUserData: (data: UserData) => void;
};
const TicketsPage: React.FC<TicketsPageProps> = ({ setUserData }) => {
const { user } = useAuth() as { user?: { username: string; operator?: number } };
const TicketsPage: React.FC<TicketsPageProps> = () => {
const navigate = useNavigate();
const [tickets, setTickets] = useState<Ticket[]>([]);
const [title, setTitle] = useState('');
const [message, setMessage] = useState('');
const [formError, setFormError] = useState('');
const [formSuccess, setFormSuccess] = useState('');
const [loading, setLoading] = useState(false);
const [responseMsg, setResponseMsg] = useState('');
const [loading, setLoading] = useState(true);
const [filters, setFilters] = useState({
status: 'all',
category: 'all',
priority: 'all'
});
useEffect(() => {
fetchTickets();
}, []);
fetchTickets();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [filters]);
const fetchTickets = async () => {
try {
const token = localStorage.getItem('access_token');
const res = await axios.get('https://ospab.host:5000/api/ticket', {
withCredentials: true,
headers: token ? { Authorization: `Bearer ${token}` } : {}
});
if (Array.isArray(res.data)) {
setTickets(res.data);
} else {
setTickets([]);
}
} catch {
const params: Record<string, string> = {};
if (filters.status !== 'all') params.status = filters.status;
if (filters.category !== 'all') params.category = filters.category;
if (filters.priority !== 'all') params.priority = filters.priority;
const response = await apiClient.get('/api/ticket', { params });
setTickets(response.data.tickets || response.data || []);
setLoading(false);
} catch (error) {
console.error('Ошибка загрузки тикетов:', error);
setTickets([]);
}
};
const updateUserData = async () => {
try {
const token = localStorage.getItem('access_token');
if (!token) return;
const headers = { Authorization: `Bearer ${token}` };
const userRes = await axios.get('https://ospab.host:5000/api/auth/me', { headers });
setUserData({
user: userRes.data.user,
balance: userRes.data.user.balance ?? 0,
servers: userRes.data.user.servers ?? [],
tickets: userRes.data.user.tickets ?? [],
});
} catch (err) {
console.error('Ошибка обновления userData после тикета:', err);
}
};
const createTicket = async (e: React.FormEvent) => {
e.preventDefault();
setFormError('');
setFormSuccess('');
if (!title.trim() || !message.trim()) {
setFormError('Заполните тему и сообщение');
return;
}
setLoading(true);
try {
const token = localStorage.getItem('access_token');
await axios.post('https://ospab.host:5000/api/ticket/create', { title, message }, {
withCredentials: true,
headers: token ? { Authorization: `Bearer ${token}` } : {}
});
setTitle('');
setMessage('');
setFormSuccess('Тикет успешно создан!');
fetchTickets();
await updateUserData();
} catch {
setFormError('Ошибка создания тикета');
} finally {
setLoading(false);
}
};
const respondTicket = async (ticketId: number) => {
const token = localStorage.getItem('access_token');
await axios.post('https://ospab.host:5000/api/ticket/respond', { ticketId, message: responseMsg }, {
withCredentials: true,
headers: token ? { Authorization: `Bearer ${token}` } : {}
});
setResponseMsg('');
fetchTickets();
await updateUserData();
const getStatusBadge = (status: string) => {
const badges: Record<string, { color: string; text: string; emoji: string }> = {
open: { color: 'bg-green-100 text-green-800', text: 'Открыт', emoji: '🟢' },
in_progress: { color: 'bg-blue-100 text-blue-800', text: 'В работе', emoji: '🔵' },
awaiting_reply: { color: 'bg-yellow-100 text-yellow-800', text: 'Ожидает ответа', emoji: '🟡' },
resolved: { color: 'bg-purple-100 text-purple-800', text: 'Решён', emoji: '🟣' },
closed: { color: 'bg-gray-100 text-gray-800', text: 'Закрыт', emoji: '⚪' }
};
const badge = badges[status] || badges.open;
return (
<span className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-medium ${badge.color}`}>
<span>{badge.emoji}</span>
<span>{badge.text}</span>
</span>
);
};
const closeTicket = async (ticketId: number) => {
const token = localStorage.getItem('access_token');
await axios.post('https://ospab.host:5000/api/ticket/close', { ticketId }, {
withCredentials: true,
headers: token ? { Authorization: `Bearer ${token}` } : {}
});
fetchTickets();
await updateUserData();
const getPriorityBadge = (priority: string) => {
const badges: Record<string, { color: string; text: string; emoji: string }> = {
urgent: { color: 'bg-red-100 text-red-800 border-red-300', text: 'Срочно', emoji: '🔴' },
high: { color: 'bg-orange-100 text-orange-800 border-orange-300', text: 'Высокий', emoji: '🟠' },
normal: { color: 'bg-gray-100 text-gray-800 border-gray-300', text: 'Обычный', emoji: '⚪' },
low: { color: 'bg-green-100 text-green-800 border-green-300', text: 'Низкий', emoji: '🟢' }
};
const badge = badges[priority] || badges.normal;
return (
<span className={`inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium border ${badge.color}`}>
<span>{badge.emoji}</span>
<span>{badge.text}</span>
</span>
);
};
const getCategoryIcon = (category: string) => {
const icons: Record<string, string> = {
general: '💬',
technical: '⚙️',
billing: '💰',
other: '📝'
};
return icons[category] || icons.general;
};
const formatRelativeTime = (dateString: string) => {
const date = new Date(dateString);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMs / 3600000);
const diffDays = Math.floor(diffMs / 86400000);
if (diffMins < 1) return 'только что';
if (diffMins < 60) return `${diffMins} мин. назад`;
if (diffHours < 24) return `${diffHours} ч. назад`;
if (diffDays < 7) return `${diffDays} дн. назад`;
return date.toLocaleDateString('ru-RU');
};
if (loading) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto"></div>
<p className="mt-4 text-gray-600">Загрузка тикетов...</p>
</div>
</div>
);
}
return (
<div className="p-8 bg-white rounded-3xl shadow-xl">
<h2 className="text-3xl font-bold text-gray-800 mb-6">Мои тикеты</h2>
<form onSubmit={createTicket} className="mb-8 max-w-xl bg-gray-50 rounded-2xl shadow p-6 flex flex-col gap-4">
<label className="font-semibold text-lg">Тема тикета</label>
<input
value={title}
onChange={e => setTitle(e.target.value)}
placeholder="Введите тему..."
className="border rounded-xl p-3 focus:outline-blue-400 text-base"
/>
<label className="font-semibold text-lg">Сообщение</label>
<textarea
value={message}
onChange={e => setMessage(e.target.value)}
placeholder="Опишите проблему или вопрос..."
className="border rounded-xl p-3 min-h-[80px] resize-y focus:outline-blue-400 text-base"
/>
{formError && <div className="text-red-500 text-sm">{formError}</div>}
{formSuccess && <div className="text-green-600 text-sm">{formSuccess}</div>}
<button
type="submit"
className={`bg-blue-500 text-white px-6 py-3 rounded-xl hover:bg-blue-600 transition text-lg font-semibold ${loading ? 'opacity-50 cursor-not-allowed' : ''}`}
disabled={loading}
>
{loading ? 'Отправка...' : 'Создать тикет'}
</button>
</form>
<div className="space-y-8">
{tickets.map(ticket => (
<div key={ticket.id} className="border rounded-2xl p-6 shadow flex flex-col">
<div className="flex flex-col md:flex-row md:items-center justify-between mb-2">
<div className="font-bold text-xl text-blue-900">{ticket.title}</div>
<div className="text-sm text-gray-500">Статус: <span className={ticket.status === 'closed' ? 'text-red-600 font-bold' : 'text-green-600 font-bold'}>{ticket.status === 'closed' ? 'Закрыт' : 'Открыт'}</span></div>
<div className="min-h-screen bg-gray-50 py-8">
<div className="max-w-7xl mx-auto px-4">
{/* Header */}
<div className="flex items-center justify-between mb-8">
<div>
<h1 className="text-3xl font-bold text-gray-900 mb-2">Тикеты поддержки</h1>
<p className="text-gray-600">Управляйте вашими обращениями в службу поддержки</p>
</div>
<button
onClick={() => navigate('/dashboard/tickets/new')}
className="bg-blue-500 hover:bg-blue-600 text-white px-6 py-3 rounded-lg font-medium transition-colors duration-200 flex items-center gap-2"
>
<span></span>
Создать тикет
</button>
</div>
{/* Filters */}
<div className="bg-white rounded-xl shadow-md p-6 mb-6">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
{/* Status Filter */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Статус</label>
<select
value={filters.status}
onChange={(e) => setFilters({ ...filters, status: e.target.value })}
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
>
<option value="all">Все статусы</option>
<option value="open">Открыт</option>
<option value="in_progress">В работе</option>
<option value="awaiting_reply">Ожидает ответа</option>
<option value="resolved">Решён</option>
<option value="closed">Закрыт</option>
</select>
</div>
<div className="text-sm text-gray-400 mb-2">Автор: {ticket.user?.username} | {new Date(ticket.createdAt).toLocaleString()}</div>
{/* Чат сообщений */}
<div className="flex flex-col gap-2 mb-4">
<div className="flex items-start gap-2">
<div className="bg-blue-100 text-blue-900 px-3 py-2 rounded-xl max-w-xl">
<span className="font-semibold">{ticket.user?.username || 'Клиент'}:</span> {ticket.message}
</div>
</div>
{((Array.isArray(ticket.responses) ? ticket.responses : []) as {
id: number;
operator?: { username?: string };
message: string;
createdAt: string;
}[]).map((r) => (
<div key={r.id} className="flex items-start gap-2">
<div className="bg-green-100 text-green-900 px-3 py-2 rounded-xl max-w-xl ml-8">
<span className="font-semibold">{r.operator?.username || 'Оператор'}:</span> {r.message}
<span className="text-gray-400 ml-2 text-xs">{new Date(r.createdAt).toLocaleString()}</span>
{/* Category Filter */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Категория</label>
<select
value={filters.category}
onChange={(e) => setFilters({ ...filters, category: e.target.value })}
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
>
<option value="all">Все категории</option>
<option value="general">Общие вопросы</option>
<option value="technical">Технические</option>
<option value="billing">Биллинг</option>
<option value="other">Другое</option>
</select>
</div>
{/* Priority Filter */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Приоритет</label>
<select
value={filters.priority}
onChange={(e) => setFilters({ ...filters, priority: e.target.value })}
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
>
<option value="all">Все приоритеты</option>
<option value="urgent">Срочно</option>
<option value="high">Высокий</option>
<option value="normal">Обычный</option>
<option value="low">Низкий</option>
</select>
</div>
</div>
</div>
{/* Tickets Grid */}
{tickets.length === 0 ? (
<div className="bg-white rounded-xl shadow-md p-12 text-center">
<div className="text-6xl mb-4">📭</div>
<h3 className="text-xl font-semibold text-gray-900 mb-2">Нет тикетов</h3>
<p className="text-gray-600 mb-6">У вас пока нет открытых тикетов поддержки</p>
<button
onClick={() => navigate('/dashboard/tickets/new')}
className="bg-blue-500 hover:bg-blue-600 text-white px-6 py-3 rounded-lg font-medium transition-colors duration-200"
>
Создать первый тикет
</button>
</div>
) : (
<div className="grid grid-cols-1 gap-6">
{tickets.map((ticket) => (
<Link
key={ticket.id}
to={`/dashboard/tickets/${ticket.id}`}
className="bg-white rounded-xl shadow-md hover:shadow-lg transition-all duration-200 overflow-hidden"
>
<div className="p-6">
{/* Header */}
<div className="flex items-start justify-between mb-4">
<div className="flex-1">
<div className="flex items-center gap-3 mb-2">
<span className="text-2xl">{getCategoryIcon(ticket.category || 'general')}</span>
<h3 className="text-xl font-semibold text-gray-900">{ticket.title}</h3>
{getPriorityBadge(ticket.priority || 'normal')}
</div>
<p className="text-gray-600 line-clamp-2">{ticket.message.substring(0, 150)}...</p>
</div>
<div className="ml-4">
{getStatusBadge(ticket.status)}
</div>
</div>
{/* Footer */}
<div className="flex items-center justify-between pt-4 border-t border-gray-200">
<div className="flex items-center gap-4 text-sm text-gray-600">
<span className="flex items-center gap-1">
<span>🕒</span>
<span>{formatRelativeTime(ticket.updatedAt)}</span>
</span>
<span className="flex items-center gap-1">
<span>💬</span>
<span>{ticket.responses?.length || 0} ответов</span>
</span>
{ticket.closedAt && (
<span className="flex items-center gap-1">
<span>🔒</span>
<span>Закрыт</span>
</span>
)}
</div>
<span className="text-blue-500 hover:text-blue-600 font-medium">
Открыть
</span>
</div>
</div>
))}
</div>
{/* Форма ответа и кнопка закрытия */}
{ticket.status !== 'closed' && (
<div className="flex flex-col md:flex-row items-center gap-2 mt-2">
{user?.operator === 1 && (
<>
<input
value={responseMsg}
onChange={e => setResponseMsg(e.target.value)}
placeholder="Ваш ответ..."
className="border rounded-xl p-2 flex-1"
disabled={loading}
/>
<button
type="button"
onClick={() => respondTicket(ticket.id)}
className="bg-green-500 text-white px-4 py-2 rounded-xl hover:bg-green-600 transition"
disabled={loading || !(responseMsg && responseMsg.trim())}
>
{loading ? 'Отправка...' : 'Ответить'}
</button>
</>
)}
<button
type="button"
onClick={() => closeTicket(ticket.id)}
className="bg-red-500 text-white px-4 py-2 rounded-xl hover:bg-red-600 transition"
disabled={loading}
>
Закрыть тикет
</button>
</div>
)}
{ticket.status === 'closed' && (
<div className="text-red-600 font-bold mt-2">Тикет закрыт</div>
)}
</Link>
))}
</div>
))}
)}
</div>
</div>
);

View File

@@ -0,0 +1,278 @@
import React, { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import apiClient from '../../../utils/apiClient';
interface Ticket {
id: number;
title: string;
message: string;
status: string;
priority: string;
category: string;
createdAt: string;
updatedAt: string;
closedAt?: string;
assignedTo?: number;
user: {
id: number;
username: string;
};
}
interface Response {
id: number;
message: string;
isInternal: boolean;
createdAt: string;
user: {
id: number;
username: string;
operator: boolean;
};
}
const TicketDetailPage: React.FC = () => {
const { id } = useParams<{ id: string }>();
const [ticket, setTicket] = useState<Ticket | null>(null);
const [responses, setResponses] = useState<Response[]>([]);
const [loading, setLoading] = useState(true);
const [newMessage, setNewMessage] = useState('');
const [sending, setSending] = useState(false);
useEffect(() => {
fetchTicket();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id]);
const fetchTicket = async () => {
try {
const response = await apiClient.get(`/api/ticket/${id}`);
setTicket(response.data.ticket);
setResponses(response.data.ticket.responses || []);
setLoading(false);
} catch (error) {
console.error('Ошибка загрузки тикета:', error);
setLoading(false);
}
};
const sendResponse = async () => {
if (!newMessage.trim()) return;
setSending(true);
try {
await apiClient.post('/api/ticket/respond', {
ticketId: id,
message: newMessage
});
setNewMessage('');
fetchTicket();
} catch (error) {
console.error('Ошибка отправки ответа:', error);
alert('Не удалось отправить ответ');
} finally {
setSending(false);
}
};
const closeTicket = async () => {
if (!confirm('Вы уверены, что хотите закрыть этот тикет?')) return;
try {
await apiClient.post('/api/ticket/close', { ticketId: id });
fetchTicket();
alert('Тикет успешно закрыт');
} catch (error) {
console.error('Ошибка закрытия тикета:', error);
alert('Не удалось закрыть тикет');
}
};
const getStatusBadge = (status: string) => {
const badges: Record<string, { color: string; text: string; emoji: string }> = {
open: { color: 'bg-green-100 text-green-800', text: 'Открыт', emoji: '🟢' },
in_progress: { color: 'bg-blue-100 text-blue-800', text: 'В работе', emoji: '🔵' },
awaiting_reply: { color: 'bg-yellow-100 text-yellow-800', text: 'Ожидает ответа', emoji: '🟡' },
resolved: { color: 'bg-purple-100 text-purple-800', text: 'Решён', emoji: '🟣' },
closed: { color: 'bg-gray-100 text-gray-800', text: 'Закрыт', emoji: '⚪' }
};
const badge = badges[status] || badges.open;
return (
<span className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-sm font-medium ${badge.color}`}>
<span>{badge.emoji}</span>
<span>{badge.text}</span>
</span>
);
};
const getPriorityBadge = (priority: string) => {
const badges: Record<string, { color: string; text: string }> = {
urgent: { color: 'bg-red-100 text-red-800', text: 'Срочно 🔴' },
high: { color: 'bg-orange-100 text-orange-800', text: 'Высокий 🟠' },
normal: { color: 'bg-gray-100 text-gray-800', text: 'Обычный ⚪' },
low: { color: 'bg-green-100 text-green-800', text: 'Низкий 🟢' }
};
const badge = badges[priority] || badges.normal;
return (
<span className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${badge.color}`}>
{badge.text}
</span>
);
};
if (loading) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto"></div>
<p className="mt-4 text-gray-600">Загрузка тикета...</p>
</div>
</div>
);
}
if (!ticket) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center">
<div className="text-6xl mb-4"></div>
<h2 className="text-2xl font-bold text-gray-900 mb-2">Тикет не найден</h2>
<Link
to="/dashboard/tickets"
className="text-blue-500 hover:text-blue-600 font-medium"
>
Вернуться к списку тикетов
</Link>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-50 py-8">
<div className="max-w-4xl mx-auto px-4">
{/* Back Button */}
<Link
to="/dashboard/tickets"
className="inline-flex items-center gap-2 text-gray-600 hover:text-gray-900 mb-6 transition-colors"
>
<span></span>
<span>Назад к тикетам</span>
</Link>
{/* Ticket Header */}
<div className="bg-white rounded-xl shadow-md p-6 mb-6">
<div className="flex items-start justify-between mb-4">
<div className="flex-1">
<h1 className="text-2xl font-bold text-gray-900 mb-2">{ticket.title}</h1>
<div className="flex items-center gap-3">
{getStatusBadge(ticket.status)}
{getPriorityBadge(ticket.priority)}
<span className="text-sm text-gray-600">
Категория: {ticket.category}
</span>
</div>
</div>
{ticket.status !== 'closed' && (
<button
onClick={closeTicket}
className="bg-gray-500 hover:bg-gray-600 text-white px-4 py-2 rounded-lg font-medium transition-colors duration-200"
>
Закрыть тикет
</button>
)}
</div>
<div className="border-t border-gray-200 pt-4 mt-4">
<p className="text-gray-700 whitespace-pre-wrap">{ticket.message}</p>
</div>
<div className="flex items-center gap-4 mt-4 text-sm text-gray-600">
<span>Создан: {new Date(ticket.createdAt).toLocaleString('ru-RU')}</span>
{ticket.closedAt && (
<span>Закрыт: {new Date(ticket.closedAt).toLocaleString('ru-RU')}</span>
)}
</div>
</div>
{/* Responses */}
<div className="space-y-4 mb-6">
{responses.map((response) => (
<div
key={response.id}
className={`bg-white rounded-xl shadow-md p-6 ${
response.isInternal ? 'bg-yellow-50 border-2 border-yellow-200' : ''
}`}
>
<div className="flex items-start gap-4">
<div className="w-10 h-10 bg-blue-500 rounded-full flex items-center justify-center text-white font-bold">
{response.user.username.charAt(0).toUpperCase()}
</div>
<div className="flex-1">
<div className="flex items-center gap-2 mb-2">
<span className="font-semibold text-gray-900">
{response.user.username}
</span>
{response.user.operator && (
<span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800">
Оператор
</span>
)}
{response.isInternal && (
<span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800">
🔒 Внутренний комментарий
</span>
)}
<span className="text-sm text-gray-600">
{new Date(response.createdAt).toLocaleString('ru-RU')}
</span>
</div>
<p className="text-gray-700 whitespace-pre-wrap">{response.message}</p>
</div>
</div>
</div>
))}
</div>
{/* New Response Form */}
{ticket.status !== 'closed' && (
<div className="bg-white rounded-xl shadow-md p-6">
<h3 className="text-lg font-semibold text-gray-900 mb-4">Добавить ответ</h3>
<textarea
value={newMessage}
onChange={(e) => setNewMessage(e.target.value)}
placeholder="Введите ваш ответ..."
className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
rows={5}
/>
<div className="flex items-center justify-end gap-3 mt-4">
<button
onClick={() => setNewMessage('')}
className="px-6 py-2 text-gray-700 hover:text-gray-900 font-medium transition-colors"
disabled={sending}
>
Очистить
</button>
<button
onClick={sendResponse}
disabled={sending || !newMessage.trim()}
className="bg-blue-500 hover:bg-blue-600 text-white px-6 py-2 rounded-lg font-medium transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
>
{sending ? 'Отправка...' : 'Отправить'}
</button>
</div>
</div>
)}
</div>
</div>
);
};
export default TicketDetailPage;

View File

@@ -0,0 +1,278 @@
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import apiClient from '../../../utils/apiClient';
interface Ticket {
id: number;
title: string;
message: string;
status: string;
priority: string;
category: string;
createdAt: string;
updatedAt: string;
responses: Response[];
assignedTo?: number;
closedAt?: string;
}
interface Response {
id: number;
message: string;
isInternal: boolean;
createdAt: string;
userId: number;
user: {
username: string;
operator: boolean;
};
}
const TicketsPage: React.FC = () => {
const [tickets, setTickets] = useState<Ticket[]>([]);
const [loading, setLoading] = useState(true);
const [filters, setFilters] = useState({
status: 'all',
category: 'all',
priority: 'all'
});
useEffect(() => {
fetchTickets();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [filters]);
const fetchTickets = async () => {
try {
const params: Record<string, string> = {};
if (filters.status !== 'all') params.status = filters.status;
if (filters.category !== 'all') params.category = filters.category;
if (filters.priority !== 'all') params.priority = filters.priority;
const response = await apiClient.get('/api/ticket', { params });
setTickets(response.data.tickets || []);
setLoading(false);
} catch (error) {
console.error('Ошибка загрузки тикетов:', error);
setLoading(false);
}
};
const getStatusBadge = (status: string) => {
const badges: Record<string, { color: string; text: string; emoji: string }> = {
open: { color: 'bg-green-100 text-green-800', text: 'Открыт', emoji: '🟢' },
in_progress: { color: 'bg-blue-100 text-blue-800', text: 'В работе', emoji: '🔵' },
awaiting_reply: { color: 'bg-yellow-100 text-yellow-800', text: 'Ожидает ответа', emoji: '🟡' },
resolved: { color: 'bg-purple-100 text-purple-800', text: 'Решён', emoji: '🟣' },
closed: { color: 'bg-gray-100 text-gray-800', text: 'Закрыт', emoji: '⚪' }
};
const badge = badges[status] || badges.open;
return (
<span className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-medium ${badge.color}`}>
<span>{badge.emoji}</span>
<span>{badge.text}</span>
</span>
);
};
const getPriorityBadge = (priority: string) => {
const badges: Record<string, { color: string; text: string; emoji: string }> = {
urgent: { color: 'bg-red-100 text-red-800 border-red-300', text: 'Срочно', emoji: '🔴' },
high: { color: 'bg-orange-100 text-orange-800 border-orange-300', text: 'Высокий', emoji: '🟠' },
normal: { color: 'bg-gray-100 text-gray-800 border-gray-300', text: 'Обычный', emoji: '⚪' },
low: { color: 'bg-green-100 text-green-800 border-green-300', text: 'Низкий', emoji: '🟢' }
};
const badge = badges[priority] || badges.normal;
return (
<span className={`inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium border ${badge.color}`}>
<span>{badge.emoji}</span>
<span>{badge.text}</span>
</span>
);
};
const getCategoryIcon = (category: string) => {
const icons: Record<string, string> = {
general: '💬',
technical: '⚙️',
billing: '💰',
other: '📝'
};
return icons[category] || icons.general;
};
const formatRelativeTime = (dateString: string) => {
const date = new Date(dateString);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMs / 3600000);
const diffDays = Math.floor(diffMs / 86400000);
if (diffMins < 1) return 'только что';
if (diffMins < 60) return `${diffMins} мин. назад`;
if (diffHours < 24) return `${diffHours} ч. назад`;
if (diffDays < 7) return `${diffDays} дн. назад`;
return date.toLocaleDateString('ru-RU');
};
if (loading) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto"></div>
<p className="mt-4 text-gray-600">Загрузка тикетов...</p>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-50 py-8">
<div className="max-w-7xl mx-auto px-4">
{/* Header */}
<div className="flex items-center justify-between mb-8">
<div>
<h1 className="text-3xl font-bold text-gray-900 mb-2">Тикеты поддержки</h1>
<p className="text-gray-600">Управляйте вашими обращениями в службу поддержки</p>
</div>
<Link
to="/dashboard/tickets/new"
className="bg-blue-500 hover:bg-blue-600 text-white px-6 py-3 rounded-lg font-medium transition-colors duration-200 flex items-center gap-2"
>
<span></span>
Создать тикет
</Link>
</div>
{/* Filters */}
<div className="bg-white rounded-xl shadow-md p-6 mb-6">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
{/* Status Filter */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Статус</label>
<select
value={filters.status}
onChange={(e) => setFilters({ ...filters, status: e.target.value })}
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
>
<option value="all">Все статусы</option>
<option value="open">Открыт</option>
<option value="in_progress">В работе</option>
<option value="awaiting_reply">Ожидает ответа</option>
<option value="resolved">Решён</option>
<option value="closed">Закрыт</option>
</select>
</div>
{/* Category Filter */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Категория</label>
<select
value={filters.category}
onChange={(e) => setFilters({ ...filters, category: e.target.value })}
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
>
<option value="all">Все категории</option>
<option value="general">Общие вопросы</option>
<option value="technical">Технические</option>
<option value="billing">Биллинг</option>
<option value="other">Другое</option>
</select>
</div>
{/* Priority Filter */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Приоритет</label>
<select
value={filters.priority}
onChange={(e) => setFilters({ ...filters, priority: e.target.value })}
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
>
<option value="all">Все приоритеты</option>
<option value="urgent">Срочно</option>
<option value="high">Высокий</option>
<option value="normal">Обычный</option>
<option value="low">Низкий</option>
</select>
</div>
</div>
</div>
{/* Tickets Grid */}
{tickets.length === 0 ? (
<div className="bg-white rounded-xl shadow-md p-12 text-center">
<div className="text-6xl mb-4">📭</div>
<h3 className="text-xl font-semibold text-gray-900 mb-2">Нет тикетов</h3>
<p className="text-gray-600 mb-6">У вас пока нет открытых тикетов поддержки</p>
<Link
to="/dashboard/tickets/new"
className="inline-block bg-blue-500 hover:bg-blue-600 text-white px-6 py-3 rounded-lg font-medium transition-colors duration-200"
>
Создать первый тикет
</Link>
</div>
) : (
<div className="grid grid-cols-1 gap-6">
{tickets.map((ticket) => (
<Link
key={ticket.id}
to={`/dashboard/tickets/${ticket.id}`}
className="bg-white rounded-xl shadow-md hover:shadow-lg transition-all duration-200 overflow-hidden"
>
<div className="p-6">
{/* Header */}
<div className="flex items-start justify-between mb-4">
<div className="flex-1">
<div className="flex items-center gap-3 mb-2">
<span className="text-2xl">{getCategoryIcon(ticket.category)}</span>
<h3 className="text-xl font-semibold text-gray-900">{ticket.title}</h3>
{getPriorityBadge(ticket.priority)}
</div>
<p className="text-gray-600 line-clamp-2">{ticket.message.substring(0, 150)}...</p>
</div>
<div className="ml-4">
{getStatusBadge(ticket.status)}
</div>
</div>
{/* Footer */}
<div className="flex items-center justify-between pt-4 border-t border-gray-200">
<div className="flex items-center gap-4 text-sm text-gray-600">
<span className="flex items-center gap-1">
<span>🕒</span>
<span>{formatRelativeTime(ticket.updatedAt)}</span>
</span>
<span className="flex items-center gap-1">
<span>💬</span>
<span>{ticket.responses?.length || 0} ответов</span>
</span>
{ticket.closedAt && (
<span className="flex items-center gap-1">
<span>🔒</span>
<span>Закрыт</span>
</span>
)}
</div>
<span className="text-blue-500 hover:text-blue-600 font-medium">
Открыть
</span>
</div>
</div>
</Link>
))}
</div>
)}
</div>
</div>
);
};
export default TicketsPage;

View File

@@ -0,0 +1,166 @@
import React, { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import apiClient from '../../../utils/apiClient';
const NewTicketPage: React.FC = () => {
const navigate = useNavigate();
const [formData, setFormData] = useState({
title: '',
message: '',
category: 'general',
priority: 'normal'
});
const [sending, setSending] = useState(false);
const [error, setError] = useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!formData.title.trim() || !formData.message.trim()) {
setError('Заполните все поля');
return;
}
setSending(true);
setError('');
try {
const response = await apiClient.post('/api/ticket/create', formData);
// Перенаправляем на созданный тикет
navigate(`/dashboard/tickets/${response.data.ticket.id}`);
} catch (err) {
console.error('Ошибка создания тикета:', err);
setError('Не удалось создать тикет. Попробуйте ещё раз.');
setSending(false);
}
};
return (
<div className="min-h-screen bg-gray-50 py-8">
<div className="max-w-3xl mx-auto px-4">
{/* Back Button */}
<Link
to="/dashboard/tickets"
className="inline-flex items-center gap-2 text-gray-600 hover:text-gray-900 mb-6 transition-colors"
>
<span></span>
<span>Назад к тикетам</span>
</Link>
{/* Form */}
<div className="bg-white rounded-xl shadow-md p-8">
<h1 className="text-2xl font-bold text-gray-900 mb-6">Создать новый тикет</h1>
{error && (
<div className="mb-6 bg-red-50 border border-red-200 text-red-800 px-4 py-3 rounded-lg">
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-6">
{/* Title */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Тема <span className="text-red-500">*</span>
</label>
<input
type="text"
value={formData.title}
onChange={(e) => setFormData({ ...formData, title: e.target.value })}
placeholder="Кратко опишите вашу проблему"
className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
required
/>
</div>
{/* Category and Priority */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* Category */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Категория
</label>
<select
value={formData.category}
onChange={(e) => setFormData({ ...formData, category: e.target.value })}
className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
>
<option value="general">💬 Общие вопросы</option>
<option value="technical"> Технические</option>
<option value="billing">💰 Биллинг</option>
<option value="other">📝 Другое</option>
</select>
</div>
{/* Priority */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Приоритет
</label>
<select
value={formData.priority}
onChange={(e) => setFormData({ ...formData, priority: e.target.value })}
className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
>
<option value="low">🟢 Низкий</option>
<option value="normal"> Обычный</option>
<option value="high">🟠 Высокий</option>
<option value="urgent">🔴 Срочно</option>
</select>
</div>
</div>
{/* Message */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Описание <span className="text-red-500">*</span>
</label>
<textarea
value={formData.message}
onChange={(e) => setFormData({ ...formData, message: e.target.value })}
placeholder="Подробно опишите вашу проблему или вопрос..."
className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
rows={8}
required
/>
<p className="mt-2 text-sm text-gray-500">
Минимум 10 символов. Чем подробнее вы опишете проблему, тем быстрее мы сможем помочь.
</p>
</div>
{/* Info Box */}
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
<h3 className="text-sm font-semibold text-blue-900 mb-2">💡 Советы:</h3>
<ul className="text-sm text-blue-800 space-y-1">
<li> Укажите все детали проблемы</li>
<li> Приложите скриншоты, если возможно</li>
<li> Опишите шаги для воспроизведения ошибки</li>
<li> Среднее время ответа: 2-4 часа</li>
</ul>
</div>
{/* Actions */}
<div className="flex items-center justify-end gap-4">
<Link
to="/dashboard/tickets"
className="px-6 py-3 text-gray-700 hover:text-gray-900 font-medium transition-colors"
>
Отмена
</Link>
<button
type="submit"
disabled={sending}
className="bg-blue-500 hover:bg-blue-600 text-white px-8 py-3 rounded-lg font-medium transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
>
{sending ? 'Создание...' : 'Создать тикет'}
</button>
</div>
</form>
</div>
</div>
</div>
);
};
export default NewTicketPage;

View File

@@ -1,7 +1,12 @@
export interface User {
id?: number;
username: string;
email?: string;
operator: number;
isAdmin?: boolean;
balance?: number;
tickets?: Ticket[];
buckets?: StorageBucket[];
}
export interface Ticket {
@@ -14,16 +19,23 @@ export interface Ticket {
user?: { username: string };
}
export interface Server {
export interface StorageBucket {
id: number;
name: string;
status: string;
// можно добавить другие поля по необходимости
plan: string;
quotaGb: number;
usedBytes: number;
objectCount: number;
storageClass: string;
region: string;
public: boolean;
versioning: boolean;
createdAt: string;
updatedAt: string;
}
export interface UserData {
user: User;
balance: number;
servers: Server[];
tickets: Ticket[];
}